abbreviationActions.ts 10.3 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, parse, 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
export function wrapWithAbbreviation(args) {
	const syntax = getSyntaxFromArgs(args);
22
	if (!syntax || !validate()) {
23 24
		return;
	}
25 26

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

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

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

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

47
			if (whitespaceBeforeSelection) {
48 49 50 51 52 53 54 55 56 57 58 59 60 61
				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);
62
			}
63 64

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

70
			expandAbbrList.push({ syntax, abbreviation, rangeToReplace, textToWrap, preceedingWhiteSpace });
71
		});
72

73 74 75 76 77 78 79
		if (!allTextToReplaceSame) {
			expandAbbrList.forEach(input => {
				input.textToWrap = '\n\$TM_SELECTED_TEXT\n';
			});
		}

		expandAbbreviationInRange(editor, expandAbbrList, true);
80 81 82
	});
}

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

	const editor = vscode.window.activeTextEditor;

91 92 93 94
	let rootNode = parse(editor.document);
	if (!rootNode) {
		return;
	}
95

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

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

		// 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 已提交
114
				abbreviation = matches[1];
115
				rangeToReplace = new vscode.Range(position.translate(0, -(abbreviation.length + 1)), position);
R
Ramya Achutha Rao 已提交
116
				return [rangeToReplace, abbreviation];
117
			}
118
		}
119 120 121 122 123
		return extractAbbreviation(editor.document, position);
	};

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

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

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

141
		abbreviationList.push({ syntax, abbreviation, rangeToReplace });
142 143
	});

144
	expandAbbreviationInRange(editor, abbreviationList, allAbbreviationsSame);
145 146 147 148
}


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

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

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

	return false;
R
Ramya Achutha Rao 已提交
174 175
}

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

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

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

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

	// 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) {
226 227 228
		expandOptions.profile['inlineBreak'] = 1;
	}

229
	// Expand the abbreviation
230 231
	let expandedText;
	try {
232
		expandedText = expand(input.abbreviation, expandOptions);
233 234 235 236
	} catch (e) {
		vscode.window.showErrorMessage('Failed to expand abbreviation');
	}

237 238 239 240
	if (!expandedText) {
		return;
	}

241
	// If no text to wrap, then return the expanded text
242
	if (!input.textToWrap || !input.preceedingWhiteSpace) {
243
		return expandedText;
244
	}
245

246 247 248
	// 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) {
249
		return expandedText.split(newLine).map(line => input.preceedingWhiteSpace + line).join(newLine);
250 251 252 253 254 255 256 257 258 259
	}

	// 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];
260
		return expandAbbr(input, newLine);
261 262
	}

263
	return input.preceedingWhiteSpace + expandedText;
264 265 266 267 268 269 270 271
}

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

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

282
	return getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
283
}