-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
Copy patheditorAccessor.ts
332 lines (278 loc) · 10.9 KB
/
editorAccessor.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { ICommonCodeEditor } from 'vs/editor/common/editorCommon';
import strings = require('vs/base/common/strings');
import { Range } from 'vs/editor/common/core/range';
import { SnippetController2 } from 'vs/editor/contrib/snippet/browser/snippetController2';
import { LanguageId, LanguageIdentifier } from 'vs/editor/common/modes';
import { Position } from 'vs/editor/common/core/position';
import { CoreEditingCommands } from 'vs/editor/common/controller/coreCommands';
import { SnippetParser, walk, Placeholder, Variable, Text, Marker } from 'vs/editor/contrib/snippet/browser/snippetParser';
import emmet = require('emmet');
export interface IGrammarContributions {
getGrammar(mode: string): string;
}
export interface ILanguageIdentifierResolver {
getLanguageIdentifier(modeId: LanguageId): LanguageIdentifier;
}
export class EditorAccessor implements emmet.Editor {
private _languageIdentifierResolver: ILanguageIdentifierResolver;
private _editor: ICommonCodeEditor;
private _syntaxProfiles: any;
private _excludedLanguages: any;
private _grammars: IGrammarContributions;
private _emmetActionName: string;
private _hasMadeEdits: boolean;
private readonly emmetSupportedModes = ['html', 'css', 'xml', 'xsl', 'haml', 'jade', 'jsx', 'slim', 'scss', 'sass', 'less', 'stylus', 'styl', 'svg'];
constructor(languageIdentifierResolver: ILanguageIdentifierResolver, editor: ICommonCodeEditor, syntaxProfiles: any, excludedLanguages: String[], grammars: IGrammarContributions, emmetActionName?: string) {
this._languageIdentifierResolver = languageIdentifierResolver;
this._editor = editor;
this._syntaxProfiles = syntaxProfiles;
this._excludedLanguages = excludedLanguages;
this._hasMadeEdits = false;
this._grammars = grammars;
this._emmetActionName = emmetActionName;
}
public getEmmetSupportedModes(): string[] {
return this.emmetSupportedModes;
}
public isEmmetEnabledMode(): boolean {
return this.emmetSupportedModes.indexOf(this.getSyntax()) !== -1;
}
public getSelectionRange(): emmet.Range {
let selection = this._editor.getSelection();
return {
start: this.getOffsetFromPosition(selection.getStartPosition()),
end: this.getOffsetFromPosition(selection.getEndPosition())
};
}
public getCurrentLineRange(): emmet.Range {
let currentLine = this._editor.getSelection().startLineNumber;
return {
start: this.getOffsetFromPosition(new Position(currentLine, 1)),
end: this.getOffsetFromPosition(new Position(currentLine + 1, 1))
};
}
public getCaretPos(): number {
let selectionStart = this._editor.getSelection().getStartPosition();
return this.getOffsetFromPosition(selectionStart);
}
public setCaretPos(pos: number): void {
this.createSelection(pos);
}
public getCurrentLine(): string {
let selectionStart = this._editor.getSelection().getStartPosition();
return this._editor.getModel().getLineContent(selectionStart.lineNumber);
}
public onBeforeEmmetAction(): void {
this._hasMadeEdits = false;
}
public replaceContent(value: string, start: number, end: number, no_indent: boolean): void {
let range = this.getRangeToReplace(value, start, end);
if (!range) {
return;
}
const tweakedValue = EditorAccessor.fixEmmetFinalTabstop(value);
// let selection define the typing range
this._editor.setSelection(range);
SnippetController2.get(this._editor).insert(tweakedValue);
// let codeSnippet = snippets.CodeSnippet.fromEmmet(value);
// SnippetController.get(this._editor).runWithReplaceRange(codeSnippet, range);
}
private static fixEmmetFinalTabstop(template: string): string {
let matchFinalStops = template.match(/\$\{0\}|\$0/g);
if (!matchFinalStops || matchFinalStops.length === 1) {
return template;
}
// string to string conversion that tries to fix the
// snippet in-place
let marker = new SnippetParser().parse(template);
let maxIndex = -Number.MIN_VALUE;
// find highest placeholder index
walk(marker, candidate => {
if (candidate instanceof Placeholder) {
let index = candidate.index;
if (index > maxIndex) {
maxIndex = index;
}
}
return true;
});
// rewrite final tabstops
walk(marker, candidate => {
if (candidate instanceof Placeholder) {
if (candidate.isFinalTabstop) {
candidate.index = ++maxIndex;
}
}
return true;
});
// write back as string
function toSnippetString(marker: Marker): string {
if (marker instanceof Text) {
return SnippetParser.escape(marker.string);
} else if (marker instanceof Placeholder) {
if (marker.children.length > 0) {
return `\${${marker.index}:${marker.children.map(toSnippetString).join('')}}`;
} else {
return `\$${marker.index}`;
}
} else if (marker instanceof Variable) {
if (marker.children.length > 0) {
return `\${${marker.name}:${marker.children.map(toSnippetString).join('')}}`;
} else {
return `\$${marker.name}`;
}
} else {
throw new Error('unexpected marker: ' + marker);
}
}
return marker.map(toSnippetString).join('');
}
public getRangeToReplace(value: string, start: number, end: number): Range {
//console.log('value', value);
let startPosition = this.getPositionFromOffset(start);
let endPosition = this.getPositionFromOffset(end);
// test if < or </ are located before or > after the replace range. Either replace these too, or block the expansion
var currentLine = this._editor.getModel().getLineContent(startPosition.lineNumber).substr(0, startPosition.column - 1); // content before the replaced range
var match = currentLine.match(/<[/]?$/);
if (match) {
if (strings.startsWith(value, match[0])) {
startPosition = new Position(startPosition.lineNumber, startPosition.column - match[0].length);
} else {
return null; // ignore
}
}
// test if > is located after the replace range. Either replace these too, or block the expansion
if (this._editor.getModel().getLineContent(endPosition.lineNumber).substr(endPosition.column - 1, endPosition.column) === '>') {
if (strings.endsWith(value, '>')) {
endPosition = new Position(endPosition.lineNumber, endPosition.column + 1);
} else {
return null; // ignore
}
}
// If this is the first edit in this "transaction", push an undo stop before them
if (!this._hasMadeEdits) {
this._hasMadeEdits = true;
this._editor.pushUndoStop();
}
let range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
let textToReplace = this._editor.getModel().getValueInRange(range);
// During Expand Abbreviation action, if the expanded abbr is the same as the text it intends to replace,
// then treat it as a no-op and return TAB to the editor
if (this._emmetActionName === 'expand_abbreviation' && (value === textToReplace || value === textToReplace + '${0}')) {
CoreEditingCommands.Tab.runEditorCommand(null, this._editor, null);
return null;
}
return range;
}
public onAfterEmmetAction(): void {
// If there were any edits in this "transaction", push an undo stop after them
if (this._hasMadeEdits) {
this._editor.pushUndoStop();
}
}
public getContent(): string {
return this._editor.getModel().getValue();
}
public createSelection(startOffset: number, endOffset?: number): void {
let startPosition = this.getPositionFromOffset(startOffset);
let endPosition = null;
if (!endOffset) {
endPosition = startPosition;
} else {
endPosition = this.getPositionFromOffset(endOffset);
}
let range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
this._editor.setSelection(range);
this._editor.revealRange(range);
}
public getSyntax(): string {
return this.getSyntaxInternal(true);
}
public getSyntaxInternal(overrideUsingProfiles: boolean): string {
let position = this._editor.getSelection().getStartPosition();
this._editor.getModel().forceTokenization(position.lineNumber);
let languageId = this._editor.getModel().getLanguageIdAtPosition(position.lineNumber, position.column);
let language = this._languageIdentifierResolver.getLanguageIdentifier(languageId).language;
let syntax = language.split('.').pop();
if (this._excludedLanguages.indexOf(syntax) !== -1) {
return '';
}
// user can overwrite the syntax using the emmet syntaxProfiles setting
let profile = this.getSyntaxProfile(syntax);
if (overrideUsingProfiles && profile && this.emmetSupportedModes.indexOf(profile) !== -1) {
return profile;
}
if (this.emmetSupportedModes.indexOf(syntax) !== -1) {
return syntax;
}
if (/\b(typescriptreact|javascriptreact|jsx-tags)\b/.test(syntax)) { // treat tsx like jsx
return 'jsx';
}
if (syntax === 'sass-indented') { // map sass-indented to sass
return 'sass';
}
syntax = this.checkParentMode(syntax);
return syntax;
}
private getSyntaxProfile(syntax: string): string {
const profile = this._syntaxProfiles[syntax];
if (profile && typeof profile === 'string') {
return profile;
}
return undefined;
}
private checkParentMode(syntax: string): string {
let languageGrammar = this._grammars.getGrammar(syntax);
if (!languageGrammar) {
return syntax;
}
let languages = languageGrammar.split('.');
if (languages.length < 2) {
return syntax;
}
for (let i = 1; i < languages.length; i++) {
const language = languages[languages.length - i];
if (this.emmetSupportedModes.indexOf(language) !== -1) {
return language;
}
}
return syntax;
}
// If users have created their own output profile for current syntax as described
// http://docs.emmet.io/customization/syntax-profiles/#create-your-own-profile
// then we return the name of this profile. Else, we send null and
// emmet is smart enough to guess the right output profile
public getProfileName(): string {
let syntax = this.getSyntaxInternal(false);
const profile = this._syntaxProfiles[syntax];
if (profile && typeof profile !== 'string') {
return syntax;
}
return null;
}
public prompt(title: string): any {
//
}
public getSelection(): string {
let selection = this._editor.getSelection();
let model = this._editor.getModel();
let start = selection.getStartPosition();
let end = selection.getEndPosition();
let range = new Range(start.lineNumber, start.column, end.lineNumber, end.column);
return model.getValueInRange(range);
}
public getFilePath(): string {
return this._editor.getModel().uri.fsPath;
}
private getPositionFromOffset(offset: number): Position {
return this._editor.getModel().getPositionAt(offset);
}
private getOffsetFromPosition(position: Position): number {
return this._editor.getModel().getOffsetAt(position);
}
}