abbreviationActions.ts 11.0 KB
Newer Older
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  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';
import { expand } from '@emmetio/expand-abbreviation';
R
Ramya Achutha Rao 已提交
8
import { Node, HtmlNode, Rule } from 'EmmetNode';
9
import { getNode, getInnerRange, getMappingForIncludedLanguages, parseDocument, validate } from './util';
10
import { getExpandOptions, extractAbbreviation, isStyleSheet, isAbbreviationValid, getEmmetMode } from 'vscode-emmet-helper';
11

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

20 21
const selectedTextToWrap = '\n\$TM_SELECTED_TEXT\n';

22 23
export function wrapWithAbbreviation(args) {
	const syntax = getSyntaxFromArgs(args);
24
	if (!syntax || !validate()) {
25 26
		return;
	}
27 28

	const editor = vscode.window.activeTextEditor;
29
	const newLine = editor.document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
30

R
Ramya Achutha Rao 已提交
31
	vscode.window.showInputBox({ prompt: 'Enter Abbreviation' }).then(abbreviation => {
32
		if (!abbreviation || !abbreviation.trim() || !isAbbreviationValid(syntax, abbreviation)) { return; }
33

R
Ramya Achutha Rao 已提交
34
		let expandAbbrList: ExpandAbbreviationInput[] = [];
35 36 37
		let firstTextToReplace: string;
		let allTextToReplaceSame: boolean = true;

38
		editor.selections.forEach(selection => {
39
			let rangeToReplace: vscode.Range = selection.isReversed ? new vscode.Range(selection.active, selection.anchor) : selection;
40 41 42
			if (rangeToReplace.isEmpty) {
				rangeToReplace = new vscode.Range(rangeToReplace.start.line, 0, rangeToReplace.start.line, editor.document.lineAt(rangeToReplace.start.line).text.length);
			}
43
			const firstLine = editor.document.lineAt(rangeToReplace.start).text;
44
			const firstLineTillSelection = firstLine.substr(0, rangeToReplace.start.character);
45
			const whitespaceBeforeSelection = /^\s*$/.test(firstLineTillSelection);
46 47 48
			let textToWrap = '';
			let preceedingWhiteSpace = '';

49
			if (whitespaceBeforeSelection) {
50 51 52 53 54 55 56 57 58 59 60 61 62 63
				const matches = firstLine.match(/^(\s*)/);
				if (matches) {
					preceedingWhiteSpace = matches[1];
				}
				if (rangeToReplace.start.character <= preceedingWhiteSpace.length) {
					rangeToReplace = new vscode.Range(rangeToReplace.start.line, 0, rangeToReplace.end.line, rangeToReplace.end.character);
				}

				textToWrap = newLine;
				for (let i = rangeToReplace.start.line; i <= rangeToReplace.end.line; i++) {
					textToWrap += '\t' + editor.document.lineAt(i).text.substr(preceedingWhiteSpace.length) + newLine;
				}
			} else {
				textToWrap = editor.document.getText(rangeToReplace);
64
			}
65 66

			if (!firstTextToReplace) {
R
Ramya Achutha Rao 已提交
67 68
				firstTextToReplace = textToWrap;
			} else if (allTextToReplaceSame && firstTextToReplace !== textToWrap) {
69 70 71
				allTextToReplaceSame = false;
			}

72
			expandAbbrList.push({ syntax, abbreviation, rangeToReplace, textToWrap, preceedingWhiteSpace });
73
		});
74

75 76
		if (!allTextToReplaceSame) {
			expandAbbrList.forEach(input => {
77
				input.textToWrap = selectedTextToWrap;
78 79 80 81
			});
		}

		expandAbbreviationInRange(editor, expandAbbrList, true);
82 83 84
	});
}

85
export function expandAbbreviation(args) {
86
	const syntax = getSyntaxFromArgs(args);
87
	if (!syntax || !validate()) {
88 89
		return;
	}
90 91 92

	const editor = vscode.window.activeTextEditor;

93
	let rootNode = parseDocument(editor.document);
94 95 96
	if (!rootNode) {
		return;
	}
97

R
Ramya Achutha Rao 已提交
98
	let abbreviationList: ExpandAbbreviationInput[] = [];
99 100 101
	let firstAbbreviation: string;
	let allAbbreviationsSame: boolean = true;

R
Ramya Achutha Rao 已提交
102
	let getAbbreviation = (document: vscode.TextDocument, selection: vscode.Selection, position: vscode.Position, isHtml: boolean): [vscode.Range, string] => {
R
Ramya Achutha Rao 已提交
103
		let rangeToReplace: vscode.Range = selection;
R
Ramya Achutha Rao 已提交
104
		let abbreviation = document.getText(rangeToReplace);
105
		if (!rangeToReplace.isEmpty) {
R
Ramya Achutha Rao 已提交
106
			return [rangeToReplace, abbreviation];
107 108 109 110 111 112 113 114 115
		}

		// Expand cases like <div to <div></div> explicitly
		// else we will end up with <<div></div>
		if (isHtml) {
			const currentLine = editor.document.lineAt(position.line).text;
			const textTillPosition = currentLine.substr(0, position.character);
			let matches = textTillPosition.match(/<(\w+)$/);
			if (matches) {
R
Ramya Achutha Rao 已提交
116
				abbreviation = matches[1];
117
				rangeToReplace = new vscode.Range(position.translate(0, -(abbreviation.length + 1)), position);
R
Ramya Achutha Rao 已提交
118
				return [rangeToReplace, abbreviation];
119
			}
120
		}
121 122 123 124 125
		return extractAbbreviation(editor.document, position);
	};

	editor.selections.forEach(selection => {
		let position = selection.isReversed ? selection.anchor : selection.active;
R
Ramya Achutha Rao 已提交
126
		let [rangeToReplace, abbreviation] = getAbbreviation(editor.document, selection, position, syntax === 'html');
127
		if (!isAbbreviationValid(syntax, abbreviation)) {
128
			vscode.window.showErrorMessage('Emmet: Invalid abbreviation');
129 130
			return;
		}
131

132 133 134 135 136
		let currentNode = getNode(rootNode, position);
		if (!isValidLocationForEmmetAbbreviation(currentNode, syntax, position)) {
			return;
		}

137 138 139 140
		if (!firstAbbreviation) {
			firstAbbreviation = abbreviation;
		} else if (allAbbreviationsSame && firstAbbreviation !== abbreviation) {
			allAbbreviationsSame = false;
141
		}
142

143
		abbreviationList.push({ syntax, abbreviation, rangeToReplace });
144 145
	});

146
	return expandAbbreviationInRange(editor, abbreviationList, allAbbreviationsSame);
147 148 149 150
}


/**
151 152
 * Checks if given position is a valid location to expand emmet abbreviation.
 * Works only on html and css/less/scss syntax
153 154 155 156
 * @param currentNode parsed node at given position
 * @param syntax syntax of the abbreviation
 * @param position position to validate
 */
157
export function isValidLocationForEmmetAbbreviation(currentNode: Node, syntax: string, position: vscode.Position): boolean {
158
	if (!currentNode) {
159
		return !isStyleSheet(syntax);
160 161 162
	}

	if (isStyleSheet(syntax)) {
R
Ramya Achutha Rao 已提交
163 164 165 166
		if (currentNode.type !== 'rule') {
			return true;
		}
		const currentCssNode = <Rule>currentNode;
167 168 169 170 171 172 173 174 175 176

		// 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 已提交
177
		return currentCssNode.selectorToken && position.isAfter(currentCssNode.selectorToken.end);
178 179
	}

R
Ramya Achutha Rao 已提交
180 181 182
	const currentHtmlNode = <HtmlNode>currentNode;
	if (currentHtmlNode.close) {
		return getInnerRange(currentHtmlNode).contains(position);
183 184 185
	}

	return false;
R
Ramya Achutha Rao 已提交
186 187
}

188 189
/**
 * Expands abbreviations as detailed in expandAbbrList in the editor
190 191 192
 * @param editor
 * @param expandAbbrList
 * @param insertSameSnippet
193
 */
194
function expandAbbreviationInRange(editor: vscode.TextEditor, expandAbbrList: ExpandAbbreviationInput[], insertSameSnippet: boolean): Thenable<boolean> {
R
Ramya Achutha Rao 已提交
195 196 197
	if (!expandAbbrList || expandAbbrList.length === 0) {
		return;
	}
198
	const newLine = editor.document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
R
Ramya Achutha Rao 已提交
199 200 201 202

	// 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
203
	let insertPromises = [];
R
Ramya Achutha Rao 已提交
204 205
	if (!insertSameSnippet) {
		expandAbbrList.forEach((expandAbbrInput: ExpandAbbreviationInput) => {
206
			let expandedText = expandAbbr(expandAbbrInput, newLine);
R
Ramya Achutha Rao 已提交
207
			if (expandedText) {
208
				insertPromises.push(editor.insertSnippet(new vscode.SnippetString(expandedText), expandAbbrInput.rangeToReplace));
R
Ramya Achutha Rao 已提交
209 210
			}
		});
211
		return Promise.all(insertPromises).then(() => Promise.resolve(true));
R
Ramya Achutha Rao 已提交
212 213 214
	}

	// Snippet to replace at all cursors are the same
215
	// We can pass all ranges to `editor.insertSnippet` in a single call so that
R
Ramya Achutha Rao 已提交
216 217
	// all cursors are maintained after snippet insertion
	const anyExpandAbbrInput = expandAbbrList[0];
218
	let expandedText = expandAbbr(anyExpandAbbrInput, newLine);
R
Ramya Achutha Rao 已提交
219
	let allRanges = expandAbbrList.map(value => {
220
		return new vscode.Range(value.rangeToReplace.start.line, value.rangeToReplace.start.character, value.rangeToReplace.end.line, value.rangeToReplace.end.character);
R
Ramya Achutha Rao 已提交
221 222
	});
	if (expandedText) {
223
		return editor.insertSnippet(new vscode.SnippetString(expandedText), allRanges);
R
Ramya Achutha Rao 已提交
224
	}
225 226
}

227
/**
228
 * Expands abbreviation as detailed in given input.
229 230
 * If there is textToWrap, then given preceedingWhiteSpace is applied
 */
231
function expandAbbr(input: ExpandAbbreviationInput, newLine: string): string {
232 233
	const emmetConfig = vscode.workspace.getConfiguration('emmet');
	const expandOptions = getExpandOptions(emmetConfig['syntaxProfiles'], emmetConfig['variables'], input.syntax, input.textToWrap);
234 235

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

242
	// Expand the abbreviation
243 244
	let expandedText;
	try {
245
		expandedText = expand(input.abbreviation, expandOptions);
246
		if (input.textToWrap && input.textToWrap !== selectedTextToWrap) {
247
			expandedText = expandedText.replace(/(\$[^\{])/g, '\\$&');
248
		}
249 250 251 252
	} catch (e) {
		vscode.window.showErrorMessage('Failed to expand abbreviation');
	}

253 254 255 256
	if (!expandedText) {
		return;
	}

257
	// If no text to wrap, then return the expanded text
258
	if (!input.textToWrap || !input.preceedingWhiteSpace) {
259
		return expandedText;
260
	}
261

262 263 264
	// There was text to wrap, and the final expanded text is multi line
	// So add the preceedingWhiteSpace to each line
	if (expandedText.indexOf('\n') > -1) {
265
		return expandedText.split(newLine).map(line => input.preceedingWhiteSpace + line).join(newLine);
266 267 268 269 270 271 272 273 274 275
	}

	// There was text to wrap and the final expanded text is single line
	// This can happen when the abbreviation was for an inline element
	// Remove the preceeding newLine + tab and the ending newLine, that was added to textToWrap
	// And re-expand the abbreviation
	let regex = newLine === '\n' ? /^\n\t(.*)\n$/ : /^\r\n\t(.*)\r\n$/;
	let matches = input.textToWrap.match(regex);
	if (matches) {
		input.textToWrap = matches[1];
276
		return expandAbbr(input, newLine);
277 278
	}

279
	return input.preceedingWhiteSpace + expandedText;
280 281 282 283 284 285 286 287
}

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

	const mappedModes = getMappingForIncludedLanguages();
290 291
	let language: string = (!args || typeof args !== 'object' || !args['language']) ? editor.document.languageId : args['language'];
	let parentMode: string = (args && typeof args === 'object') ? args['parentMode'] : undefined;
292 293
	let excludedLanguages = vscode.workspace.getConfiguration('emmet')['exlcudeLanguages'] ? vscode.workspace.getConfiguration('emmet')['exlcudeLanguages'] : [];
	let syntax = getEmmetMode((mappedModes[language] ? mappedModes[language] : language), excludedLanguages);
294 295 296 297
	if (syntax) {
		return syntax;
	}

298
	return getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
299
}