Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f16c20b8ecad5641b8eba5e3458643027ee8a8f4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*******************************************************************************
 * Copyright (c) 2022 Dirk Steinkamp
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     Dirk Steinkamp <dirk.steinkamp@gmx.de> - initial API and implementation
 *******************************************************************************/
package org.eclipse.ui.internal.texteditor.multiselection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Control;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

import org.eclipse.core.runtime.Adapters;

import org.eclipse.jface.viewers.ISelection;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IMultiTextSelection;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.MultiTextSelection;
import org.eclipse.jface.text.Region;

import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.handlers.HandlerUtil;

import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorExtension5;

/**
 * Common super class for Multi-Selection-actions, containing various helper
 * methods. Subclasses need to overwrite {@link #execute()}, which is only
 * invoked if the {@link #textEditor} and {@link #document} could be properly
 * initialized.
 *
 * @see AddAllMatchesToMultiSelectionHandler
 * @see MultiSelectionDownHandler
 * @see MultiSelectionUpHandler
 * @see StopMultiSelectionHandler
 */
abstract class AbstractMultiSelectionHandler extends AbstractHandler {
	/**
	 * Each widget can have a different anchor selection, that is stored in the
	 * widget's data with this key.
	 */
	private static final String ANCHOR_REGION_KEY = "org.eclipse.ui.internal.texteditor.multiselection.AbstractMultiSelectionHandler.anchorRegion"; //$NON-NLS-1$
	private ExecutionEvent event;
	private ITextEditor textEditor;
	private IDocument document;

	/**
	 * This method needs to be overwritten from subclasses to handle the event.
	 *
	 * @throws ExecutionException an Exception the event handler might throw
	 */
	public abstract void execute() throws ExecutionException;

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		if (initFrom(event)) {
			execute();
		}
		return null;
	}

	public ExecutionEvent getEvent() {
		return event;
	}

	protected boolean isMultiSelectionActive() {
		IRegion[] regions = getSelectedRegions();
		return regions != null && regions.length > 1;
	}

	protected boolean nothingSelected() {
		IRegion[] regions = getSelectedRegions();
		return regions == null || regions.length == 0 || (regions.length == 1 && regions[0].getLength() == 0);
	}

	protected IRegion[] getSelectedRegions() {
		ISelection selection = textEditor.getSelectionProvider().getSelection();

		if (!(selection instanceof IMultiTextSelection)) {
			return null;
		}

		return ((IMultiTextSelection) selection).getRegions();
	}

	protected IRegion offsetAsCaretRegion(int offset) {
		return createRegionIfValid(offset, 0);
	}

	protected void selectRegion(IRegion region) {
		selectRegions(new IRegion[] { region });
	}

	protected void selectRegions(IRegion[] regions) {
		setBlockSelectionMode(false);

		ISelection newSelection = new MultiTextSelection(document, regions);
		textEditor.getSelectionProvider().setSelection(newSelection);
	}

	protected void selectIdentifierUnderCaret() {
		int offset = getCaretOffset();

		Region identifierRegion = getIdentifierUnderCaretRegion(offset);
		if (identifierRegion != null) {
			selectRegion(identifierRegion);
			setAnchorRegion(identifierRegion);
		}
	}

	protected void selectCaretPosition() {
		IRegion caretRegion = offsetAsCaretRegion(getCaretOffset());
		selectRegion(caretRegion);
		setAnchorRegion(caretRegion);
	}

	protected boolean allRegionsHaveSameText() {
		return allRegionsHaveSameText(getSelectedRegions());
	}

	protected boolean allRegionsEmpty() {
		IRegion[] selectedRegions = getSelectedRegions();
		if (selectedRegions == null)
			return true;
		return isEmpty(selectedRegions[0]) && allRegionsHaveSameText(selectedRegions);
	}

	protected boolean isEmpty(IRegion region) {
		return region == null || region.getLength() == 0;
	}

	protected IRegion getAnchorRegion() {
		return (IRegion) getWidget().getData(ANCHOR_REGION_KEY);
	}

	protected void setAnchorRegion(IRegion selection) {
		if (selection == null) {
			getWidget().setData(ANCHOR_REGION_KEY, null);
		} else {
			getWidget().setData(ANCHOR_REGION_KEY, selection);
		}
	}

	private void initAnchorRegion() {
		IRegion[] regions = getSelectedRegions();
		if ((regions != null && regions.length == 1) || !contains(regions, getAnchorRegion())) {
			setAnchorRegion(regions[0]);
		}
	}

	private boolean contains(IRegion[] regions, IRegion region) {
		return Arrays.asList(regions).contains(region);
	}

	private boolean allRegionsHaveSameText(IRegion[] regions) {
		if (regions == null || regions.length == 1)
			return true;

		try {
			return allRegionsHaveText(regions, regionAsString(regions[0]));
		} catch (BadLocationException e) {
			return false;
		}
	}

	private boolean allRegionsHaveText(IRegion[] regions, String text) throws BadLocationException {
		for (IRegion iRegion : regions) {
			if (!text.equals(regionAsString(iRegion))) {
				return false;
			}
		}
		return true;
	}

	protected IRegion[] addRegion(IRegion[] regions, IRegion newRegion) {
		if (newRegion != null) {
			IRegion[] newRegions = Arrays.copyOf(regions, regions.length + 1);
			newRegions[newRegions.length - 1] = newRegion;
			return newRegions;
		} else {
			return regions;
		}
	}

	protected IRegion[] removeLastRegionButOne(IRegion[] regions) {
		if (regions == null || regions.length == 0)
			return null;
		if (regions.length == 1) {
			return regions;
		}

		return Arrays.copyOf(regions, regions.length - 1);
	}

	protected IRegion[] removeFirstRegionButOne(IRegion[] regions) {
		if (regions == null || regions.length == 0)
			return null;
		if (regions.length == 1) {
			return regions;
		}

		return Arrays.copyOfRange(regions, 1, regions.length);
	}

	protected int getCaretOffset() {
		return getWidget().getCaretOffset();
	}

	protected void setCaretOffset(int offset) {
		getWidget().setCaretOffset(offset);
	}

	protected IRegion findNextMatch(IRegion region) throws ExecutionException {
		try {
			if (region.getLength() == 0) {
				return offsetAsCaretRegion(offsetInNextLine(region.getOffset()));
			} else {
				String searchString = getTextOfRegion(region);

				String fullText = getFullText();
				int matchPos = fullText.indexOf(searchString, offsetAfter(region));
				return createRegionIfValid(matchPos, region.getLength());
			}
		} catch (BadLocationException e) {
			throw new ExecutionException("Internal error in findNextMatch", e);
		}
	}

	protected IRegion findPreviousMatch(IRegion region) throws ExecutionException {
		try {
			if (region.getLength() == 0) {
				return offsetAsCaretRegion(offsetInPreviousLine(region.getOffset()));
			} else {
				String searchString = getTextOfRegion(region);

				String fullText = getFullText();
				int matchPos = fullText.lastIndexOf(searchString, region.getOffset() - 1);
				return createRegionIfValid(matchPos, region.getLength());
			}
		} catch (BadLocationException e) {
			throw new ExecutionException("Internal error in findPreviousMatch", e);
		}
	}

	private IRegion createRegionIfValid(int offset, int length) {
		if ((offset < 0) || (offset > document.getLength()))
			return null;

		return new Region(offset, Math.min(length, document.getLength() - offset));
	}

	protected IRegion[] findAllMatches(IRegion region) throws ExecutionException {
		try {
			String searchString = getTextOfRegion(region);

			String fullText = getFullText();
			List<IRegion> regions = findAllMatches(fullText, searchString);
			return toArray(regions);
		} catch (BadLocationException e) {
			throw new ExecutionException("Internal error in findAllMatches", e);
		}
	}

	private List<IRegion> findAllMatches(String fullText, String searchString) {
		List<IRegion> regions = new ArrayList<>();
		int length = searchString.length();
		int matchPos = 0;
		while ((matchPos = fullText.indexOf(searchString, matchPos)) >= 0) {
			regions.add(new Region(matchPos, length));
			matchPos += length;
		}
		return regions;
	}

	private int offsetInNextLine(int offset) throws BadLocationException {
		return moveOffsetByLines(offset, 1);
	}

	private int offsetInPreviousLine(int offset) throws BadLocationException {
		return moveOffsetByLines(offset, -1);
	}

	private int moveOffsetByLines(int offset, int lineDelta) throws BadLocationException {
		int lineNo = document.getLineOfOffset(offset);
		int newLineNo = lineNo + lineDelta;
		if ((newLineNo < 0) || (newLineNo >= document.getNumberOfLines()))
			return -1;

		int newLineOffset = document.getLineOffset(newLineNo);
		int delta = offset - document.getLineOffset(lineNo);

		return newLineOffset + delta;
	}

	private boolean initFrom(ExecutionEvent event) {
		this.event = event;
		initTextEditor();
		if (textEditor == null)
			return false;
		document = getDocument();
		initAnchorRegion();
		return true;
	}

	private void initTextEditor() {
		IEditorPart editor = HandlerUtil.getActiveEditor(event);
		textEditor = Adapters.adapt(editor, ITextEditor.class);
	}

	private IDocument getDocument() {
		return textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
	}

	private IRegion[] toArray(List<IRegion> regions) {
		return regions.toArray(new IRegion[regions.size()]);
	}

	private int offsetAfter(IRegion region) {
		return region.getOffset() + region.getLength();
	}

	private String getTextOfRegion(IRegion region) throws BadLocationException {
		return document.get(region.getOffset(), region.getLength());
	}

	private String getFullText() {
		return document.get();
	}

	private String regionAsString(IRegion region) throws BadLocationException {
		return document.get(region.getOffset(), region.getLength());
	}

	private Region getIdentifierUnderCaretRegion(int offset) {
		try {
			int startOffset = findStartOfIdentifier(offset);
			int endOffset = findEndOfIdentifier(startOffset);
			Region identifierRegion = new Region(startOffset, endOffset - startOffset);
			return identifierRegion;
		} catch (BadLocationException e) {
			return null;
		}
	}

	private int findStartOfIdentifier(int offset) throws BadLocationException {
		for (int i = offset - 1; i >= 0; i--) {
			if (!isJavaIdentifierCharAtPos(i)) {
				return i + 1;
			}
		}
		return 0; // start of document reached
	}

	private int findEndOfIdentifier(int offset) throws BadLocationException {
		for (int i = offset; i <= document.getLength(); i++) {
			if (i == document.getLength() || !isJavaIdentifierCharAtPos(i)) {
				return i;
			}
		}
		return offset;
	}

	private boolean isJavaIdentifierCharAtPos(int i) throws BadLocationException {
		return Character.isJavaIdentifierStart(document.getChar(i))
				|| Character.isJavaIdentifierPart(document.getChar(i));
	}

	private StyledText getWidget() {
		return (StyledText) textEditor.getAdapter(Control.class);
	}

	private void setBlockSelectionMode(boolean blockSelectionMode) {
		if (!(textEditor instanceof ITextEditorExtension5)) {
			return;
		}
		ITextEditorExtension5 ext = (ITextEditorExtension5) textEditor;
		ext.setBlockSelectionMode(blockSelectionMode);
	}

	protected boolean selectionIsAboveAnchorRegion() {
		IRegion[] selectedRegions = getSelectedRegions();
		if (selectedRegions == null || selectedRegions.length == 1)
			return false;
		return isLastRegion(getAnchorRegion(), selectedRegions);
	}

	protected boolean selectionIsBelowAnchorRegion() {
		IRegion[] selectedRegions = getSelectedRegions();
		if (selectedRegions == null || selectedRegions.length == 1)
			return false;
		return isFirstRegion(getAnchorRegion(), selectedRegions);
	}

	private boolean isLastRegion(IRegion region, IRegion[] regions) {
		if (region == null || regions == null || regions.length == 0)
			return false;

		return region.equals(regions[regions.length - 1]);
	}

	private boolean isFirstRegion(IRegion region, IRegion[] regions) {
		if (region == null || regions == null || regions.length == 0)
			return false;

		return region.equals(regions[0]);
	}
}

Back to the top