filters.rst 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. ===================
  2. Source Code Filters
  3. ===================
  4. .. contents::
  5. A `Source Code Filter (SCF)` transforms the input character stream to an in-memory
  6. output stream before parsing. A filter can be used to provide templating
  7. systems or preprocessors.
  8. To use a filter for a source file the ``#?`` notation is used::
  9. #? stdtmpl(subsChar = '$', metaChar = '#')
  10. #proc generateXML(name, age: string): string =
  11. # result = ""
  12. <xml>
  13. <name>$name</name>
  14. <age>$age</age>
  15. </xml>
  16. As the example shows, passing arguments to a filter can be done
  17. just like an ordinary procedure call with named or positional arguments. The
  18. available parameters depend on the invoked filter. Before version 0.12.0 of
  19. the language ``#!`` was used instead of ``#?``.
  20. **Hint:** With ``--hint[codeBegin]:on`` or ``--verbosity:2``
  21. (or higher) while compiling or `nim check`, Nim lists the processed code after
  22. each filter application.
  23. Usage
  24. =====
  25. First, put your SCF code in a separate file with filters specified in the first line.
  26. **Note:** You can name your SCF file with any file extension you want, but the
  27. conventional extension is ``.nimf``
  28. (it used to be ``.tmpl`` but that was too generic, for example preventing github to
  29. recognize it as Nim source file).
  30. If we use `generateXML` code shown above and call the SCF file `xmlGen.nimf`
  31. In your `main.nim`:
  32. .. code-block:: nim
  33. include "xmlGen.nimf"
  34. echo generateXML("John Smith","42")
  35. Pipe operator
  36. =============
  37. Filters can be combined with the ``|`` pipe operator::
  38. #? strip(startswith="<") | stdtmpl
  39. #proc generateXML(name, age: string): string =
  40. # result = ""
  41. <xml>
  42. <name>$name</name>
  43. <age>$age</age>
  44. </xml>
  45. Available filters
  46. =================
  47. Replace filter
  48. --------------
  49. The replace filter replaces substrings in each line.
  50. Parameters and their defaults:
  51. ``sub: string = ""``
  52. the substring that is searched for
  53. ``by: string = ""``
  54. the string the substring is replaced with
  55. Strip filter
  56. ------------
  57. The strip filter simply removes leading and trailing whitespace from
  58. each line.
  59. Parameters and their defaults:
  60. ``startswith: string = ""``
  61. strip only the lines that start with *startswith* (ignoring leading
  62. whitespace). If empty every line is stripped.
  63. ``leading: bool = true``
  64. strip leading whitespace
  65. ``trailing: bool = true``
  66. strip trailing whitespace
  67. StdTmpl filter
  68. --------------
  69. The stdtmpl filter provides a simple templating engine for Nim. The
  70. filter uses a line based parser: Lines prefixed with a *meta character*
  71. (default: ``#``) contain Nim code, other lines are verbatim. Because
  72. indentation-based parsing is not suited for a templating engine, control flow
  73. statements need ``end X`` delimiters.
  74. Parameters and their defaults:
  75. ``metaChar: char = '#'``
  76. prefix for a line that contains Nim code
  77. ``subsChar: char = '$'``
  78. prefix for a Nim expression within a template line
  79. ``conc: string = " & "``
  80. the operation for concatenation
  81. ``emit: string = "result.add"``
  82. the operation to emit a string literal
  83. ``toString: string = "$"``
  84. the operation that is applied to each expression
  85. Example::
  86. #? stdtmpl | standard
  87. #proc generateHTMLPage(title, currentTab, content: string,
  88. # tabs: openArray[string]): string =
  89. # result = ""
  90. <head><title>$title</title></head>
  91. <body>
  92. <div id="menu">
  93. <ul>
  94. #for tab in items(tabs):
  95. #if currentTab == tab:
  96. <li><a id="selected"
  97. #else:
  98. <li><a
  99. #end if
  100. href="${tab}.html">$tab</a></li>
  101. #end for
  102. </ul>
  103. </div>
  104. <div id="content">
  105. $content
  106. A dollar: $$.
  107. </div>
  108. </body>
  109. The filter transforms this into:
  110. .. code-block:: nim
  111. proc generateHTMLPage(title, currentTab, content: string,
  112. tabs: openArray[string]): string =
  113. result = ""
  114. result.add("<head><title>" & $(title) & "</title></head>\n" &
  115. "<body>\n" &
  116. " <div id=\"menu\">\n" &
  117. " <ul>\n")
  118. for tab in items(tabs):
  119. if currentTab == tab:
  120. result.add(" <li><a id=\"selected\" \n")
  121. else:
  122. result.add(" <li><a\n")
  123. #end
  124. result.add(" href=\"" & $(tab) & ".html\">" & $(tab) & "</a></li>\n")
  125. #end
  126. result.add(" </ul>\n" &
  127. " </div>\n" &
  128. " <div id=\"content\">\n" &
  129. " " & $(content) & "\n" &
  130. " A dollar: $.\n" &
  131. " </div>\n" &
  132. "</body>\n")
  133. Each line that does not start with the meta character (ignoring leading
  134. whitespace) is converted to a string literal that is added to ``result``.
  135. The substitution character introduces a Nim expression *e* within the
  136. string literal. *e* is converted to a string with the *toString* operation
  137. which defaults to ``$``. For strong type checking, set ``toString`` to the
  138. empty string. *e* must match this PEG pattern::
  139. e <- [a-zA-Z\128-\255][a-zA-Z0-9\128-\255_.]* / '{' x '}'
  140. x <- '{' x+ '}' / [^}]*
  141. To produce a single substitution character it has to be doubled: ``$$``
  142. produces ``$``.
  143. The template engine is quite flexible. It is easy to produce a procedure that
  144. writes the template code directly to a file::
  145. #? stdtmpl(emit="f.write") | standard
  146. #proc writeHTMLPage(f: File, title, currentTab, content: string,
  147. # tabs: openArray[string]) =
  148. <head><title>$title</title></head>
  149. <body>
  150. <div id="menu">
  151. <ul>
  152. #for tab in items(tabs):
  153. #if currentTab == tab:
  154. <li><a id="selected"
  155. #else:
  156. <li><a
  157. #end if
  158. href="${tab}.html" title = "$title - $tab">$tab</a></li>
  159. #end for
  160. </ul>
  161. </div>
  162. <div id="content">
  163. $content
  164. A dollar: $$.
  165. </div>
  166. </body>