-
-
Notifications
You must be signed in to change notification settings - Fork 960
/
string.ts
98 lines (83 loc) · 2.18 KB
/
string.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict'
export class SnippetString {
public static isSnippetString(thing: any): thing is SnippetString {
if (thing instanceof SnippetString) {
return true
}
if (!thing) {
return false
}
return typeof thing.value === 'string'
}
private static _escape(value: string): string {
return value.replace(/\$|}|\\/g, '\\$&')
}
private _tabstop = 1
public value: string
constructor(value?: string) {
this.value = value || ''
}
public appendText(str: string): SnippetString {
this.value += SnippetString._escape(str)
return this
}
public appendTabstop(num: number = this._tabstop++): SnippetString {
this.value += '$'
this.value += num
return this
}
public appendPlaceholder(
value: string | ((snippet: SnippetString) => any),
num: number = this._tabstop++
): SnippetString {
if (typeof value === 'function') {
const nested = new SnippetString()
nested._tabstop = this._tabstop
value(nested)
this._tabstop = nested._tabstop
value = nested.value
} else {
value = SnippetString._escape(value)
}
this.value += '${'
this.value += num
this.value += ':'
this.value += value
this.value += '}'
return this
}
public appendChoice(
values: string[],
num: number = this._tabstop++
): SnippetString {
const value = values.map(s => s.replace(/\$|}|\\|,/g, '\\$&')).join(',')
this.value += '${'
this.value += num
this.value += '|'
this.value += value
this.value += '|}'
return this
}
public appendVariable(
name: string,
defaultValue?: string | ((snippet: SnippetString) => any)
): SnippetString {
if (typeof defaultValue === 'function') {
const nested = new SnippetString()
nested._tabstop = this._tabstop
defaultValue(nested)
this._tabstop = nested._tabstop
defaultValue = nested.value
} else if (typeof defaultValue === 'string') {
defaultValue = defaultValue.replace(/\$|}/g, '\\$&')
}
this.value += '${'
this.value += name
if (defaultValue) {
this.value += ':'
this.value += defaultValue
}
this.value += '}'
return this
}
}