abbreviationActions.ts 10.5 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
	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 159 160 161 162
	if (!currentNode) {
		return true;
	}

	if (isStyleSheet(syntax)) {
R
Ramya Achutha Rao 已提交
163 164 165 166 167
		if (currentNode.type !== 'rule') {
			return true;
		}
		const currentCssNode = <Rule>currentNode;
		return currentCssNode.selectorToken && position.isAfter(currentCssNode.selectorToken.end);
168 169
	}

R
Ramya Achutha Rao 已提交
170 171 172
	const currentHtmlNode = <HtmlNode>currentNode;
	if (currentHtmlNode.close) {
		return getInnerRange(currentHtmlNode).contains(position);
173 174 175
	}

	return false;
R
Ramya Achutha Rao 已提交
176 177
}

178 179
/**
 * Expands abbreviations as detailed in expandAbbrList in the editor
180 181 182
 * @param editor
 * @param expandAbbrList
 * @param insertSameSnippet
183
 */
184
function expandAbbreviationInRange(editor: vscode.TextEditor, expandAbbrList: ExpandAbbreviationInput[], insertSameSnippet: boolean) {
R
Ramya Achutha Rao 已提交
185 186 187
	if (!expandAbbrList || expandAbbrList.length === 0) {
		return;
	}
188
	const newLine = editor.document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
R
Ramya Achutha Rao 已提交
189 190 191 192 193 194

	// 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
	if (!insertSameSnippet) {
		expandAbbrList.forEach((expandAbbrInput: ExpandAbbreviationInput) => {
195
			let expandedText = expandAbbr(expandAbbrInput, newLine);
R
Ramya Achutha Rao 已提交
196 197 198 199 200 201 202 203
			if (expandedText) {
				editor.insertSnippet(new vscode.SnippetString(expandedText), expandAbbrInput.rangeToReplace);
			}
		});
		return;
	}

	// Snippet to replace at all cursors are the same
204
	// We can pass all ranges to `editor.insertSnippet` in a single call so that
R
Ramya Achutha Rao 已提交
205 206
	// all cursors are maintained after snippet insertion
	const anyExpandAbbrInput = expandAbbrList[0];
207
	let expandedText = expandAbbr(anyExpandAbbrInput, newLine);
R
Ramya Achutha Rao 已提交
208
	let allRanges = expandAbbrList.map(value => {
209
		return new vscode.Range(value.rangeToReplace.start.line, value.rangeToReplace.start.character, value.rangeToReplace.end.line, value.rangeToReplace.end.character);
R
Ramya Achutha Rao 已提交
210 211 212 213
	});
	if (expandedText) {
		editor.insertSnippet(new vscode.SnippetString(expandedText), allRanges);
	}
214 215
}

216
/**
217
 * Expands abbreviation as detailed in given input.
218 219
 * If there is textToWrap, then given preceedingWhiteSpace is applied
 */
220
function expandAbbr(input: ExpandAbbreviationInput, newLine: string): string {
221 222
	const emmetConfig = vscode.workspace.getConfiguration('emmet');
	const expandOptions = getExpandOptions(emmetConfig['syntaxProfiles'], emmetConfig['variables'], input.syntax, input.textToWrap);
223 224 225 226 227

	// 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.textToWrap && !input.rangeToReplace.isSingleLine) {
228 229 230
		expandOptions.profile['inlineBreak'] = 1;
	}

231
	// Expand the abbreviation
232 233
	let expandedText;
	try {
234
		expandedText = expand(input.abbreviation, expandOptions);
235
		if (input.textToWrap && input.textToWrap !== selectedTextToWrap) {
236
			expandedText = expandedText.replace(/(\$[^\{])/g, '\\$&');
237
		}
238 239 240 241
	} catch (e) {
		vscode.window.showErrorMessage('Failed to expand abbreviation');
	}

242 243 244 245
	if (!expandedText) {
		return;
	}

246
	// If no text to wrap, then return the expanded text
247
	if (!input.textToWrap || !input.preceedingWhiteSpace) {
248
		return expandedText;
249
	}
250

251 252 253
	// 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) {
254
		return expandedText.split(newLine).map(line => input.preceedingWhiteSpace + line).join(newLine);
255 256 257 258 259 260 261 262 263 264
	}

	// 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];
265
		return expandAbbr(input, newLine);
266 267
	}

268
	return input.preceedingWhiteSpace + expandedText;
269 270 271 272 273 274 275 276
}

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

	const mappedModes = getMappingForIncludedLanguages();
279 280
	let language: string = (typeof args !== 'object' || !args['language']) ? editor.document.languageId : args['language'];
	let parentMode: string = typeof args === 'object' ? args['parentMode'] : undefined;
281 282
	let excludedLanguages = vscode.workspace.getConfiguration('emmet')['exlcudeLanguages'] ? vscode.workspace.getConfiguration('emmet')['exlcudeLanguages'] : [];
	let syntax = getEmmetMode((mappedModes[language] ? mappedModes[language] : language), excludedLanguages);
283 284 285 286
	if (syntax) {
		return syntax;
	}

287
	return getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
288
}