1 | # Global text helpers
|
2 | #
|
3 | module.exports =
|
4 |
|
5 | # Whitespace helper function.
|
6 | #
|
7 | # @param [Number] n the number if indents
|
8 | # @return [String] the indention string
|
9 | #
|
10 | whitespace: (n) ->
|
11 | n = n * 2
|
12 | a = []
|
13 | while a.length < n
|
14 | a.push ' '
|
15 | a.join ''
|
16 |
|
17 | # Escape quotation in a text.
|
18 | #
|
19 | # @param [String] text the text containing quotes
|
20 | # @return [String] the escaped text
|
21 | #
|
22 | escapeQuotes: (text) ->
|
23 | return '' unless text
|
24 |
|
25 | text.replace(/"/g, '\\"').replace(/\\\\\"/g, '\\"')
|
26 |
|
27 | # Unescape quotation in a text.
|
28 | #
|
29 | # @param [String] text the text containing escaped quotes
|
30 | # @return [String] the text without escaped quotes
|
31 | #
|
32 | unescapeQuotes: (text) ->
|
33 | return '' unless text
|
34 |
|
35 | text.replace(/\\"/g, '"')
|
36 |
|
37 | # HTML Escape a text.
|
38 | #
|
39 | # @param [String] text the text
|
40 | # @return [String] the HTML escaped text
|
41 | #
|
42 | escapeHTML: (text) ->
|
43 | return '' unless text
|
44 |
|
45 | text
|
46 | .replace(/&/g, '&')
|
47 | .replace(/</g, '<')
|
48 | .replace(/>/g, '>')
|
49 | .replace(/\"/g, '"')
|
50 |
|
51 | # Preserve newlines within the preserve tags,
|
52 | #
|
53 | # @param [String] code the code to preserve
|
54 | # @return [String] the preserved code
|
55 | #
|
56 | preserve: (code) ->
|
57 | if code
|
58 | code.replace /<(pre|textarea)>(.*?)<\/\1>/g, (text) ->
|
59 | text.replace('\\n', '\&\#x000A;')
|
60 |
|
61 | # Indent the given text.
|
62 | #
|
63 | # @param [String] text the text to indent
|
64 | # @param [Integer] the amount of spaced to insert
|
65 | # @return [String] the indented text
|
66 | #
|
67 | indent: (text, spaces) ->
|
68 | text.replace /^(.*)$/mg, module.exports.whitespace(spaces) + '$1'
|