annotate.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import macros, parseutils
  2. # Generate tags
  3. macro make(names: untyped{nkBracket}): untyped =
  4. result = newStmtList()
  5. for i in 0 .. names.len-1:
  6. result.add newProc(
  7. name = ident($names[i]).postfix("*"),
  8. params = [
  9. ident("string"),
  10. newIdentDefs(
  11. ident("content"),
  12. ident("string")
  13. )
  14. ],
  15. body = newStmtList(
  16. parseStmt("reindent(content)")
  17. )
  18. )
  19. iterator lines(value: string): string =
  20. var i = 0
  21. while i < value.len:
  22. var line: string
  23. inc(i, value.parseUntil(line, 0x0A.char, i) + 1)
  24. yield line
  25. proc reindent*(value: string, preset_indent = 0): string =
  26. var indent = -1
  27. # Detect indentation!
  28. for ln in lines(value):
  29. var read = ln.skipWhitespace()
  30. # If the line is empty, ignore it for indentation
  31. if read == ln.len: continue
  32. indent = if indent < 0: read
  33. else: min(indent, read)
  34. # Create a precursor indent as-needed
  35. var precursor = newString(0)
  36. for i in 1 .. preset_indent:
  37. precursor.add(' ')
  38. # Re-indent
  39. result = newString(0)
  40. for ln in lines(value):
  41. var value = ln.substr(indent)
  42. result.add(precursor)
  43. if value.len > 0:
  44. result.add(value)
  45. result.add(0x0A.char)
  46. return result
  47. #Define tags
  48. make([ html, xml, glsl, js, css, rst ])
  49. when isMainModule:
  50. ## Test tags
  51. const script = js"""
  52. var x = 5;
  53. console.log(x.toString());
  54. """
  55. const styles = css"""
  56. .someRule {
  57. width: 500px;
  58. }
  59. """
  60. const body = html"""
  61. <ul>
  62. <li>1</li>
  63. <li>2</li>
  64. <li>
  65. <a hef="#google">google</a>
  66. </li>
  67. </ul>
  68. """
  69. const info = xml"""
  70. <item>
  71. <i>1</i>
  72. <i>2</i>
  73. </item>
  74. """
  75. const shader = glsl"""
  76. void main()
  77. {
  78. gl_Position = gl_ProjectionMatrix
  79. * gl_ModelViewMatrix
  80. * gl_Vertex;
  81. }
  82. """
  83. echo script
  84. echo styles
  85. echo body
  86. echo info
  87. echo shader