abbreviationActions.ts 9.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, 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
			const firstLineTillSelection = firstLine.substr(0, rangeToReplace.start.character);
			const noTextBeforeSelection = /^\s*$/.test(firstLineTillSelection);
			let textToWrap = '';
			let preceedingWhiteSpace = '';

			if (noTextBeforeSelection) {
				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
		expandAbbreviationInRange(editor, expandAbbrList, allTextToReplaceSame);
74 75 76
	});
}

77
export function expandAbbreviation(args) {
78
	const syntax = getSyntaxFromArgs(args);
79
	if (!syntax || !validate()) {
80 81
		return;
	}
82 83 84

	const editor = vscode.window.activeTextEditor;

85 86 87 88
	let rootNode = parse(editor.document);
	if (!rootNode) {
		return;
	}
89

R
Ramya Achutha Rao 已提交
90
	let abbreviationList: ExpandAbbreviationInput[] = [];
91 92 93
	let firstAbbreviation: string;
	let allAbbreviationsSame: boolean = true;

94
	editor.selections.forEach(selection => {
R
Ramya Achutha Rao 已提交
95
		let rangeToReplace: vscode.Range = selection;
96
		let position = selection.isReversed ? selection.anchor : selection.active;
R
Ramya Achutha Rao 已提交
97 98 99
		let abbreviation = editor.document.getText(rangeToReplace);
		if (rangeToReplace.isEmpty) {
			[rangeToReplace, abbreviation] = extractAbbreviation(editor.document, position);
100
		}
101
		if (!isAbbreviationValid(syntax, abbreviation)) {
102
			vscode.window.showErrorMessage('Emmet: Invalid abbreviation');
103 104
			return;
		}
105

106 107 108 109 110
		let currentNode = getNode(rootNode, position);
		if (!isValidLocationForEmmetAbbreviation(currentNode, syntax, position)) {
			return;
		}

111 112 113 114
		if (!firstAbbreviation) {
			firstAbbreviation = abbreviation;
		} else if (allAbbreviationsSame && firstAbbreviation !== abbreviation) {
			allAbbreviationsSame = false;
115
		}
116

117
		abbreviationList.push({ syntax, abbreviation, rangeToReplace });
118 119
	});

120
	expandAbbreviationInRange(editor, abbreviationList, allAbbreviationsSame);
121 122 123 124
}


/**
125 126
 * Checks if given position is a valid location to expand emmet abbreviation.
 * Works only on html and css/less/scss syntax
127 128 129 130
 * @param currentNode parsed node at given position
 * @param syntax syntax of the abbreviation
 * @param position position to validate
 */
131
export function isValidLocationForEmmetAbbreviation(currentNode: Node, syntax: string, position: vscode.Position): boolean {
132 133 134 135 136
	if (!currentNode) {
		return true;
	}

	if (isStyleSheet(syntax)) {
R
Ramya Achutha Rao 已提交
137 138 139 140 141
		if (currentNode.type !== 'rule') {
			return true;
		}
		const currentCssNode = <Rule>currentNode;
		return currentCssNode.selectorToken && position.isAfter(currentCssNode.selectorToken.end);
142 143
	}

R
Ramya Achutha Rao 已提交
144 145 146
	const currentHtmlNode = <HtmlNode>currentNode;
	if (currentHtmlNode.close) {
		return getInnerRange(currentHtmlNode).contains(position);
147 148 149
	}

	return false;
R
Ramya Achutha Rao 已提交
150 151
}

152 153
/**
 * Expands abbreviations as detailed in expandAbbrList in the editor
154 155 156
 * @param editor
 * @param expandAbbrList
 * @param insertSameSnippet
157
 */
158
function expandAbbreviationInRange(editor: vscode.TextEditor, expandAbbrList: ExpandAbbreviationInput[], insertSameSnippet: boolean) {
R
Ramya Achutha Rao 已提交
159 160 161
	if (!expandAbbrList || expandAbbrList.length === 0) {
		return;
	}
162
	const newLine = editor.document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
R
Ramya Achutha Rao 已提交
163 164 165 166 167 168

	// 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) => {
169
			let expandedText = expandAbbr(expandAbbrInput, newLine);
R
Ramya Achutha Rao 已提交
170 171 172 173 174 175 176 177
			if (expandedText) {
				editor.insertSnippet(new vscode.SnippetString(expandedText), expandAbbrInput.rangeToReplace);
			}
		});
		return;
	}

	// Snippet to replace at all cursors are the same
178
	// We can pass all ranges to `editor.insertSnippet` in a single call so that
R
Ramya Achutha Rao 已提交
179 180
	// all cursors are maintained after snippet insertion
	const anyExpandAbbrInput = expandAbbrList[0];
181
	let expandedText = expandAbbr(anyExpandAbbrInput, newLine);
R
Ramya Achutha Rao 已提交
182
	let allRanges = expandAbbrList.map(value => {
183
		return new vscode.Range(value.rangeToReplace.start.line, value.rangeToReplace.start.character, value.rangeToReplace.end.line, value.rangeToReplace.end.character);
R
Ramya Achutha Rao 已提交
184 185 186 187
	});
	if (expandedText) {
		editor.insertSnippet(new vscode.SnippetString(expandedText), allRanges);
	}
188 189
}

190
/**
191
 * Expands abbreviation as detailed in given input.
192 193
 * If there is textToWrap, then given preceedingWhiteSpace is applied
 */
194
function expandAbbr(input: ExpandAbbreviationInput, newLine: string): string {
195 196
	const emmetConfig = vscode.workspace.getConfiguration('emmet');
	const expandOptions = getExpandOptions(emmetConfig['syntaxProfiles'], emmetConfig['variables'], input.syntax, input.textToWrap);
197
	// Expand the abbreviation
198 199
	let expandedText;
	try {
200
		expandedText = expand(input.abbreviation, expandOptions);
201 202 203 204
	} catch (e) {
		vscode.window.showErrorMessage('Failed to expand abbreviation');
	}

205 206 207 208
	if (!expandedText) {
		return;
	}

209
	// If no text to wrap, then return the expanded text
210 211
	if (!input.textToWrap) {
		return expandedText;
212
	}
213

214 215 216
	// 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) {
217
		return expandedText.split(newLine).map(line => input.preceedingWhiteSpace + line).join(newLine);
218 219 220 221 222 223 224 225 226 227
	}

	// 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];
228
		return expandAbbr(input, newLine);
229 230
	}

231
	return input.preceedingWhiteSpace + expandedText;
232 233 234 235 236 237 238 239
}

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

	const mappedModes = getMappingForIncludedLanguages();
242 243
	let language: string = (typeof args !== 'object' || !args['language']) ? editor.document.languageId : args['language'];
	let parentMode: string = typeof args === 'object' ? args['parentMode'] : undefined;
244 245
	let excludedLanguages = vscode.workspace.getConfiguration('emmet')['exlcudeLanguages'] ? vscode.workspace.getConfiguration('emmet')['exlcudeLanguages'] : [];
	let syntax = getEmmetMode((mappedModes[language] ? mappedModes[language] : language), excludedLanguages);
246 247 248 249
	if (syntax) {
		return syntax;
	}

250
	return getEmmetMode((mappedModes[parentMode] ? mappedModes[parentMode] : parentMode), excludedLanguages);
251
}