Java Code Examples for org.eclipse.jface.text.ITextSelection#getText()

The following examples show how to use org.eclipse.jface.text.ITextSelection#getText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TagsSearchHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The initial search string will be the closest full word forward, if it is on the same line
 * 
 * @param document
 * @param selection
 * @return the initial search string
 * 
 * @throws BadLocationException
 */
protected ITextSelection initText(ITextEditor editor, IDocument document, ITextSelection selection) throws BadLocationException {
	ITextSelection result = null;

	if (selection != null) {
		if (selection.getLength() == 0) {
			int line = document.getLineOfOffset(selection.getOffset());
			// get the proximate word
			try {
				ITextSelection tmp = new SexpForwardHandler().getTransSexp(document, selection.getOffset(), true);
				// make sure we're still on the same line
				if (tmp != null && line == document.getLineOfOffset(tmp.getOffset())) {
					selection = tmp;
				}
				// ignore 
			} catch (BadLocationException e) {}
		}
		if (selection != null && selection.getLength() > 0 && selection.getText() != null) {
			result = selection;
		}
	}
	return result;
}
 
Example 2
Source File: SearchExecuteMinibuffer.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Prime the minibuffer with the supplied text (which must be guaranteed to be present and selected in the buffer)
 *  
 * @param selection
 */
public void initMinibufferSelection(ITextSelection selection){
	if (selection != null && selection.getLength() > 0) {
		String text = selection.getText();
		saveState();
		try {
			// temporarily disable selection changed
			setSearching(true);				
			MarkUtils.setSelection(getEditor(),selection);
		} finally {
			setSearching(false);
		}
		initMinibuffer(text);
		checkCasePos(text);
		addToHistory();
		// force start (for history searches) to beginning of text rather than cursor
		setStartOffset(getTextWidget().getSelectionRange().x);
		setFound(true);
	}
}
 
Example 3
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
private IRegion getBlockComment(IDocument document, ITextSelection selection, CommentSupport commentSupport)
		throws BadLocationException {
	if (selection.getText() == null) {
		return null;
	}
	String text = document.get();
	String open = commentSupport.getBlockComment().getKey();
	String close = commentSupport.getBlockComment().getValue();
	int selectionStart = selection.getOffset();
	int selectionEnd = selectionStart + selection.getLength();
	int openOffset = TextUtils.startIndexOfOffsetTouchingString(text, selectionStart, open);
	if (openOffset == -1) {
		openOffset = text.lastIndexOf(open, selectionStart);
		if (openOffset == -1 || openOffset < document.getLineOffset(selection.getStartLine())) {
			return null;
		}
	}

	int closeOffset = TextUtils.startIndexOfOffsetTouchingString(text, selectionEnd, close);
	if (closeOffset == -1 || closeOffset < openOffset + open.length()) {
		closeOffset = text.indexOf(close, selectionEnd);
		IRegion endLineRegion = document.getLineInformation(document.getLineOfOffset(selectionEnd));
		if (openOffset == -1 || closeOffset < openOffset + open.length()
				|| closeOffset > endLineRegion.getOffset() + endLineRegion.getLength()) {
			return null;
		}
	}

	// Make sure there isn't a different block closer before the one we found
	int othercloseOffset = text.indexOf(close, openOffset + open.length());
	while (othercloseOffset != -1 && othercloseOffset < closeOffset) {
		int startOfLineOffset = document.getLineOffset(document.getLineOfOffset(othercloseOffset));
		if (commentSupport.getLineComment() != null && text.substring(startOfLineOffset, othercloseOffset)
				.indexOf(commentSupport.getLineComment()) != -1) {
			return null;
		}
		othercloseOffset = text.indexOf(close, othercloseOffset + close.length());
	}
	return new Region(openOffset, closeOffset - openOffset);
}
 
Example 4
Source File: JavaSearchPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SearchPatternData trySimpleTextSelection(ITextSelection selection) {
	String selectedText= selection.getText();
	if (selectedText != null && selectedText.length() > 0) {
		int i= 0;
		while (i < selectedText.length() && !IndentManipulation.isLineDelimiterChar(selectedText.charAt(i))) {
			i++;
		}
		if (i > 0) {
			return new SearchPatternData(TYPE, REFERENCES, 0, fIsCaseSensitive, selectedText.substring(0, i), null, JavaSearchScopeFactory.ALL);
		}
	}
	return null;
}
 
Example 5
Source File: ClipboardOperationAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isNonTrivialSelection(ITextSelection selection) {
	if (selection.getLength() < 30) {
		String text= selection.getText();
		if (text != null) {
			for (int i= 0; i < text.length(); i++) {
				if (!Character.isJavaIdentifierPart(text.charAt(i))) {
					return true;
				}
			}
		}
		return false;
	}
	return true;
}
 
Example 6
Source File: RegisterNumberHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.minibuffer.IMinibufferExecutable#executeResult(org.eclipse.ui.texteditor.ITextEditor, java.lang.Object)
 */
public boolean doExecuteResult(ITextEditor editor, Object minibufferResult) {
	
	if (minibufferResult != null && ((String)minibufferResult).length() > 0) {
		String key = (String)minibufferResult;
		int number = 0; 
		if (getCallCount() > 1) {
			number = getCallCount();
		} else {
			ITextSelection sel = getCurrentSelection(editor);
			// if some text is selected, use it
			if (sel.getLength() == 0) {
				// else get the next token in the buffer and try that
				sel = getNextSelection(getThisDocument(editor), sel);
			}
			String text = null;
			if (sel != null && (text = sel.getText()) != null && text.length() > 0) {
				try {
					number = Integer.parseInt(text);
					int offend = sel.getOffset()+sel.getLength();
					selectAndReveal(editor, offend, offend);
				} catch (NumberFormatException e) {
				}
			} 
		}
		TecoRegister.getInstance().put(key,number);				
		showResultMessage(editor, String.format(REGISTER_NUMBER, key,number), false);
	} else {
		showResultMessage(editor, NO_REGISTER, true);
	}
	return true;
}
 
Example 7
Source File: TransposeSexpHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
private int swapSexps(ITextEditor editor, IDocument document, Sexps sexps) throws BadLocationException {
	int result = NO_OFFSET;
	ITextSelection forward = sexps.getForward();
	ITextSelection backward = sexps.getBackward();
	if (forward != null && backward != null && !sexps.intersectP()) {
		result = forward.getOffset() + forward.getLength();
		String sexp1text = backward.getText();
		String sexp2text = forward.getText();
		// swap the text from bottom up
		updateText(document,forward, sexp1text);
		updateText(document,backward, sexp2text);
	}
	return result;
}
 
Example 8
Source File: PyGlobalsBrowserWorkbench.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(IAction action) {
    String text = null;
    if (this.selection instanceof ITextSelection) {
        ITextSelection textSelection = (ITextSelection) this.selection;
        text = textSelection.getText();

        if (text == null || text.length() == 0) {
            //No selection... let's see if we can get a word there... 
            //(note: not using getDocument because only 3.5 has it)
            Object document = Reflection.getAttrObj(textSelection, "fDocument");
            //returns null if we couldn't get it.
            if (document instanceof IDocument) { // document != null
                PySelection ps = new PySelection((IDocument) document,
                        new CoreTextSelection((IDocument) document, textSelection.getOffset(),
                                textSelection.getLength()));
                try {
                    text = ps.getCurrToken().o1;
                } catch (BadLocationException e) {
                    //ignore
                }
            }
        }
    }

    PyGlobalsBrowser.getFromWorkspace(text);
}
 
Example 9
Source File: TextViewerMoveLinesAction.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void runWithEvent(Event event) {
	ITextViewer viewer = getTextViewer();
	if (viewer == null)
		return;

	if (!canModifyViewer())
		return;

	// get involved objects

	IDocument document= viewer.getDocument();
	if (document == null)
		return;

	StyledText widget= viewer.getTextWidget();
	if (widget == null)
		return;

	// get selection
	ITextSelection sel= (ITextSelection) viewer.getSelectionProvider().getSelection();
	if (sel.isEmpty())
		return;

	ITextSelection skippedLine= getSkippedLine(document, sel);
	if (skippedLine == null)
		return;

	try {

		ITextSelection movingArea= getMovingSelection(document, sel, viewer);

		// if either the skipped line or the moving lines are outside the widget's
		// visible area, bail out
		if (!containedByVisibleRegion(movingArea, viewer) || !containedByVisibleRegion(skippedLine, viewer))
			return;

		// get the content to be moved around: the moving (selected) area and the skipped line
		String moving= movingArea.getText();
		String skipped= skippedLine.getText();
		if (moving == null || skipped == null || document.getLength() == 0)
			return;

		String delim;
		String insertion;
		int offset, deviation;
		if (fUpwards) {
			delim= document.getLineDelimiter(skippedLine.getEndLine());
			if (fCopy) {
				delim= TextUtilities.getDefaultLineDelimiter(document);
				insertion= moving + delim;
				offset= movingArea.getOffset();
				deviation= 0;
			} else {
				Assert.isNotNull(delim);
				insertion= moving + delim + skipped;
				offset= skippedLine.getOffset();
				deviation= -skippedLine.getLength() - delim.length();
			}
		} else {
			delim= document.getLineDelimiter(movingArea.getEndLine());
			if (fCopy) {
				if (delim == null) {
					delim= TextUtilities.getDefaultLineDelimiter(document);
					insertion= delim + moving;
				} else {
					insertion= moving + delim;
				}
				offset= skippedLine.getOffset();
				deviation= movingArea.getLength() + delim.length();
			} else {
				Assert.isNotNull(delim);
				insertion= skipped + delim + moving;
				offset= movingArea.getOffset();
				deviation= skipped.length() + delim.length();
			}
		}

		// modify the document
		beginCompoundEdit();
		if (fCopy) {
			document.replace(offset, 0, insertion);
		} else {
			document.replace(offset, insertion.length(), insertion);
		}

		// move the selection along
		int selOffset= movingArea.getOffset() + deviation;
		int selLength= movingArea.getLength() + (fAddDelimiter ? delim.length() : 0);
		if (! (viewer instanceof ITextViewerExtension5))
			selLength= Math.min(selLength, viewer.getVisibleRegion().getOffset() + viewer.getVisibleRegion().getLength() - selOffset);
		else {
			// TODO need to check what is necessary in the projection case
		}
		selectAndReveal(viewer, selOffset, selLength);
	} catch (BadLocationException x) {
		// won't happen without concurrent modification - bail out
		return;
	}
}
 
Example 10
Source File: ToggleCommentHandler.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private void getTypeContent(StringBuilder buf,
		ITextSelection iTextSelection, String type)
		throws BadLocationException {
	int offset = 0;
	if (iTextSelection.getOffset() == iDocument.getLength()) {
		offset = iDocument.getLength() - 1;
	} else {
		offset = iTextSelection.getOffset();
	}
	ITypedRegion typeRegion = iDocument.getPartition(offset);
	String text = iTextSelection.getText();
	ITypedRegion typeRegion_new = null;
	if (offset > 0) {
		typeRegion_new = iDocument.getPartition(offset - 1);
	}
	String TYPE_COMMENT = TYPE_HTML_COMMENT;
	String TYPE_COMMENT_BEGIN = TYPE_HTML_COMMENT_BEGIN;
	String TYPE_COMMENT_END = TYPE_HTML_COMMENT_END;
	if (TYPE_CSS.equals(type)) {
		TYPE_COMMENT = TYPE_CSS_M_COMMENT;
		TYPE_COMMENT_BEGIN = TYPE_CSS_M_COMMENT_BEGIN;
		TYPE_COMMENT_END = TYPE_CSS_M_COMMENT_END;
	}

	if (iTextSelection.getLength() == 0) {
		if (typeRegion != null && typeRegion.getType().equals(TYPE_COMMENT)) {
			setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
					TYPE_COMMENT_END);
			return;
		} else if (typeRegion_new != null
				&& typeRegion_new.getType().equals(TYPE_COMMENT)) {
			setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
					TYPE_COMMENT_END);
			return;
		}

		int lineNum = iTextSelection.getStartLine();
		IRegion lineInfo = iDocument.getLineInformation(lineNum);
		text = iDocument.get(lineInfo.getOffset(), lineInfo.getLength());
		String content = text.trim();
		if (content == null || content.length() == 0) {
			if (TYPE_HTML.equals(type)) {
				buf.append("<!---->");
			} else {
				buf.append("/**/");
			}

			subLength = 0;
			selecedRangeOffset = (iTextSelection.getOffset() + TYPE_COMMENT_BEGIN
					.length());
			return;
		}
		if (text != null && content.endsWith(TYPE_COMMENT_END)) {
			int index = text.indexOf(TYPE_COMMENT_END);
			typeRegion = iDocument.getPartition(iTextSelection.getOffset()
					- (text.length() - index));
			if ((typeRegion != null)
					&& (typeRegion.getType().equals(TYPE_COMMENT))) {

				setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
						TYPE_COMMENT_END);
				selecedRangeOffset = (lineInfo.getOffset()
						+ lineInfo.getLength() + buf.toString().length() - text
						.length());
				return;
			}
		}

		String replaceText = TYPE_COMMENT_BEGIN + content
				+ TYPE_COMMENT_END;
		text = text.replace(content, replaceText);
		buf.append(text);
		subLength = lineInfo.getLength();
		lineStartOffset = lineInfo.getOffset();
	} else {
		if ((typeRegion != null)
				&& (typeRegion.getType().equals(TYPE_COMMENT))) {
			setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
					TYPE_COMMENT_END);
		} else {
			buf.append(TYPE_COMMENT_BEGIN);
			buf.append(text);
			buf.append(TYPE_COMMENT_END);
			subLength = iTextSelection.getLength();
			lineStartOffset = iTextSelection.getOffset();
		}
	}
}
 
Example 11
Source File: SmartSemicolonAutoEditStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes the next insert position of the given character in the current line.
 *
 * @param document the document we are working on
 * @param line the line where the change is being made
 * @param offset the position of the caret in the line when <code>character</code> was typed
 * @param character the character to look for
 * @param partitioning the document partitioning
 * @return the position where <code>character</code> should be inserted / replaced
 */
protected static int computeCharacterPosition(IDocument document, ITextSelection line, int offset, char character, String partitioning) {
	String text= line.getText();
	if (text == null)
		return 0;

	int insertPos;
	if (character == BRACECHAR) {

		insertPos= computeArrayInitializationPos(document, line, offset, partitioning);

		if (insertPos == -1) {
			insertPos= computeAfterTryDoElse(document, line, offset);
		}

		if (insertPos == -1) {
			insertPos= computeAfterParenthesis(document, line, offset, partitioning);
		}

	} else if (character == SEMICHAR) {

		if (isForStatement(text, offset)) {
			insertPos= -1; // don't do anything in for statements, as semis are vital part of these
		} else {
			int nextPartitionPos= nextPartitionOrLineEnd(document, line, offset, partitioning);
			insertPos= startOfWhitespaceBeforeOffset(text, nextPartitionPos);
			// if there is a semi present, return its location as alreadyPresent() will take it out this way.
			if (insertPos > 0 && text.charAt(insertPos - 1) == character)
				insertPos= insertPos - 1;
			else if (insertPos > 0 && text.charAt(insertPos - 1) == '}') {
				int opening= scanBackward(document, insertPos - 1 + line.getOffset(), partitioning, -1, new char[] { '{' });
				if (opening > -1 && opening < offset + line.getOffset()) {
					if (computeArrayInitializationPos(document, line, opening - line.getOffset(), partitioning) == -1) {
						insertPos= offset;
					}
				}
			}
		}

	} else {
		Assert.isTrue(false);
		return -1;
	}

	return insertPos;
}