linkedEditing.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  6. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  9. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10. };
  11. var __param = (this && this.__param) || function (paramIndex, decorator) {
  12. return function (target, key) { decorator(target, key, paramIndex); }
  13. };
  14. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  15. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  16. return new (P || (P = Promise))(function (resolve, reject) {
  17. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  18. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  19. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  20. step((generator = generator.apply(thisArg, _arguments || [])).next());
  21. });
  22. };
  23. import * as arrays from '../../../base/common/arrays.js';
  24. import { createCancelablePromise, Delayer, first } from '../../../base/common/async.js';
  25. import { CancellationToken } from '../../../base/common/cancellation.js';
  26. import { Color } from '../../../base/common/color.js';
  27. import { isPromiseCanceledError, onUnexpectedError, onUnexpectedExternalError } from '../../../base/common/errors.js';
  28. import { Disposable, DisposableStore } from '../../../base/common/lifecycle.js';
  29. import * as strings from '../../../base/common/strings.js';
  30. import { URI } from '../../../base/common/uri.js';
  31. import { EditorAction, EditorCommand, registerEditorAction, registerEditorCommand, registerEditorContribution, registerModelAndPositionCommand } from '../../browser/editorExtensions.js';
  32. import { ICodeEditorService } from '../../browser/services/codeEditorService.js';
  33. import { Position } from '../../common/core/position.js';
  34. import { Range } from '../../common/core/range.js';
  35. import { EditorContextKeys } from '../../common/editorContextKeys.js';
  36. import { ModelDecorationOptions } from '../../common/model/textModel.js';
  37. import { LinkedEditingRangeProviderRegistry } from '../../common/modes.js';
  38. import { LanguageConfigurationRegistry } from '../../common/modes/languageConfigurationRegistry.js';
  39. import * as nls from '../../../nls.js';
  40. import { ContextKeyExpr, IContextKeyService, RawContextKey } from '../../../platform/contextkey/common/contextkey.js';
  41. import { registerColor } from '../../../platform/theme/common/colorRegistry.js';
  42. import { registerThemingParticipant } from '../../../platform/theme/common/themeService.js';
  43. export const CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = new RawContextKey('LinkedEditingInputVisible', false);
  44. const DECORATION_CLASS_NAME = 'linked-editing-decoration';
  45. let LinkedEditingContribution = class LinkedEditingContribution extends Disposable {
  46. constructor(editor, contextKeyService) {
  47. super();
  48. this._debounceDuration = 200;
  49. this._localToDispose = this._register(new DisposableStore());
  50. this._editor = editor;
  51. this._enabled = false;
  52. this._visibleContextKey = CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
  53. this._currentDecorations = [];
  54. this._languageWordPattern = null;
  55. this._currentWordPattern = null;
  56. this._ignoreChangeEvent = false;
  57. this._localToDispose = this._register(new DisposableStore());
  58. this._rangeUpdateTriggerPromise = null;
  59. this._rangeSyncTriggerPromise = null;
  60. this._currentRequest = null;
  61. this._currentRequestPosition = null;
  62. this._currentRequestModelVersion = null;
  63. this._register(this._editor.onDidChangeModel(() => this.reinitialize(true)));
  64. this._register(this._editor.onDidChangeConfiguration(e => {
  65. if (e.hasChanged(61 /* linkedEditing */) || e.hasChanged(81 /* renameOnType */)) {
  66. this.reinitialize(false);
  67. }
  68. }));
  69. this._register(LinkedEditingRangeProviderRegistry.onDidChange(() => this.reinitialize(false)));
  70. this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize(true)));
  71. this.reinitialize(true);
  72. }
  73. static get(editor) {
  74. return editor.getContribution(LinkedEditingContribution.ID);
  75. }
  76. reinitialize(forceRefresh) {
  77. const model = this._editor.getModel();
  78. const isEnabled = model !== null && (this._editor.getOption(61 /* linkedEditing */) || this._editor.getOption(81 /* renameOnType */)) && LinkedEditingRangeProviderRegistry.has(model);
  79. if (isEnabled === this._enabled && !forceRefresh) {
  80. return;
  81. }
  82. this._enabled = isEnabled;
  83. this.clearRanges();
  84. this._localToDispose.clear();
  85. if (!isEnabled || model === null) {
  86. return;
  87. }
  88. this._languageWordPattern = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageId());
  89. this._localToDispose.add(model.onDidChangeLanguageConfiguration(() => {
  90. this._languageWordPattern = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageId());
  91. }));
  92. const rangeUpdateScheduler = new Delayer(this._debounceDuration);
  93. const triggerRangeUpdate = () => {
  94. this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), this._debounceDuration);
  95. };
  96. const rangeSyncScheduler = new Delayer(0);
  97. const triggerRangeSync = (decorations) => {
  98. this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(decorations));
  99. };
  100. this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => {
  101. triggerRangeUpdate();
  102. }));
  103. this._localToDispose.add(this._editor.onDidChangeModelContent((e) => {
  104. if (!this._ignoreChangeEvent) {
  105. if (this._currentDecorations.length > 0) {
  106. const referenceRange = model.getDecorationRange(this._currentDecorations[0]);
  107. if (referenceRange && e.changes.every(c => referenceRange.intersectRanges(c.range))) {
  108. triggerRangeSync(this._currentDecorations);
  109. return;
  110. }
  111. }
  112. }
  113. triggerRangeUpdate();
  114. }));
  115. this._localToDispose.add({
  116. dispose: () => {
  117. rangeUpdateScheduler.cancel();
  118. rangeSyncScheduler.cancel();
  119. }
  120. });
  121. this.updateRanges();
  122. }
  123. _syncRanges(decorations) {
  124. // dalayed invocation, make sure we're still on
  125. if (!this._editor.hasModel() || decorations !== this._currentDecorations || decorations.length === 0) {
  126. // nothing to do
  127. return;
  128. }
  129. const model = this._editor.getModel();
  130. const referenceRange = model.getDecorationRange(decorations[0]);
  131. if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) {
  132. return this.clearRanges();
  133. }
  134. const referenceValue = model.getValueInRange(referenceRange);
  135. if (this._currentWordPattern) {
  136. const match = referenceValue.match(this._currentWordPattern);
  137. const matchLength = match ? match[0].length : 0;
  138. if (matchLength !== referenceValue.length) {
  139. return this.clearRanges();
  140. }
  141. }
  142. let edits = [];
  143. for (let i = 1, len = decorations.length; i < len; i++) {
  144. const mirrorRange = model.getDecorationRange(decorations[i]);
  145. if (!mirrorRange) {
  146. continue;
  147. }
  148. if (mirrorRange.startLineNumber !== mirrorRange.endLineNumber) {
  149. edits.push({
  150. range: mirrorRange,
  151. text: referenceValue
  152. });
  153. }
  154. else {
  155. let oldValue = model.getValueInRange(mirrorRange);
  156. let newValue = referenceValue;
  157. let rangeStartColumn = mirrorRange.startColumn;
  158. let rangeEndColumn = mirrorRange.endColumn;
  159. const commonPrefixLength = strings.commonPrefixLength(oldValue, newValue);
  160. rangeStartColumn += commonPrefixLength;
  161. oldValue = oldValue.substr(commonPrefixLength);
  162. newValue = newValue.substr(commonPrefixLength);
  163. const commonSuffixLength = strings.commonSuffixLength(oldValue, newValue);
  164. rangeEndColumn -= commonSuffixLength;
  165. oldValue = oldValue.substr(0, oldValue.length - commonSuffixLength);
  166. newValue = newValue.substr(0, newValue.length - commonSuffixLength);
  167. if (rangeStartColumn !== rangeEndColumn || newValue.length !== 0) {
  168. edits.push({
  169. range: new Range(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn),
  170. text: newValue
  171. });
  172. }
  173. }
  174. }
  175. if (edits.length === 0) {
  176. return;
  177. }
  178. try {
  179. this._editor.popUndoStop();
  180. this._ignoreChangeEvent = true;
  181. const prevEditOperationType = this._editor._getViewModel().getPrevEditOperationType();
  182. this._editor.executeEdits('linkedEditing', edits);
  183. this._editor._getViewModel().setPrevEditOperationType(prevEditOperationType);
  184. }
  185. finally {
  186. this._ignoreChangeEvent = false;
  187. }
  188. }
  189. dispose() {
  190. this.clearRanges();
  191. super.dispose();
  192. }
  193. clearRanges() {
  194. this._visibleContextKey.set(false);
  195. this._currentDecorations = this._editor.deltaDecorations(this._currentDecorations, []);
  196. if (this._currentRequest) {
  197. this._currentRequest.cancel();
  198. this._currentRequest = null;
  199. this._currentRequestPosition = null;
  200. }
  201. }
  202. updateRanges(force = false) {
  203. return __awaiter(this, void 0, void 0, function* () {
  204. if (!this._editor.hasModel()) {
  205. this.clearRanges();
  206. return;
  207. }
  208. const position = this._editor.getPosition();
  209. if (!this._enabled && !force || this._editor.getSelections().length > 1) {
  210. // disabled or multicursor
  211. this.clearRanges();
  212. return;
  213. }
  214. const model = this._editor.getModel();
  215. const modelVersionId = model.getVersionId();
  216. if (this._currentRequestPosition && this._currentRequestModelVersion === modelVersionId) {
  217. if (position.equals(this._currentRequestPosition)) {
  218. return; // same position
  219. }
  220. if (this._currentDecorations && this._currentDecorations.length > 0) {
  221. const range = model.getDecorationRange(this._currentDecorations[0]);
  222. if (range && range.containsPosition(position)) {
  223. return; // just moving inside the existing primary range
  224. }
  225. }
  226. }
  227. this._currentRequestPosition = position;
  228. this._currentRequestModelVersion = modelVersionId;
  229. const request = createCancelablePromise((token) => __awaiter(this, void 0, void 0, function* () {
  230. try {
  231. const response = yield getLinkedEditingRanges(model, position, token);
  232. if (request !== this._currentRequest) {
  233. return;
  234. }
  235. this._currentRequest = null;
  236. if (modelVersionId !== model.getVersionId()) {
  237. return;
  238. }
  239. let ranges = [];
  240. if (response === null || response === void 0 ? void 0 : response.ranges) {
  241. ranges = response.ranges;
  242. }
  243. this._currentWordPattern = (response === null || response === void 0 ? void 0 : response.wordPattern) || this._languageWordPattern;
  244. let foundReferenceRange = false;
  245. for (let i = 0, len = ranges.length; i < len; i++) {
  246. if (Range.containsPosition(ranges[i], position)) {
  247. foundReferenceRange = true;
  248. if (i !== 0) {
  249. const referenceRange = ranges[i];
  250. ranges.splice(i, 1);
  251. ranges.unshift(referenceRange);
  252. }
  253. break;
  254. }
  255. }
  256. if (!foundReferenceRange) {
  257. // Cannot do linked editing if the ranges are not where the cursor is...
  258. this.clearRanges();
  259. return;
  260. }
  261. const decorations = ranges.map(range => ({ range: range, options: LinkedEditingContribution.DECORATION }));
  262. this._visibleContextKey.set(true);
  263. this._currentDecorations = this._editor.deltaDecorations(this._currentDecorations, decorations);
  264. }
  265. catch (err) {
  266. if (!isPromiseCanceledError(err)) {
  267. onUnexpectedError(err);
  268. }
  269. if (this._currentRequest === request || !this._currentRequest) {
  270. // stop if we are still the latest request
  271. this.clearRanges();
  272. }
  273. }
  274. }));
  275. this._currentRequest = request;
  276. return request;
  277. });
  278. }
  279. };
  280. LinkedEditingContribution.ID = 'editor.contrib.linkedEditing';
  281. LinkedEditingContribution.DECORATION = ModelDecorationOptions.register({
  282. description: 'linked-editing',
  283. stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */,
  284. className: DECORATION_CLASS_NAME
  285. });
  286. LinkedEditingContribution = __decorate([
  287. __param(1, IContextKeyService)
  288. ], LinkedEditingContribution);
  289. export { LinkedEditingContribution };
  290. export class LinkedEditingAction extends EditorAction {
  291. constructor() {
  292. super({
  293. id: 'editor.action.linkedEditing',
  294. label: nls.localize('linkedEditing.label', "Start Linked Editing"),
  295. alias: 'Start Linked Editing',
  296. precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
  297. kbOpts: {
  298. kbExpr: EditorContextKeys.editorTextFocus,
  299. primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 60 /* F2 */,
  300. weight: 100 /* EditorContrib */
  301. }
  302. });
  303. }
  304. runCommand(accessor, args) {
  305. const editorService = accessor.get(ICodeEditorService);
  306. const [uri, pos] = Array.isArray(args) && args || [undefined, undefined];
  307. if (URI.isUri(uri) && Position.isIPosition(pos)) {
  308. return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => {
  309. if (!editor) {
  310. return;
  311. }
  312. editor.setPosition(pos);
  313. editor.invokeWithinContext(accessor => {
  314. this.reportTelemetry(accessor, editor);
  315. return this.run(accessor, editor);
  316. });
  317. }, onUnexpectedError);
  318. }
  319. return super.runCommand(accessor, args);
  320. }
  321. run(_accessor, editor) {
  322. const controller = LinkedEditingContribution.get(editor);
  323. if (controller) {
  324. return Promise.resolve(controller.updateRanges(true));
  325. }
  326. return Promise.resolve();
  327. }
  328. }
  329. const LinkedEditingCommand = EditorCommand.bindToContribution(LinkedEditingContribution.get);
  330. registerEditorCommand(new LinkedEditingCommand({
  331. id: 'cancelLinkedEditingInput',
  332. precondition: CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE,
  333. handler: x => x.clearRanges(),
  334. kbOpts: {
  335. kbExpr: EditorContextKeys.editorTextFocus,
  336. weight: 100 /* EditorContrib */ + 99,
  337. primary: 9 /* Escape */,
  338. secondary: [1024 /* Shift */ | 9 /* Escape */]
  339. }
  340. }));
  341. function getLinkedEditingRanges(model, position, token) {
  342. const orderedByScore = LinkedEditingRangeProviderRegistry.ordered(model);
  343. // in order of score ask the linked editing range provider
  344. // until someone response with a good result
  345. // (good = not null)
  346. return first(orderedByScore.map(provider => () => __awaiter(this, void 0, void 0, function* () {
  347. try {
  348. return yield provider.provideLinkedEditingRanges(model, position, token);
  349. }
  350. catch (e) {
  351. onUnexpectedExternalError(e);
  352. return undefined;
  353. }
  354. })), result => !!result && arrays.isNonEmptyArray(result === null || result === void 0 ? void 0 : result.ranges));
  355. }
  356. export const editorLinkedEditingBackground = registerColor('editor.linkedEditingBackground', { dark: Color.fromHex('#f00').transparent(0.3), light: Color.fromHex('#f00').transparent(0.3), hc: Color.fromHex('#f00').transparent(0.3) }, nls.localize('editorLinkedEditingBackground', 'Background color when the editor auto renames on type.'));
  357. registerThemingParticipant((theme, collector) => {
  358. const editorLinkedEditingBackgroundColor = theme.getColor(editorLinkedEditingBackground);
  359. if (editorLinkedEditingBackgroundColor) {
  360. collector.addRule(`.monaco-editor .${DECORATION_CLASS_NAME} { background: ${editorLinkedEditingBackgroundColor}; border-left-color: ${editorLinkedEditingBackgroundColor}; }`);
  361. }
  362. });
  363. registerModelAndPositionCommand('_executeLinkedEditingProvider', (model, position) => getLinkedEditingRanges(model, position, CancellationToken.None));
  364. registerEditorContribution(LinkedEditingContribution.ID, LinkedEditingContribution);
  365. registerEditorAction(LinkedEditingAction);