Skip to main content
summaryrefslogtreecommitdiffstats
blob: 0f34d8f15df13bb1c3e1f2d3ee7e9d8f42823553 (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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/*******************************************************************************
 * Copyright (c) 2009, 2012 Avaloq Evolution AG and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Tom Eicher (Avaloq Evolution AG) - initial API and implementation
 *******************************************************************************/
package org.eclipse.jface.internal.text;

import java.util.Arrays;

import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.GC;

import org.eclipse.core.runtime.Assert;

import org.eclipse.text.edits.DeleteEdit;
import org.eclipse.text.edits.InsertEdit;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BlockTextSelection;
import org.eclipse.jface.text.IBlockTextSelection;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;

/**
 * Processes {@link ITextSelection}s.
 * 
 * @since 3.5
 */
public final class SelectionProcessor {
	private static class Implementation {
		/**
		 * Returns a text edit describing the text modification that would be executed if the given
		 * selection was replaced by <code>replacement</code>.
		 * 
		 * @param selection the selection to replace
		 * @param replacement the replacement text
		 * @return a text edit describing the operation needed to replace <code>selection</code>
		 * @throws BadLocationException if computing the edit failed
		 */
		TextEdit replace(ISelection selection, String replacement) throws BadLocationException {
			return new MultiTextEdit();
		}

		/**
		 * Returns the text covered by <code>selection</code>
		 * 
		 * @param selection the selection
		 * @return the text covered by <code>selection</code>
		 * @throws BadLocationException if computing the edit failed
		 */
		String getText(ISelection selection) throws BadLocationException {
			return ""; //$NON-NLS-1$
		}

		/**
		 * Returns <code>true</code> if the text covered by <code>selection</code> does not contain any
		 * characters. Note the difference to {@link ITextSelection#isEmpty()}, which returns
		 * <code>true</code> only for invalid selections.
		 * 
		 * @param selection the selection
		 * @return <code>true</code> if <code>selection</code> does not contain any text,
		 *         <code>false</code> otherwise
		 * @throws BadLocationException if accessing the document failed
		 */
		boolean isEmpty(ISelection selection) throws BadLocationException {
			return selection.isEmpty();
		}

		/**
		 * Returns <code>true</code> if <code>selection</code> covers text on two or more lines,
		 * <code>false</code> otherwise.
		 * 
		 * @param selection the selection
		 * @return <code>true</code> if <code>selection</code> covers text on two or more lines,
		 *         <code>false</code> otherwise
		 * @throws BadLocationException if selection is not a valid selection on the target document 
		 */
		boolean isMultiline(ISelection selection) throws BadLocationException {
			if (selection == null)
				throw new NullPointerException();
			return false;
		}

		TextEdit delete(ISelection selection) throws BadLocationException {
			return replace(selection, ""); //$NON-NLS-1$
		}

		TextEdit backspace(ISelection selection) throws BadLocationException {
			return replace(selection, ""); //$NON-NLS-1$
		}

		/**
		 * Returns a selection similar to <code>selection</code> but {@linkplain #isEmpty(ISelection)
		 * empty}. Typically, the selection is reduced to its left-most offset.
		 * 
		 * @param selection the selection
		 * @param beginning <code>true</code> to collapse the selection to its smallest position
		 *            (i.e. its left-most offset), <code>false</code> to collapse it to its greatest
		 *            position (e.g its right-most offset)
		 * @return an empty variant of <code>selection</code>
		 * @throws BadLocationException if accessing the document failed
		 */
		ISelection makeEmpty(ISelection selection, boolean beginning) throws BadLocationException {
			return selection;
		}

		/**
		 * Returns the text regions covered by the given selection.
		 * 
		 * @param selection the selection
		 * @return the text regions corresponding to <code>selection</code>
		 * @throws BadLocationException if accessing the document failed
		 */
		IRegion[] getRanges(ISelection selection) throws BadLocationException {
			return new IRegion[0];
		}

		/**
		 * Returns the number of lines touched by <code>selection</code>. 
		 * 
		 * @param selection the selection
		 * @return the number of lines touched by <code>selection</code>
		 * @throws BadLocationException if accessing the document failed
		 */
		int getCoveredLines(ISelection selection) throws BadLocationException {
			return 0;
		}

		/**
		 * Returns the selection after replacing <code>selection</code> by <code>replacement</code>.
		 * 
		 * @param selection the selection to be replaced
		 * @param replacement the replacement text
		 * @return the selection that the user expects after the specified replacement operation
		 * @throws BadLocationException if accessing the document failed
		 */
		ISelection makeReplaceSelection(ISelection selection, String replacement) throws BadLocationException {
			return makeEmpty(selection, false);
		}
	}

	private final Implementation NULL_IMPLEMENTATION= new Implementation();

	private final Implementation RANGE_IMPLEMENTATION= new Implementation() {
		@Override
		TextEdit replace(ISelection selection, String replacement) {
			ITextSelection ts= (ITextSelection)selection;
			return new ReplaceEdit(ts.getOffset(), ts.getLength(), replacement);
		}

		@Override
		String getText(ISelection selection) {
			ITextSelection ts= (ITextSelection)selection;
			return ts.getText();
		}

		@Override
		boolean isEmpty(ISelection selection) {
			ITextSelection ts= (ITextSelection)selection;
			return ts.getLength() <= 0;
		}

		@Override
		boolean isMultiline(ISelection selection) throws BadLocationException {
			ITextSelection ts= (ITextSelection)selection;
			return fDocument.getLineOfOffset(ts.getOffset()) < fDocument.getLineOfOffset(ts.getOffset() + ts.getLength());
		}

		@Override
		TextEdit delete(ISelection selection) {
			ITextSelection ts= (ITextSelection)selection;
			if (isEmpty(selection))
				return new DeleteEdit(ts.getOffset(), 1);
			return new DeleteEdit(ts.getOffset(), ts.getLength());
		}

		@Override
		TextEdit backspace(ISelection selection) throws BadLocationException {
			ITextSelection ts= (ITextSelection)selection;
			if (isEmpty(selection))
				return new DeleteEdit(ts.getOffset() - 1, 1);
			return new DeleteEdit(ts.getOffset(), ts.getLength());
		}

		@Override
		ISelection makeEmpty(ISelection selection, boolean beginning) {
			ITextSelection ts= (ITextSelection)selection;
			return beginning ? 
					  new TextSelection(fDocument, ts.getOffset(), 0)
					: new TextSelection(fDocument, ts.getOffset() + ts.getLength(), 0);
		}

		@Override
		IRegion[] getRanges(ISelection selection) {
			ITextSelection ts= (ITextSelection)selection;
			return new IRegion[] { new Region(ts.getOffset(), ts.getLength()) };
		}
		
		@Override
		int getCoveredLines(ISelection selection) throws BadLocationException {
			ITextSelection ts= (ITextSelection)selection;
			return ts.getEndLine() - ts.getStartLine() + 1;
		}
		
		@Override
		ISelection makeReplaceSelection(ISelection selection, String replacement) {
			ITextSelection ts= (ITextSelection)selection;
			return new TextSelection(fDocument, ts.getOffset() + replacement.length(), 0);
		}
	};

	private final Implementation COLUMN_IMPLEMENTATION= new Implementation() {
		private TextEdit replace(ISelection selection, String replacement, boolean delete) throws BadLocationException {
			try {
				MultiTextEdit root;
				IBlockTextSelection cts= (IBlockTextSelection)selection;
				int startLine= cts.getStartLine();
				int endLine= cts.getEndLine();
				int startColumn= cts.getStartColumn();
				int endColumn= cts.getEndColumn();
				int visualStartColumn= computeVisualColumn(startLine, startColumn);
				int visualEndColumn= computeVisualColumn(endLine, endColumn);
				root= new MultiTextEdit();
				String[] delimiters= fDocument.getLegalLineDelimiters();

				int lastDelim= 0;
				for (int line= startLine; line <= endLine; line++) {
					String string;
					if (lastDelim == -1) {
						string= ""; //$NON-NLS-1$
					} else {
						int[] index= TextUtilities.indexOf(delimiters, replacement, lastDelim);
						if (index[0] == -1) {
							string= replacement.substring(lastDelim);
							lastDelim= -1;
						} else {
							string= replacement.substring(lastDelim, index[0]);
							lastDelim= index[0] + delimiters[index[1]].length();
						}
					}
					TextEdit replace= createReplaceEdit(line, visualStartColumn, visualEndColumn, string, delete);
					root.addChild(replace);
				}
				while (lastDelim != -1) {
					// more stuff to insert
					String string;
					int[] index= TextUtilities.indexOf(delimiters, replacement, lastDelim);
					if (index[0] == -1) {
						string= replacement.substring(lastDelim);
						lastDelim= -1;
					} else {
						string= replacement.substring(lastDelim, index[0]);
						lastDelim= index[0] + delimiters[index[1]].length();
					}
					endLine++;
					TextEdit edit;
					if (endLine < fDocument.getNumberOfLines()) {
						edit= createReplaceEdit(endLine, visualStartColumn, visualEndColumn, string, delete);
					} else {
						// insertion reaches beyond the last line
						int insertLocation= root.getExclusiveEnd();
						int spaces= visualStartColumn;
						char[] array= new char[spaces];
						Arrays.fill(array, ' ');
						string= TextUtilities.getDefaultLineDelimiter(fDocument) + String.valueOf(array) + string;
						edit= new InsertEdit(insertLocation, string);
						insertLocation+= string.length();
					}
					root.addChild(edit);
				}
				return root;
			} catch (MalformedTreeException x) {
				Assert.isTrue(false);
				return null;
			}
		}

		@Override
		TextEdit replace(ISelection selection, String replacement) throws BadLocationException {
			return replace(selection, replacement, false);
		}

		@Override
		String getText(ISelection selection) throws BadLocationException {
			IBlockTextSelection cts= (IBlockTextSelection)selection;
			StringBuffer buf= new StringBuffer(cts.getLength());
			int startLine= cts.getStartLine();
			int endLine= cts.getEndLine();
			int startColumn= cts.getStartColumn();
			int endColumn= cts.getEndColumn();
			int visualStartColumn= computeVisualColumn(startLine, startColumn);
			int visualEndColumn= computeVisualColumn(endLine, endColumn);

			for (int line= startLine; line <= endLine; line++) {
				appendColumnRange(buf, line, visualStartColumn, visualEndColumn);
				if (line != endLine)
					buf.append(fDocument.getLineDelimiter(line));
			}

			return buf.toString();
		}

		@Override
		boolean isEmpty(ISelection selection) throws BadLocationException {
			IBlockTextSelection cts= (IBlockTextSelection)selection;
			int startLine= cts.getStartLine();
			int endLine= cts.getEndLine();
			int startColumn= cts.getStartColumn();
			int endColumn= cts.getEndColumn();
			int visualStartColumn= computeVisualColumn(startLine, startColumn);
			int visualEndColumn= computeVisualColumn(endLine, endColumn);
			return visualEndColumn == visualStartColumn;
		}

		@Override
		boolean isMultiline(ISelection selection) {
			ITextSelection ts= (ITextSelection)selection;
			return ts.getEndLine() > ts.getStartLine();
		}

		@Override
		TextEdit delete(ISelection selection) throws BadLocationException {
			if (isEmpty(selection)) {
				IBlockTextSelection cts= (IBlockTextSelection)selection;
				selection= new BlockTextSelection(fDocument, cts.getStartLine(), cts.getStartColumn(), cts.getEndLine(), cts.getEndColumn() + 1, fTabWidth);
			}
			return replace(selection, "", true); //$NON-NLS-1$
		}

		@Override
		TextEdit backspace(ISelection selection) throws BadLocationException {
			IBlockTextSelection cts= (IBlockTextSelection)selection;
			if (isEmpty(selection) && cts.getStartColumn() > 0) {
				selection= new BlockTextSelection(fDocument, cts.getStartLine(), cts.getStartColumn() - 1, cts.getEndLine(), cts.getEndColumn(), fTabWidth);
			}
			return replace(selection, ""); //$NON-NLS-1$
		}

		@Override
		ISelection makeEmpty(ISelection selection, boolean beginning) throws BadLocationException {
			IBlockTextSelection cts= (IBlockTextSelection)selection;
			int startLine, startColumn, endLine, endColumn;
			if (beginning) {
				startLine= cts.getStartLine();
				startColumn= cts.getStartColumn();
				endLine= cts.getEndLine();
				endColumn= computeCharacterColumn(endLine, computeVisualColumn(startLine, startColumn));
			} else {
				endLine= cts.getEndLine();
				endColumn= cts.getEndColumn();
				startLine= cts.getStartLine();
				startColumn= computeCharacterColumn(startLine, computeVisualColumn(endLine, endColumn));
			}
			return new BlockTextSelection(fDocument, startLine, startColumn, endLine, endColumn, fTabWidth);
		}
		
		@Override
		ISelection makeReplaceSelection(ISelection selection, String replacement) throws BadLocationException {
			IBlockTextSelection bts= (IBlockTextSelection)selection;
			String[] delimiters= fDocument.getLegalLineDelimiters();
			int[] index= TextUtilities.indexOf(delimiters, replacement, 0);
			int length;
			if (index[0] == -1)
				length= replacement.length();
			else
				length= index[0];

			int startLine= bts.getStartLine();
			int column= bts.getStartColumn() + length;
			int endLine= bts.getEndLine();
			int endColumn= computeCharacterColumn(endLine, computeVisualColumn(startLine, column));
			return new BlockTextSelection(fDocument, startLine, column, endLine, endColumn, fTabWidth);
		}

		@Override
		IRegion[] getRanges(ISelection selection) throws BadLocationException {
			IBlockTextSelection cts= (IBlockTextSelection)selection;
			final int startLine= cts.getStartLine();
			final int endLine= cts.getEndLine();
			int visualStartColumn= computeVisualColumn(startLine, cts.getStartColumn());
			int visualEndColumn= computeVisualColumn(endLine, cts.getEndColumn());
			IRegion[] ranges= new IRegion[endLine - startLine + 1];

			for (int line= startLine; line <= endLine; line++) {
				int startColumn= computeCharacterColumn(line, visualStartColumn);
				int endColumn= computeCharacterColumn(line, visualEndColumn);
				IRegion lineInfo= fDocument.getLineInformation(line);
				int lineEnd= lineInfo.getLength();
				startColumn= Math.min(startColumn, lineEnd);
				endColumn= Math.min(endColumn, lineEnd);
				ranges[line - startLine]= new Region(lineInfo.getOffset() + startColumn, endColumn - startColumn);
			}

			return ranges;
		}
		
		@Override
		int getCoveredLines(ISelection selection) throws BadLocationException {
			ITextSelection ts= (ITextSelection)selection;
			return ts.getEndLine() - ts.getStartLine() + 1;
		}

		private TextEdit createReplaceEdit(int line, int visualStartColumn, int visualEndColumn, String replacement, boolean delete) throws BadLocationException {
			IRegion info= fDocument.getLineInformation(line);
			int lineLength= info.getLength();
			String content= fDocument.get(info.getOffset(), lineLength);
			int startColumn= -1;
			int endColumn= -1;
			int visual= 0;
			for (int offset= 0; offset < lineLength; offset++) {
				if (startColumn == -1) {
					if (visual == visualStartColumn)
						if (!delete && isWider(content.charAt(offset), visual) && replacement.length() == 0)
							startColumn= offset - 1;
						else
							startColumn= offset;
					else if (visual > visualStartColumn) {
						if (isWider(content.charAt(offset - 1), visual))
							startColumn= offset - 1;
						else
							startColumn= offset;
					}
				}
				if (startColumn != -1) {
					if (visual == visualEndColumn) {
						endColumn= offset;
						break;
					} else if (visual > visualEndColumn) {
						if (!delete && isWider(content.charAt(offset - 1), visual))
							endColumn= offset - 1;
						else
							endColumn= offset;
						break;
					}
				}
				visual+= visualSizeIncrement(content.charAt(offset), visual);
			}
			if (startColumn == -1) {
				boolean materializeVirtualSpace= replacement.length() != 0;
				if (materializeVirtualSpace) {
					int spaces= Math.max(0, visualStartColumn - visual);
					char[] array= new char[spaces];
					Arrays.fill(array, ' ');
					return new InsertEdit(info.getOffset() + lineLength, String.valueOf(array) + replacement);
				}
				return new MultiTextEdit();
			}
			if (endColumn == -1)
				endColumn= lineLength;
			if (replacement.length() == 0)
				return new DeleteEdit(info.getOffset() + startColumn, endColumn - startColumn);
			return new ReplaceEdit(info.getOffset() + startColumn, endColumn - startColumn, replacement);
		}

		private void appendColumnRange(StringBuffer buf, int line, int visualStartColumn, int visualEndColumn) throws BadLocationException {
			IRegion info= fDocument.getLineInformation(line);
			int lineLength= info.getLength();
			String content= fDocument.get(info.getOffset(), lineLength);
			int startColumn= -1;
			int endColumn= -1;
			int visual= 0;
			for (int offset= 0; offset < lineLength; offset++) {
				if (startColumn == -1 && visual >= visualStartColumn)
					startColumn= offset;
				if (visual >= visualEndColumn) {
					endColumn= offset;
					break;
				}
				visual+= visualSizeIncrement(content.charAt(offset), visual);
			}
			if (startColumn != -1)
				buf.append(content.substring(startColumn, endColumn == -1 ? lineLength : endColumn));
			if (endColumn == -1) {
				int spaces= Math.max(0, visualEndColumn - Math.max(visual, visualStartColumn));
				for (int i= 0; i < spaces; i++)
					buf.append(' ');
			}
		}

		private int computeVisualColumn(final int line, final int column) throws BadLocationException {
			IRegion info= fDocument.getLineInformation(line);
			int lineLength= info.getLength();
			int to= Math.min(lineLength, column);
			String content= fDocument.get(info.getOffset(), lineLength);
			int visual= 0;
			for (int offset= 0; offset < to; offset++)
				visual+= visualSizeIncrement(content.charAt(offset), visual);
			if (column > lineLength)
				visual+= column - lineLength; // virtual spaces
			return visual;
		}

		private int computeCharacterColumn(int line, int visualColumn) throws BadLocationException {
			IRegion info= fDocument.getLineInformation(line);
			int lineLength= info.getLength();
			String content= fDocument.get(info.getOffset(), lineLength);
			int visual= 0;
			for (int offset= 0; offset < lineLength; offset++) {
				if (visual >= visualColumn)
					return offset;
				visual+= visualSizeIncrement(content.charAt(offset), visual);
			}
			return lineLength + Math.max(0, visualColumn - visual);
		}

		private boolean isWider(char character, int visual) {
			return visualSizeIncrement(character, visual) > 1;
		}

		/**
		 * Returns the increment in visual length represented by <code>character</code> given the
		 * current visual length. The visual length is <code>1</code> unless <code>character</code>
		 * is a tabulator (<code>\t</code>).
		 * 
		 * @param character the character the length of which to compute
		 * @param visual the current visual length
		 * @return the increment in visual length represented by <code>character</code>, which is in
		 *         <code>[0,fTabWidth]</code>
		 */
		private int visualSizeIncrement(char character, int visual) {
			if (character > 255 && fStyledText != null) {
				GC gc= null;
				try {
					gc= new GC(fStyledText);
					int charWidth= gc.stringExtent(new String(Character.toString(character))).x;
					int singleCharWidth= gc.stringExtent(" ").x; //$NON-NLS-1$
					return (int)Math.ceil(charWidth / singleCharWidth);
				} finally {
					if (gc != null)
						gc.dispose();
				}
			}
			if (character != '\t')
				return 1;
			if (fTabWidth <= 0)
				return 0;
			return fTabWidth - visual % fTabWidth;
		}
	};

	private final IDocument fDocument;

	private final int fTabWidth;

	private IRewriteTarget fRewriteTarget;

	private ISelectionProvider fSelectionProvider;

	private StyledText fStyledText;

	/**
	 * Creates a new processor on the given viewer.
	 * 
	 * @param viewer the viewer
	 */
	public SelectionProcessor(ITextViewer viewer) {
		this(viewer.getDocument(), viewer.getTextWidget().getTabs());
		if (viewer instanceof ITextViewerExtension) {
			ITextViewerExtension ext= (ITextViewerExtension)viewer;
			fRewriteTarget= ext.getRewriteTarget();
		}
		fSelectionProvider= viewer.getSelectionProvider();
		fStyledText= viewer.getTextWidget();
	}

	/**
	 * Creates a new processor on the given document and using the given tab width.
	 * 
	 * @param document the document
	 * @param tabWidth the tabulator width in space equivalents, must be <code>&gt;=0</code>
	 */
	public SelectionProcessor(IDocument document, int tabWidth) {
		Assert.isNotNull(document);
		Assert.isTrue(tabWidth >= 0);
		fDocument= document;
		fTabWidth= tabWidth;
	}

	/**
	 * Returns a text edit describing the text modification that would be executed if the delete key
	 * was pressed on the given selection.
	 * 
	 * @param selection the selection to delete
	 * @return a text edit describing the operation needed to delete <code>selection</code>
	 * @throws BadLocationException if computing the edit failed
	 */
	public TextEdit delete(ISelection selection) throws BadLocationException {
		return getImplementation(selection).delete(selection);
	}

	/**
	 * Returns a text edit describing the text modification that would be executed if the backspace
	 * key was pressed on the given selection.
	 * 
	 * @param selection the selection to delete
	 * @return a text edit describing the operation needed to delete <code>selection</code>
	 * @throws BadLocationException if computing the edit failed
	 */
	public TextEdit backspace(ISelection selection) throws BadLocationException {
		return getImplementation(selection).backspace(selection);
	}

	/**
	 * Returns a text edit describing the text modification that would be executed if the given
	 * selection was replaced by <code>replacement</code>.
	 * 
	 * @param selection the selection to replace
	 * @param replacement the replacement text
	 * @return a text edit describing the operation needed to replace <code>selection</code>
	 * @throws BadLocationException if computing the edit failed
	 */
	public TextEdit replace(ISelection selection, String replacement) throws BadLocationException {
		return getImplementation(selection).replace(selection, replacement);
	}

	/**
	 * Returns the text covered by <code>selection</code>
	 * 
	 * @param selection the selection
	 * @return the text covered by <code>selection</code>
	 * @throws BadLocationException if computing the edit failed
	 */
	public String getText(ISelection selection) throws BadLocationException {
		return getImplementation(selection).getText(selection);
	}

	/**
	 * Returns <code>true</code> if the text covered by <code>selection</code> does not contain any
	 * characters. Note the difference to {@link ITextSelection#isEmpty()}, which returns
	 * <code>true</code> only for invalid selections.
	 * 
	 * @param selection the selection
	 * @return <code>true</code> if <code>selection</code> does not contain any text,
	 *         <code>false</code> otherwise
	 * @throws BadLocationException if accessing the document failed
	 */
	public boolean isEmpty(ISelection selection) throws BadLocationException {
		return getImplementation(selection).isEmpty(selection);
	}

	/**
	 * Returns <code>true</code> if <code>selection</code> extends to two or more lines,
	 * <code>false</code> otherwise.
	 * 
	 * @param selection the selection
	 * @return <code>true</code> if <code>selection</code> extends to two or more lines,
	 *         <code>false</code> otherwise
	 * @throws BadLocationException if <code>selection</code> is not valid regarding the target
	 *             document
	 */
	public boolean isMultiline(ISelection selection) throws BadLocationException {
		return getImplementation(selection).isMultiline(selection);
	}

	/**
	 * Returns a selection similar to <code>selection</code> but {@linkplain #isEmpty(ISelection)
	 * empty}. Typically, the selection is reduced to its extreme offsets.
	 * 
	 * @param selection the selection
	 * @param beginning <code>true</code> to collapse the selection to its smallest position (i.e.
	 *            its left-most offset), <code>false</code> to collapse it to its greatest position
	 *            (e.g its right-most offset)
	 * @return an empty variant of <code>selection</code>
	 * @throws BadLocationException if accessing the document failed
	 */
	public ISelection makeEmpty(ISelection selection, boolean beginning) throws BadLocationException {
		return getImplementation(selection).makeEmpty(selection, beginning);
	}
	
	private ISelection makeReplaceSelection(ISelection selection, String replacement) throws BadLocationException {
		return getImplementation(selection).makeReplaceSelection(selection, replacement);
	}

	/**
	 * Convenience method that applies the edit returned from {@link #delete(ISelection)} to the
	 * underlying document.
	 * 
	 * @param selection the selection to delete
	 * @throws BadLocationException if accessing the document failed
	 */
	public void doDelete(ISelection selection) throws BadLocationException {
		TextEdit edit= delete(selection);
		boolean complex= edit.hasChildren();
		if (complex && fRewriteTarget != null)
			fRewriteTarget.beginCompoundChange();
		try {
			edit.apply(fDocument, TextEdit.UPDATE_REGIONS);
			if (fSelectionProvider != null) {
				ISelection empty= makeEmpty(selection, true);
				fSelectionProvider.setSelection(empty);
			}
		} finally {
		if (complex && fRewriteTarget != null)
			fRewriteTarget.endCompoundChange();
		}
	}
	
	/**
	 * Convenience method that applies the edit returned from {@link #replace(ISelection, String)}
	 * to the underlying document and adapts the selection accordingly.
	 * 
	 * @param selection the selection to replace
	 * @param replacement the replacement text
	 * @throws BadLocationException if accessing the document failed
	 */
	public void doReplace(ISelection selection, String replacement) throws BadLocationException {
		TextEdit edit= replace(selection, replacement);
		boolean complex= edit.hasChildren();
		if (complex && fRewriteTarget != null)
			fRewriteTarget.beginCompoundChange();
		try {
			edit.apply(fDocument, TextEdit.UPDATE_REGIONS);

			if (fSelectionProvider != null) {
				ISelection empty= makeReplaceSelection(selection, replacement);
				fSelectionProvider.setSelection(empty);
			}
		} finally {
			if (complex && fRewriteTarget != null)
				fRewriteTarget.endCompoundChange();
		}
	}
	
	/**
	 * Returns the text regions covered by the given selection.
	 * 
	 * @param selection the selection
	 * @return the text regions corresponding to <code>selection</code>
	 * @throws BadLocationException if accessing the document failed
	 */
	public IRegion[] getRanges(ISelection selection) throws BadLocationException {
		return getImplementation(selection).getRanges(selection);
	}

	/**
	 * Returns the number of lines touched by <code>selection</code>. Note that for linear
	 * selections, this is the number of contained delimiters plus 1.
	 * 
	 * @param selection the selection
	 * @return the number of lines touched by <code>selection</code>
	 * @throws BadLocationException if accessing the document failed
	 */
	public int getCoveredLines(ISelection selection) throws BadLocationException {
		return getImplementation(selection).getCoveredLines(selection);
	}

	/**
	 * Returns the implementation.
	 * 
	 * @param selection the selection
	 * @return the corresponding processor implementation
	 */
	private Implementation getImplementation(ISelection selection) {
		if (selection instanceof IBlockTextSelection)
			return COLUMN_IMPLEMENTATION;
		else if (selection instanceof ITextSelection)
			return RANGE_IMPLEMENTATION;
		else
			return NULL_IMPLEMENTATION;
	}
}

Back to the top