abbreviationActions.ts 11.2 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
		let { abbreviation, filters } = extractAbbreviationFromText(inputAbbreviation);
72 73 74 75
		let input: ExpandAbbreviationInput = {
			syntax,
			abbreviation,
			rangeToReplace: editor.selection,
76 77
			textToWrap: lines,
			filters
78 79 80 81 82 83 84
		};

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

}

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

	const editor = vscode.window.activeTextEditor;

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

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

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

		// 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) {
117 118 119
				abbr = matches[1];
				rangeToReplace = new vscode.Range(position.translate(0, -(abbr.length + 1)), position);
				return [rangeToReplace, abbr, []];
120
			}
121
		}
122 123 124 125 126 127
		let extractedResults = extractAbbreviation(editor.document, position);
		if (!extractedResults) {
			return [null, '', []];
		}

		let { abbreviationRange, abbreviation, filters } = extractedResults;
128
		return [new vscode.Range(abbreviationRange.start.line, abbreviationRange.start.character, abbreviationRange.end.line, abbreviationRange.end.character), abbreviation, filters];
129 130 131 132
	};

	editor.selections.forEach(selection => {
		let position = selection.isReversed ? selection.anchor : selection.active;
133
		let [rangeToReplace, abbreviation, filters] = getAbbreviation(editor.document, selection, position, syntax === 'html');
134 135 136
		if (!rangeToReplace) {
			return;
		}
137
		if (!isAbbreviationValid(syntax, abbreviation)) {
138
			vscode.window.showErrorMessage('Emmet: Invalid abbreviation');
139 140
			return;
		}
141

142 143 144 145 146
		let currentNode = getNode(rootNode, position);
		if (!isValidLocationForEmmetAbbreviation(currentNode, syntax, position)) {
			return;
		}

147 148 149 150
		if (!firstAbbreviation) {
			firstAbbreviation = abbreviation;
		} else if (allAbbreviationsSame && firstAbbreviation !== abbreviation) {
			allAbbreviationsSame = false;
151
		}
152

153
		abbreviationList.push({ syntax, abbreviation, rangeToReplace, filters });
154 155
	});

156
	return expandAbbreviationInRange(editor, abbreviationList, allAbbreviationsSame);
157 158 159 160
}


/**
161 162
 * Checks if given position is a valid location to expand emmet abbreviation.
 * Works only on html and css/less/scss syntax
163 164 165 166
 * @param currentNode parsed node at given position
 * @param syntax syntax of the abbreviation
 * @param position position to validate
 */
167
export function isValidLocationForEmmetAbbreviation(currentNode: Node, syntax: string, position: vscode.Position): boolean {
168
	if (!currentNode) {
169
		return !isStyleSheet(syntax) || (syntax === 'sass' || syntax === 'stylus');
170 171 172
	}

	if (isStyleSheet(syntax)) {
R
Ramya Achutha Rao 已提交
173 174 175 176
		if (currentNode.type !== 'rule') {
			return true;
		}
		const currentCssNode = <Rule>currentNode;
177 178 179 180 181 182 183 184 185 186

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

R
Ramya Achutha Rao 已提交
190 191 192
	const currentHtmlNode = <HtmlNode>currentNode;
	if (currentHtmlNode.close) {
		return getInnerRange(currentHtmlNode).contains(position);
193 194 195
	}

	return false;
R
Ramya Achutha Rao 已提交
196 197
}

198 199
/**
 * Expands abbreviations as detailed in expandAbbrList in the editor
200 201 202
 * @param editor
 * @param expandAbbrList
 * @param insertSameSnippet
203
 */
204
function expandAbbreviationInRange(editor: vscode.TextEditor, expandAbbrList: ExpandAbbreviationInput[], insertSameSnippet: boolean): Thenable<boolean> {
R
Ramya Achutha Rao 已提交
205
	if (!expandAbbrList || expandAbbrList.length === 0) {
206
		return Promise.resolve(false);
R
Ramya Achutha Rao 已提交
207 208 209 210 211
	}

	// 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
212
	let insertPromises = [];
R
Ramya Achutha Rao 已提交
213 214
	if (!insertSameSnippet) {
		expandAbbrList.forEach((expandAbbrInput: ExpandAbbreviationInput) => {
215
			let expandedText = expandAbbr(expandAbbrInput);
R
Ramya Achutha Rao 已提交
216
			if (expandedText) {
217
				insertPromises.push(editor.insertSnippet(new vscode.SnippetString(expandedText), expandAbbrInput.rangeToReplace));
R
Ramya Achutha Rao 已提交
218 219
			}
		});
220
		return Promise.all(insertPromises).then(() => Promise.resolve(true));
R
Ramya Achutha Rao 已提交
221 222 223
	}

	// Snippet to replace at all cursors are the same
224
	// We can pass all ranges to `editor.insertSnippet` in a single call so that
R
Ramya Achutha Rao 已提交
225 226
	// all cursors are maintained after snippet insertion
	const anyExpandAbbrInput = expandAbbrList[0];
227
	let expandedText = expandAbbr(anyExpandAbbrInput);
R
Ramya Achutha Rao 已提交
228
	let allRanges = expandAbbrList.map(value => {
229
		return new vscode.Range(value.rangeToReplace.start.line, value.rangeToReplace.start.character, value.rangeToReplace.end.line, value.rangeToReplace.end.character);
R
Ramya Achutha Rao 已提交
230 231
	});
	if (expandedText) {
232
		return editor.insertSnippet(new vscode.SnippetString(expandedText), allRanges);
R
Ramya Achutha Rao 已提交
233
	}
234
	return Promise.resolve(false);
235 236
}

237
/**
238
 * Expands abbreviation as detailed in given input.
239
 */
240
function expandAbbr(input: ExpandAbbreviationInput): string {
241
	const emmetConfig = vscode.workspace.getConfiguration('emmet');
242
	const expandOptions = getExpandOptions(input.syntax, emmetConfig['syntaxProfiles'], emmetConfig['variables'], input.filters);
243

244

245
	if (input.textToWrap) {
246 247 248 249 250
		if (input.filters && input.filters.indexOf('t') > -1) {
			input.textToWrap = input.textToWrap.map(line => {
				return line.replace(trimRegex, '').trim();
			});
		}
251 252 253 254 255 256 257 258
		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;
		}
259 260
	}

261
	try {
262
		// Expand the abbreviation
263
		let expandedText = expandAbbreviation(input.abbreviation, expandOptions);
264

265
		// If the expanded text is single line then we dont need the \t we added to $TM_SELECTED_TEXT earlier
266
		if (input.textToWrap && input.textToWrap.length === 1 && expandedText.indexOf('\n') === -1) {
267 268
			expandedText = expandedText.replace(/\s*\$TM_SELECTED_TEXT\s*/, '\$TM_SELECTED_TEXT');
		}
269 270
		return expandedText;

271 272
	} catch (e) {
		vscode.window.showErrorMessage('Failed to expand abbreviation');
273 274 275
	}


276 277 278 279 280 281 282 283
}

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

	const mappedModes = getMappingForIncludedLanguages();
286 287
	let language: string = (!args || typeof args !== 'object' || !args['language']) ? editor.document.languageId : args['language'];
	let parentMode: string = (args && typeof args === 'object') ? args['parentMode'] : undefined;
288
	let excludedLanguages = vscode.workspace.getConfiguration('emmet')['excludeLanguages'] ? vscode.workspace.getConfiguration('emmet')['excludeLanguages'] : [];
289
	let syntax = getEmmetMode((mappedModes[language] ? mappedModes[language] : language), excludedLanguages);
290 291
	if (!syntax) {
		syntax = getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
292 293
	}

294 295 296 297 298
	// Final fallback to html
	if (!syntax) {
		syntax = getEmmetMode('html', excludedLanguages);
	}
	return syntax;
299
}