abbreviationActions.ts 12.1 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
R
Ramya Achutha Rao 已提交
7
import { Node, HtmlNode, Rule } from 'EmmetNode';
8
import { getNode, getInnerRange, getMappingForIncludedLanguages, parseDocument, validate } from './util';
9
import { getExpandOptions, extractAbbreviation, extractAbbreviationFromText, isStyleSheet, isAbbreviationValid, getEmmetMode, expandAbbreviation } from 'vscode-emmet-helper';
10

11 12
const trimRegex = /[\u00a0]*[\d|#|\-|\*|\u2022]+\.?/;

R
Ramya Achutha Rao 已提交
13
interface ExpandAbbreviationInput {
14
	syntax: string;
R
Ramya Achutha Rao 已提交
15 16
	abbreviation: string;
	rangeToReplace: vscode.Range;
17
	textToWrap?: string[];
18
	filters?: string[];
R
Ramya Achutha Rao 已提交
19 20
}

21
export function wrapWithAbbreviation(args) {
22
	if (!validate(false)) {
23 24
		return;
	}
25 26

	const editor = vscode.window.activeTextEditor;
27
	const abbreviationPromise = (args && args['abbreviation']) ? Promise.resolve(args['abbreviation']) : vscode.window.showInputBox({ prompt: 'Enter Abbreviation' });
28
	const syntax = getSyntaxFromArgs({ language: editor.document.languageId });
29 30

	return abbreviationPromise.then(abbreviation => {
31
		if (!abbreviation || !abbreviation.trim() || !isAbbreviationValid(syntax, abbreviation)) { return; }
32

R
Ramya Achutha Rao 已提交
33
		let expandAbbrList: ExpandAbbreviationInput[] = [];
34

35
		editor.selections.forEach(selection => {
36
			let rangeToReplace: vscode.Range = selection.isReversed ? new vscode.Range(selection.active, selection.anchor) : selection;
37 38 39
			if (rangeToReplace.isEmpty) {
				rangeToReplace = new vscode.Range(rangeToReplace.start.line, 0, rangeToReplace.start.line, editor.document.lineAt(rangeToReplace.start.line).text.length);
			}
40

41 42 43
			const firstLineOfSelection = editor.document.lineAt(rangeToReplace.start).text.substr(rangeToReplace.start.character);
			const matches = firstLineOfSelection.match(/^(\s*)/);
			const preceedingWhiteSpace = matches ? matches[1].length : 0;
44

45
			rangeToReplace = new vscode.Range(rangeToReplace.start.line, rangeToReplace.start.character + preceedingWhiteSpace, rangeToReplace.end.line, rangeToReplace.end.character);
46
			expandAbbrList.push({ syntax, abbreviation, rangeToReplace, textToWrap: ['\n\t\$TM_SELECTED_TEXT\n'] });
47
		});
48

49
		return expandAbbreviationInRange(editor, expandAbbrList, true);
50 51 52
	});
}

53 54 55 56 57 58 59 60 61 62 63 64
export function wrapIndividualLinesWithAbbreviation(args) {
	if (!validate(false)) {
		return;
	}

	const editor = vscode.window.activeTextEditor;
	if (editor.selection.isEmpty) {
		vscode.window.showInformationMessage('Select more than 1 line and try again.');
		return;
	}

	const abbreviationPromise = (args && args['abbreviation']) ? Promise.resolve(args['abbreviation']) : vscode.window.showInputBox({ prompt: 'Enter Abbreviation' });
65
	const syntax = getSyntaxFromArgs({ language: editor.document.languageId });
66 67
	const lines = editor.document.getText(editor.selection).split('\n').map(x => x.trim());

68 69
	return abbreviationPromise.then(inputAbbreviation => {
		if (!inputAbbreviation || !inputAbbreviation.trim() || !isAbbreviationValid(syntax, inputAbbreviation)) { return; }
70

71 72 73 74 75 76
		let extractedResults = extractAbbreviationFromText(inputAbbreviation);
		if (!extractedResults) {
			return;
		}

		let { abbreviation, filters } = extractedResults;
77 78 79 80
		let input: ExpandAbbreviationInput = {
			syntax,
			abbreviation,
			rangeToReplace: editor.selection,
81 82
			textToWrap: lines,
			filters
83 84 85 86 87 88 89
		};

		return expandAbbreviationInRange(editor, [input], true);
	});

}

90
export function expandEmmetAbbreviation(args): Thenable<boolean> {
91 92
	const syntax = getSyntaxFromArgs(args);
	if (!syntax || !validate()) {
93
		return fallbackTab();
94
	}
95 96 97

	const editor = vscode.window.activeTextEditor;

98
	let rootNode = parseDocument(editor.document);
99
	if (!rootNode) {
100
		return fallbackTab();
101
	}
102

R
Ramya Achutha Rao 已提交
103
	let abbreviationList: ExpandAbbreviationInput[] = [];
104 105 106
	let firstAbbreviation: string;
	let allAbbreviationsSame: boolean = true;

107
	let getAbbreviation = (document: vscode.TextDocument, selection: vscode.Selection, position: vscode.Position, syntax: string): [vscode.Range, string, string[]] => {
R
Ramya Achutha Rao 已提交
108
		let rangeToReplace: vscode.Range = selection;
109
		let abbr = document.getText(rangeToReplace);
110
		if (!rangeToReplace.isEmpty) {
111 112 113 114 115
			let extractedResults = extractAbbreviationFromText(abbr);
			if (extractedResults) {
				return [rangeToReplace, extractedResults.abbreviation, extractedResults.filters];
			}
			return [null, '', []];
116 117
		}

118 119 120
		const currentLine = editor.document.lineAt(position.line).text;
		const textTillPosition = currentLine.substr(0, position.character);

121 122
		// Expand cases like <div to <div></div> explicitly
		// else we will end up with <<div></div>
123
		if (syntax === 'html') {
124 125
			let matches = textTillPosition.match(/<(\w+)$/);
			if (matches) {
126 127 128
				abbr = matches[1];
				rangeToReplace = new vscode.Range(position.translate(0, -(abbr.length + 1)), position);
				return [rangeToReplace, abbr, []];
129
			}
130
		}
131

R
Ramya Achutha Rao 已提交
132
		// Dont try to expand abbreviations when cursor is before/after ; or : or in the middle of a word
133
		// Fix for https://github.com/Microsoft/vscode/issues/1623 in new emmet
R
Ramya Achutha Rao 已提交
134
		if (isStyleSheet(syntax) && !/\s!$/.test(textTillPosition)) {
135
			const charAtPosition = currentLine.substr(position.character, 1);
R
Ramya Achutha Rao 已提交
136 137 138
			if (textTillPosition.endsWith(':')
				|| textTillPosition.endsWith(';')
				|| (charAtPosition && !/\s/.test(charAtPosition))) {
139 140 141 142
				return [null, '', []];
			}
		}

143 144 145 146 147 148
		let extractedResults = extractAbbreviation(editor.document, position);
		if (!extractedResults) {
			return [null, '', []];
		}

		let { abbreviationRange, abbreviation, filters } = extractedResults;
149
		return [new vscode.Range(abbreviationRange.start.line, abbreviationRange.start.character, abbreviationRange.end.line, abbreviationRange.end.character), abbreviation, filters];
150 151 152 153
	};

	editor.selections.forEach(selection => {
		let position = selection.isReversed ? selection.anchor : selection.active;
R
Ramya Achutha Rao 已提交
154
		let [rangeToReplace, abbreviation, filters] = getAbbreviation(editor.document, selection, position, syntax);
155 156 157
		if (!rangeToReplace) {
			return;
		}
158 159 160
		if (!isAbbreviationValid(syntax, abbreviation)) {
			return;
		}
161

162 163 164 165 166
		let currentNode = getNode(rootNode, position);
		if (!isValidLocationForEmmetAbbreviation(currentNode, syntax, position)) {
			return;
		}

167 168 169 170
		if (!firstAbbreviation) {
			firstAbbreviation = abbreviation;
		} else if (allAbbreviationsSame && firstAbbreviation !== abbreviation) {
			allAbbreviationsSame = false;
171
		}
172

173
		abbreviationList.push({ syntax, abbreviation, rangeToReplace, filters });
174 175
	});

176 177 178 179 180
	return expandAbbreviationInRange(editor, abbreviationList, allAbbreviationsSame).then(success => {
		if (!success) {
			return fallbackTab();
		}
	});
181 182
}

183 184 185 186 187
function fallbackTab(): Thenable<boolean> {
	if (vscode.workspace.getConfiguration('emmet')['triggerExpansionOnTab'] === true) {
		return vscode.commands.executeCommand('tab');
	}
}
188
/**
189 190
 * Checks if given position is a valid location to expand emmet abbreviation.
 * Works only on html and css/less/scss syntax
191 192 193 194
 * @param currentNode parsed node at given position
 * @param syntax syntax of the abbreviation
 * @param position position to validate
 */
195
export function isValidLocationForEmmetAbbreviation(currentNode: Node, syntax: string, position: vscode.Position): boolean {
196
	if (!currentNode) {
197
		return !isStyleSheet(syntax) || (syntax === 'sass' || syntax === 'stylus');
198 199 200
	}

	if (isStyleSheet(syntax)) {
R
Ramya Achutha Rao 已提交
201 202 203 204
		if (currentNode.type !== 'rule') {
			return true;
		}
		const currentCssNode = <Rule>currentNode;
205 206 207 208 209 210 211 212 213 214

		// Workaround for https://github.com/Microsoft/vscode/30188
		if (currentCssNode.parent
			&& currentCssNode.parent.type === 'rule'
			&& currentCssNode.selectorToken
			&& currentCssNode.selectorToken.start.line !== currentCssNode.selectorToken.end.line) {
			return true;
		}

		// Position is valid if it occurs after the `{` that marks beginning of rule contents
R
Ramya Achutha Rao 已提交
215
		return currentCssNode.selectorToken && position.isAfter(currentCssNode.selectorToken.end);
216 217
	}

R
Ramya Achutha Rao 已提交
218 219 220
	const currentHtmlNode = <HtmlNode>currentNode;
	if (currentHtmlNode.close) {
		return getInnerRange(currentHtmlNode).contains(position);
221 222 223
	}

	return false;
R
Ramya Achutha Rao 已提交
224 225
}

226 227
/**
 * Expands abbreviations as detailed in expandAbbrList in the editor
228 229 230
 * @param editor
 * @param expandAbbrList
 * @param insertSameSnippet
231
 * @returns false if no snippet can be inserted.
232
 */
233
function expandAbbreviationInRange(editor: vscode.TextEditor, expandAbbrList: ExpandAbbreviationInput[], insertSameSnippet: boolean): Thenable<boolean> {
R
Ramya Achutha Rao 已提交
234
	if (!expandAbbrList || expandAbbrList.length === 0) {
235
		return Promise.resolve(false);
R
Ramya Achutha Rao 已提交
236 237 238 239 240
	}

	// Snippet to replace at multiple cursors are not the same
	// `editor.insertSnippet` will have to be called for each instance separately
	// We will not be able to maintain multiple cursors after snippet insertion
241
	let insertPromises = [];
R
Ramya Achutha Rao 已提交
242 243
	if (!insertSameSnippet) {
		expandAbbrList.forEach((expandAbbrInput: ExpandAbbreviationInput) => {
244
			let expandedText = expandAbbr(expandAbbrInput);
R
Ramya Achutha Rao 已提交
245
			if (expandedText) {
246
				insertPromises.push(editor.insertSnippet(new vscode.SnippetString(expandedText), expandAbbrInput.rangeToReplace));
R
Ramya Achutha Rao 已提交
247 248
			}
		});
249 250 251
		if (insertPromises.length === 0) {
			return Promise.resolve(false);
		}
252
		return Promise.all(insertPromises).then(() => Promise.resolve(true));
R
Ramya Achutha Rao 已提交
253 254 255
	}

	// Snippet to replace at all cursors are the same
256
	// We can pass all ranges to `editor.insertSnippet` in a single call so that
R
Ramya Achutha Rao 已提交
257 258
	// all cursors are maintained after snippet insertion
	const anyExpandAbbrInput = expandAbbrList[0];
259
	let expandedText = expandAbbr(anyExpandAbbrInput);
R
Ramya Achutha Rao 已提交
260
	let allRanges = expandAbbrList.map(value => {
261
		return new vscode.Range(value.rangeToReplace.start.line, value.rangeToReplace.start.character, value.rangeToReplace.end.line, value.rangeToReplace.end.character);
R
Ramya Achutha Rao 已提交
262 263
	});
	if (expandedText) {
264
		return editor.insertSnippet(new vscode.SnippetString(expandedText), allRanges);
R
Ramya Achutha Rao 已提交
265
	}
266
	return Promise.resolve(false);
267 268
}

269
/**
270
 * Expands abbreviation as detailed in given input.
271
 */
272
function expandAbbr(input: ExpandAbbreviationInput): string {
273
	const emmetConfig = vscode.workspace.getConfiguration('emmet');
274
	const expandOptions = getExpandOptions(input.syntax, emmetConfig['syntaxProfiles'], emmetConfig['variables'], input.filters);
275

276

277
	if (input.textToWrap) {
278 279 280 281 282
		if (input.filters && input.filters.indexOf('t') > -1) {
			input.textToWrap = input.textToWrap.map(line => {
				return line.replace(trimRegex, '').trim();
			});
		}
283 284 285 286 287 288 289 290
		expandOptions['text'] = input.textToWrap;

		// Below fixes https://github.com/Microsoft/vscode/issues/29898
		// With this, Emmet formats inline elements as block elements
		// ensuring the wrapped multi line text does not get merged to a single line
		if (!input.rangeToReplace.isSingleLine) {
			expandOptions.profile['inlineBreak'] = 1;
		}
291 292
	}

293
	try {
294
		// Expand the abbreviation
295
		let expandedText = expandAbbreviation(input.abbreviation, expandOptions);
296

297
		// If the expanded text is single line then we dont need the \t we added to $TM_SELECTED_TEXT earlier
298
		if (input.textToWrap && input.textToWrap.length === 1 && expandedText.indexOf('\n') === -1) {
299 300
			expandedText = expandedText.replace(/\s*\$TM_SELECTED_TEXT\s*/, '\$TM_SELECTED_TEXT');
		}
301 302
		return expandedText;

303 304
	} catch (e) {
		vscode.window.showErrorMessage('Failed to expand abbreviation');
305 306 307
	}


308 309 310 311 312 313 314 315
}

function getSyntaxFromArgs(args: any): string {
	let editor = vscode.window.activeTextEditor;
	if (!editor) {
		vscode.window.showInformationMessage('No editor is active.');
		return;
	}
316 317

	const mappedModes = getMappingForIncludedLanguages();
318 319
	let language: string = (!args || typeof args !== 'object' || !args['language']) ? editor.document.languageId : args['language'];
	let parentMode: string = (args && typeof args === 'object') ? args['parentMode'] : undefined;
320
	let excludedLanguages = vscode.workspace.getConfiguration('emmet')['excludeLanguages'] ? vscode.workspace.getConfiguration('emmet')['excludeLanguages'] : [];
321
	let syntax = getEmmetMode((mappedModes[language] ? mappedModes[language] : language), excludedLanguages);
322 323
	if (!syntax) {
		syntax = getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
324 325
	}

326 327 328 329 330
	// Final fallback to html
	if (!syntax) {
		syntax = getEmmetMode('html', excludedLanguages);
	}
	return syntax;
331
}