1 |
|
2 | Utils = require './Utils'
|
3 | Pattern = require './Pattern'
|
4 |
|
5 | # Unescaper encapsulates unescaping rules for single and double-quoted YAML strings.
|
6 | #
|
7 | class Unescaper
|
8 |
|
9 | # Regex fragment that matches an escaped character in
|
10 | # a double quoted string.
|
11 | @PATTERN_ESCAPED_CHARACTER: new Pattern '\\\\([0abt\tnvfre "\\/\\\\N_LP]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})';
|
12 |
|
13 |
|
14 | # Unescapes a single quoted string.
|
15 | #
|
16 | # @param [String] value A single quoted string.
|
17 | #
|
18 | # @return [String] The unescaped string.
|
19 | #
|
20 | @unescapeSingleQuotedString: (value) ->
|
21 | return value.replace(/\'\'/g, '\'')
|
22 |
|
23 |
|
24 | # Unescapes a double quoted string.
|
25 | #
|
26 | # @param [String] value A double quoted string.
|
27 | #
|
28 | # @return [String] The unescaped string.
|
29 | #
|
30 | @unescapeDoubleQuotedString: (value) ->
|
31 | @_unescapeCallback ?= (str) =>
|
32 | return @unescapeCharacter(str)
|
33 |
|
34 | # Evaluate the string
|
35 | return @PATTERN_ESCAPED_CHARACTER.replace value, @_unescapeCallback
|
36 |
|
37 |
|
38 | # Unescapes a character that was found in a double-quoted string
|
39 | #
|
40 | # @param [String] value An escaped character
|
41 | #
|
42 | # @return [String] The unescaped character
|
43 | #
|
44 | @unescapeCharacter: (value) ->
|
45 | ch = String.fromCharCode
|
46 | switch value.charAt(1)
|
47 | when '0'
|
48 | return ch(0)
|
49 | when 'a'
|
50 | return ch(7)
|
51 | when 'b'
|
52 | return ch(8)
|
53 | when 't'
|
54 | return "\t"
|
55 | when "\t"
|
56 | return "\t"
|
57 | when 'n'
|
58 | return "\n"
|
59 | when 'v'
|
60 | return ch(11)
|
61 | when 'f'
|
62 | return ch(12)
|
63 | when 'r'
|
64 | return ch(13)
|
65 | when 'e'
|
66 | return ch(27)
|
67 | when ' '
|
68 | return ' '
|
69 | when '"'
|
70 | return '"'
|
71 | when '/'
|
72 | return '/'
|
73 | when '\\'
|
74 | return '\\'
|
75 | when 'N'
|
76 | # U+0085 NEXT LINE
|
77 | return ch(0x0085)
|
78 | when '_'
|
79 | # U+00A0 NO-BREAK SPACE
|
80 | return ch(0x00A0)
|
81 | when 'L'
|
82 | # U+2028 LINE SEPARATOR
|
83 | return ch(0x2028)
|
84 | when 'P'
|
85 | # U+2029 PARAGRAPH SEPARATOR
|
86 | return ch(0x2029)
|
87 | when 'x'
|
88 | return Utils.utf8chr(Utils.hexDec(value.substr(2, 2)))
|
89 | when 'u'
|
90 | return Utils.utf8chr(Utils.hexDec(value.substr(2, 4)))
|
91 | when 'U'
|
92 | return Utils.utf8chr(Utils.hexDec(value.substr(2, 8)))
|
93 | else
|
94 | return ''
|
95 |
|
96 | module.exports = Unescaper
|