Java Code Examples for org.eclipse.jface.text.IDocument#getLineInformationOfOffset()

The following examples show how to use org.eclipse.jface.text.IDocument#getLineInformationOfOffset() . 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: ImpexInstructionContentAssistProcessor.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
public String getCurrentLine(IDocument document, int cursorPosition, boolean toCursor) {
	final String docContent = document.get();
	String line = "";
	IRegion currentRegion = null;
	int posOffset = cursorPosition;
	try {
		currentRegion = document.getLineInformationOfOffset(cursorPosition);
		if (toCursor == false) {
			posOffset = currentRegion.getOffset() + currentRegion.getLength();
		}
		line = docContent.substring(currentRegion.getOffset(), posOffset);
	}
	catch (BadLocationException ble) {
		LOG.log(Level.WARNING, "could not get current line", ble);
	}
	return line;
}
 
Example 2
Source File: PyAction.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the position of the last non whitespace char in the current line.
 * @param doc
 * @param cursorOffset
 * @return position of the last character of the line (returned as an absolute
 *            offset)
 * 
 * @throws BadLocationException
 */
protected int getLastCharPosition(IDocument doc, int cursorOffset) throws BadLocationException {
    IRegion region;
    region = doc.getLineInformationOfOffset(cursorOffset);
    int offset = region.getOffset();
    String src = doc.get(offset, region.getLength());

    int i = src.length();
    boolean breaked = false;
    while (i > 0) {
        i--;
        //we have to break if we find a character that is not a whitespace or a tab.
        if (Character.isWhitespace(src.charAt(i)) == false && src.charAt(i) != '\t') {
            breaked = true;
            break;
        }
    }
    if (!breaked) {
        i--;
    }
    return (offset + i);
}
 
Example 3
Source File: ColumnSupport.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Insert whitespace (tabs or spaces as appropriate) into document at off
 * When replacing, emacs clears the segment if the line length is less than the column
 * 
 * @param document
 * @param column 	the current column of offset
 * @param offset	the point to begin the insertion
 * @param colLen 	the length, in columns, of the insertion
 * @param replace 	replace if true, else add
 * 
 * @return the StringBuilder for length testing
 * 
 * @throws BadLocationException
 */
public String insertSpaces(IDocument document, int column, int offset, int colLen, boolean replace, boolean force) throws BadLocationException {

	String spaces;
	IRegion lineInfo = document.getLineInformationOfOffset(offset);
	// get the correct number of characters to traverse
	int seglen = lineInfo.getLength() - (offset - lineInfo.getOffset());
	// get the correct offset/column  
	IRegion colEnd = getColumn(document, offset, seglen, colLen);

	if (replace && colEnd.getLength() < colLen )  {
		if (colEnd.getOffset() != offset+seglen) {
			// line is long enough but spacing in line does not match with required column
			spaces = getSpaces(column, colEnd.getLength()).toString(); 
		} else {
			spaces = EMPTY_STR;
		}
	} else {
		spaces = getSpaces(column, colLen).toString();
	}
	// insert into document at offset
	document.replace(offset, (replace ? colEnd.getOffset() - offset : 0), spaces.toString());
	return spaces;
}
 
Example 4
Source File: AbstractWordAwareDoubleClickStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IRegion findWord(IDocument document, int offset) {
	try {
		IRegion line = document.getLineInformationOfOffset(offset);

		if (offset == line.getOffset() + line.getLength())
			return null;

		BreakIterator breakIter = createBreakIterator();
		CharacterIterator characterIterator = new DocumentCharacterIterator(document);
		breakIter.setText(characterIterator);
		int start = breakIter.preceding(offset);
		if (start == BreakIterator.DONE)
			start = line.getOffset();

		int end = breakIter.following(offset);
		if (end == BreakIterator.DONE)
			end = line.getOffset() + line.getLength();

		if (breakIter.isBoundary(offset)) {
			if (end - offset > offset - start)
				start = offset;
			else
				end = offset;
		}

		if (end == start)
			return null;
		return new Region(start, end - start);
	} catch (BadLocationException e) {
		return null;
	}
}
 
Example 5
Source File: JavaStringAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getLineIndentation(IDocument document, int offset) throws BadLocationException {

		// find start of line
		int adjustedOffset= (offset == document.getLength() ? offset  - 1 : offset);
		IRegion line= document.getLineInformationOfOffset(adjustedOffset);
		int start= line.getOffset();

		// find white spaces
		int end= findEndOfWhiteSpace(document, start, offset);

		return document.get(start, end - start);
	}
 
Example 6
Source File: WhitespaceCharacterPainter.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void paint(int reason)
{
	IDocument document = fTextViewer.getDocument();
	if (document == null)
	{
		deactivate(false);
		return;
	}
	if (!fIsActive)
	{
		fIsActive = true;
		fTextWidget.addPaintListener(this);
		redrawAll();
	}
	else if (reason == CONFIGURATION || reason == INTERNAL)
	{
		redrawAll();
	}
	else if (reason == TEXT_CHANGE)
	{
		// redraw current line only
		try
		{
			IRegion lineRegion = document
					.getLineInformationOfOffset(getDocumentOffset(fTextWidget.getCaretOffset()));
			int widgetOffset = getWidgetOffset(lineRegion.getOffset());
			int charCount = fTextWidget.getCharCount();
			int redrawLength = Math.min(lineRegion.getLength(), charCount - widgetOffset);
			if (widgetOffset >= 0 && redrawLength > 0)
			{
				fTextWidget.redrawRange(widgetOffset, redrawLength, true);
			}
		}
		catch (BadLocationException e)
		{
			// ignore
		}
	}
}
 
Example 7
Source File: JavaPairMatcher.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the angular bracket at <code>offset</code> is a type parameter opening bracket.
 * 
 * @param offset the offset of the opening bracket
 * @param document the document
 * @param scanner a java heuristic scanner on <code>document</code>
 * @return <code>true</code> if the bracket is part of a type parameter, <code>false</code>
 *         otherwise
 * @since 3.1
 */
private boolean isTypeParameterOpeningBracket(int offset, IDocument document, JavaHeuristicScanner scanner) {
	/*
	 * type parameter come after braces (closing or opening), semicolons, or after
	 * a Type name (heuristic: starts with capital character), or after a modifier
	 * keyword in a method declaration (visibility, static, synchronized, final)
	 */

	try {
		IRegion line= document.getLineInformationOfOffset(offset);

		int prevToken= scanner.previousToken(offset - 1, line.getOffset());
		int prevTokenOffset= scanner.getPosition() + 1;
		String previous= prevToken == Symbols.TokenEOF ? null : document.get(prevTokenOffset, offset - prevTokenOffset).trim();

		if (	   prevToken == Symbols.TokenLBRACE
				|| prevToken == Symbols.TokenRBRACE
				|| prevToken == Symbols.TokenSEMICOLON
				|| prevToken == Symbols.TokenSYNCHRONIZED
				|| prevToken == Symbols.TokenSTATIC
				|| (prevToken == Symbols.TokenIDENT && isTypeParameterIntroducer(previous))
				|| prevToken == Symbols.TokenEOF)
			return true;
	} catch (BadLocationException e) {
		return false;
	}

	return false;
}
 
Example 8
Source File: WhatCursorPosition.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusNoEditHandler#transform(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection, org.eclipse.core.commands.ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {
	
	String msg = null;
	
	int offset = getCursorOffset(editor,currentSelection);
	int docLen = document.getLength();
	IRegion line = document.getLineInformationOfOffset(offset); 

	if (offset >= docLen) {
		msg = String.format(EOB_POSITION, offset,docLen);
	} else {
		char curChar = document.getChar(offset);
		String sChar = "";	//$NON-NLS-1$
		int percent = new Float(((offset * 100) / docLen) + .5).intValue();

		if (offset == line.getOffset() + line.getLength()){
			String ld = document.getLineDelimiter(document.getLineOfOffset(offset));
			char[] points = ld.toCharArray();
			for (int i=0; i<points.length; i++) {
				sChar += normalizeChar(points[i]);
			}
			msg = String.format(EOL_POSITION, sChar,offset,docLen,percent);
		} else {

			int curCode = (int) curChar;
			sChar = (curChar <= ' ' ? normalizeChar(curChar) : String.valueOf(curChar));
			msg = String.format(CURSOR_POSITION, sChar, curCode, curCode, curCode, offset, docLen, percent);
		}
	}
	EmacsPlusUtils.showMessage(editor, msg, false);
	setCmdResult(new Integer(offset));
	return super.transform(editor, document, currentSelection, event);

}
 
Example 9
Source File: XtextEditor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected int getLineStartPosition(final IDocument document, final String line, final int length,
		final int offset) {

	String type = IDocument.DEFAULT_CONTENT_TYPE;
	try {
		type = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, offset, false);
	} catch (BadLocationException exception) {
		// Should not happen
	}

	int lineStartPosition = super.getLineStartPosition(document, line, length, offset);
	if (tokenTypeToPartitionTypeMapperExtension.isMultiLineComment(type)
			|| tokenTypeToPartitionTypeMapperExtension.isSingleLineComment(type)) {
		try {
			IRegion lineInformation = document.getLineInformationOfOffset(offset);
			int offsetInLine = offset - lineInformation.getOffset();
			return getCommentLineStartPosition(line, length, offsetInLine, lineStartPosition);
		} catch(BadLocationException e) {
			// Should not happen
		}
	} 
	if (type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
		if (isStartOfSingleLineComment(line, length, lineStartPosition) && !isStartOfMultiLineComment(line, length, lineStartPosition)) {
			return getTextStartPosition(line, length, lineStartPosition + 1);
		}
	}
	return lineStartPosition;
}
 
Example 10
Source File: DocumentUtils.java    From http4e with Apache License 2.0 5 votes vote down vote up
public static IRegion getDelimRegion( IDocument doc, int offset) throws BadLocationException{
   IRegion regLine = doc.getLineInformationOfOffset(offset);
   FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(doc);
   int lineOff = regLine.getOffset();
   IRegion regDelim = null;
   try {
      regDelim = finder.find(lineOff, AssistConstants.S_EQUAL, true, true, false, false);
  } catch (Exception ignore) {}

   return regDelim;
}
 
Example 11
Source File: ScopeAnalyzerVisitorWithoutImports.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Base constructor (after data from the PySelection is gotten)
 * @throws BadLocationException 
 */
protected ScopeAnalyzerVisitorWithoutImports(IPythonNature nature, String moduleName, IModule current,
        IDocument document, IProgressMonitor monitor, String pNameToFind, int absoluteCursorOffset,
        String[] tokenAndQual) throws BadLocationException {

    super(nature, moduleName, current, document, monitor);
    if (document != null) {
        IRegion region = document.getLineInformationOfOffset(absoluteCursorOffset);
        currLine = document.getLineOfOffset(absoluteCursorOffset);
        currCol = absoluteCursorOffset - region.getOffset();
    }

    nameToFind = pNameToFind;
    completeNameToFind = tokenAndQual[0] + tokenAndQual[1];
}
 
Example 12
Source File: IndentGuidesPainter.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public void paint(int reason) {
	IDocument document = fTextViewer.getDocument();
	if (document == null) {
		deactivate(false);
		return;
	}
	if (!fIsActive) {
		fIsActive = true;
		fTextWidget.addPaintListener(this);
		indentsModel.applyToDocument(document, this, fTextWidget);
	} else if (reason == CONFIGURATION || reason == INTERNAL) {
		redrawAll();
	} else if (reason == TEXT_CHANGE) {
		// redraw current line only
		try {
			IRegion lineRegion = document
					.getLineInformationOfOffset(getDocumentOffset(fTextWidget
							.getCaretOffset()));
			int widgetOffset = getWidgetOffset(lineRegion.getOffset());
			int charCount = fTextWidget.getCharCount();
			int redrawLength = Math.min(lineRegion.getLength(), charCount - widgetOffset);
			if (widgetOffset >= 0 && redrawLength > 0) {
				fTextWidget.redrawRange(widgetOffset, redrawLength, true);
			}
		} catch (BadLocationException e) {
			// ignore
		}
	}
}
 
Example 13
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the indentation level at the position of code completion.
 *
 * @return the indentation level at the position of the code completion
 */
private int getIndentation() {
	int start= getStart();
	IDocument document= getDocument();
	try {
		IRegion region= document.getLineInformationOfOffset(start);
		String lineContent= document.get(region.getOffset(), region.getLength());
		IJavaProject project= getJavaProject();
		return Strings.computeIndentUnits(lineContent, project);
	} catch (BadLocationException e) {
		return 0;
	}
}
 
Example 14
Source File: SexpBaseBackwardHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * When moving backward, and we're consuming _'s, see if we're currently positioned by an _
 * 
 * @param doc
 * @param iter
 * @param pos current word position
 * @return new offset if word moves past any _'s, else pos   
 */
int checkUnder(IDocument doc, BreakIterator iter, int pos) {
	int result = pos;
	try {
		if (!isUnder()) {
			char c = doc.getChar(result);
			IRegion lineInfo = doc.getLineInformationOfOffset(pos);
			if (c == '_') {
				// we've backed over an _
				Matcher matcher = getUnderMatcher();
				// get text including the trailing _
				matcher.reset(doc.get(lineInfo.getOffset(), pos+1 - lineInfo.getOffset()));
				if (matcher.find()) {
					result = lineInfo.getOffset() + matcher.start(1);
				}
			} else if (result > lineInfo.getOffset()){
				// check preceding character
				c = doc.getChar(result-1);
				if (c == '_' || (!isDot() && c == '.')) {
					// we've been stopped by a preceding _ or . 
					result = checkUnder(doc,iter,iter.previous());
				}
			}
		}
	} catch (BadLocationException e) {
	}
	return result;
}
 
Example 15
Source File: LanguageConfigurationRegistryManager.java    From tm4e with Eclipse Public License 1.0 4 votes vote down vote up
public EnterActionAndIndent getEnterAction(IDocument document, int offset, IContentType contentType) {
	String indentation = TextUtils.getLinePrefixingWhitespaceAtPosition(document, offset);
	// let scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber,
	// range.startColumn);
	OnEnterSupport onEnterSupport = this._getOnEnterSupport(contentType /* scopedLineTokens.languageId */);
	if (onEnterSupport == null) {
		return null;
	}

	try {
		IRegion lineInfo = document.getLineInformationOfOffset(offset);

		// String scopeLineText = DocumentHelper.getLineTextOfOffset(document, offset,
		// false);
		String beforeEnterText = document.get(lineInfo.getOffset(), offset - lineInfo.getOffset());
		String afterEnterText = null;

		// selection support
		// if (range.isEmpty()) {
		afterEnterText = document.get(offset, lineInfo.getLength() - (offset - lineInfo.getOffset())); // scopedLineText.substr(range.startColumn
																										// - 1 -
																										// scopedLineTokens.firstCharOffset);
		// } else {
		// const endScopedLineTokens = this.getScopedLineTokens(model,
		// range.endLineNumber, range.endColumn);
		// afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn
		// - 1 - scopedLineTokens.firstCharOffset);
		// }

		String oneLineAboveText = ""; //$NON-NLS-1$
		/*
		 * let lineNumber = range.startLineNumber; let oneLineAboveText = '';
		 *
		 * if (lineNumber > 1 && scopedLineTokens.firstCharOffset === 0) { // This is
		 * not the first line and the entire line belongs to this mode let
		 * oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, lineNumber -
		 * 1); if (oneLineAboveScopedLineTokens.languageId ===
		 * scopedLineTokens.languageId) { // The line above ends with text belonging to
		 * the same mode oneLineAboveText =
		 * oneLineAboveScopedLineTokens.getLineContent(); } }
		 */

		EnterAction enterResult = null;
		try {
			enterResult = onEnterSupport.onEnter(oneLineAboveText, beforeEnterText, afterEnterText);
		} catch (Exception e) {
			// onUnexpectedError(e);
		}

		if (enterResult == null) {
			return null;
		} else {
			// Here we add `\t` to appendText first because enterAction is leveraging
			// appendText and removeText to change indentation.
			if (enterResult.getAppendText() == null) {
				if ((enterResult.getIndentAction() == IndentAction.Indent)
						|| (enterResult.getIndentAction() == IndentAction.IndentOutdent)) {
					enterResult.setAppendText("\t"); //$NON-NLS-1$
				} else {
					enterResult.setAppendText(""); //$NON-NLS-1$
				}
			}
		}

		if (enterResult.getRemoveText() != null) {
			indentation = indentation.substring(0, indentation.length() - enterResult.getRemoveText());
		}

		return new EnterActionAndIndent(enterResult, indentation);

	} catch (BadLocationException e1) {
	}
	return null;
}
 
Example 16
Source File: IndentAction.java    From typescript.java with MIT License 4 votes vote down vote up
/**
 * Computes and returns the indentation for a javadoc line. The line must be
 * inside a javadoc comment.
 * 
 * @param document
 *            the document
 * @param line
 *            the line in document
 * @param scanner
 *            the scanner
 * @param partition
 *            the javadoc partition
 * @return the indent, or <code>null</code> if not computable
 * @throws BadLocationException
 * 
 */
private String computeJavadocIndent(IDocument document, int line, JavaHeuristicScanner scanner,
		ITypedRegion partition) throws BadLocationException {
	if (line == 0) // impossible - the first line is never inside a javadoc
					// comment
		return null;

	// don't make any assumptions if the line does not start with \s*\* - it
	// might be
	// commented out code, for which we don't want to change the indent
	final IRegion lineInfo = document.getLineInformation(line);
	final int lineStart = lineInfo.getOffset();
	final int lineLength = lineInfo.getLength();
	final int lineEnd = lineStart + lineLength;
	int nonWS = scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
	if (nonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
		if (nonWS == JavaHeuristicScanner.NOT_FOUND)
			return document.get(lineStart, lineLength);
		return document.get(lineStart, nonWS - lineStart);
	}

	// take the indent from the previous line and reuse
	IRegion previousLine = document.getLineInformation(line - 1);
	int previousLineStart = previousLine.getOffset();
	int previousLineLength = previousLine.getLength();
	int previousLineEnd = previousLineStart + previousLineLength;

	StringBuffer buf = new StringBuffer();
	int previousLineNonWS = scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
	if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
		// align with the comment start if the previous line is not an
		// asterisked line
		previousLine = document.getLineInformationOfOffset(partition.getOffset());
		previousLineStart = previousLine.getOffset();
		previousLineLength = previousLine.getLength();
		previousLineEnd = previousLineStart + previousLineLength;
		previousLineNonWS = scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
		if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND)
			previousLineNonWS = previousLineEnd;

		// add the initial space
		// TODO this may be controlled by a formatter preference in the
		// future
		buf.append(' ');
	}

	String indentation = document.get(previousLineStart, previousLineNonWS - previousLineStart);
	buf.insert(0, indentation);
	return buf.toString();
}
 
Example 17
Source File: DeleteWhitespaceHandler.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Determine the correct set of lines and delete the whitespace at the end of each of them.
 * 
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {
	int result = NO_OFFSET;
	int lastLine = 0;
	int firstLine = 0;
	int maxOffset = Integer.MAX_VALUE;		
	if (editor.showsHighlightRangeOnly()) {
		// if the buffer is narrowed, then operate on precise region
		IRegion narrow = editor.getHighlightRange();
		int lastOffset = narrow.getOffset() + narrow.getLength();
		firstLine = document.getLineOfOffset(narrow.getOffset()); 
		lastLine = document.getLineOfOffset(lastOffset);
		IRegion endInfo = document.getLineInformationOfOffset(lastOffset);
		if (endInfo.getOffset() != lastOffset) {
			// point maxOffset at the last character in the narrowed region
			maxOffset = lastOffset -1;
		} else {
			// back up if we're at the first offset of the last line
			lastLine--;
		}
	} else {
		lastLine = document.getNumberOfLines() -1;
	}
	if (firstLine <= lastLine) {
		Position coff = new Position(getCursorOffset(editor,currentSelection),0);
		try {
			// record the position so we can restore it after any whitespace deletions
			document.addPosition(coff);
			deleteWhitepace(lastLine,firstLine,maxOffset,document);
		} catch (BadLocationException e) {
			// shouldn't happen, but alert user if it does
			asyncShowMessage(editor,BAD_LOCATION_ERROR,true);
		} finally {
			result = coff.getOffset();
			document.removePosition(coff);
		}
	}
	return result;
}
 
Example 18
Source File: RectangleSupport.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Convert the selection information to a RectangleInfo object with information about the 
 * offsets, lengths and columns involved
 * 
 * @param editor
 * @param document
 * @param selection
 * @return the RectangleInfo object
 */
public RectangleInfo getRectangleInfo(ITextEditor editor, IDocument document,ITextSelection selection) {
	RectangleInfo result = null;
	try {
		if (selection != null) {
			result = new RectangleInfo(); 
			// get begin and end offsets
			int beginOff = selection.getOffset();
			int endOff = beginOff + selection.getLength();
			// get begin and end line information
			IRegion bl = document.getLineInformationOfOffset(beginOff);
			IRegion el = document.getLineInformationOfOffset(endOff);
			int blOff = bl.getOffset();
			int elOff = el.getOffset();
			// determine the start and end columns
			int startCol = getColumn(document, blOff, beginOff - blOff,Integer.MAX_VALUE).getLength();
			int endCol = getColumn(document, elOff, endOff - elOff,Integer.MAX_VALUE).getLength();
			if (endCol < startCol) {
				int tmp = endCol;
				endCol = startCol;
				startCol = tmp;
			}
			result.setStartColumn(startCol);
			result.setEndColumn(endCol);
			// for each line in the rectangle, determine the offset and length
			int bline = document.getLineOfOffset(blOff);
			int eline = document.getLineOfOffset(elOff);
			LineInfo[] lines = new LineInfo[eline+1-bline];
			for (int i = 0; i < lines.length; i ++) {
				IRegion line = document.getLineInformation(bline + i);
				IRegion start = getColumn(document,line.getOffset(),line.getLength(),startCol);
				IRegion end = getColumn(document,line.getOffset(),line.getLength(),endCol);
				lines[i] = new LineInfo(start.getOffset(),(end.getOffset()-start.getOffset()),end.getLength());
			}
			result.setLines(lines);
		}
	} catch (BadLocationException e) {
		result = null;
	}
	return result;
}
 
Example 19
Source File: SelectAllOccurrencesHandler.java    From eclipse-multicursor with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Mostly based on code from {@link org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal}
 */
private void startEditing(ISourceViewer viewer) throws ExecutionException {
	Point selOffsetAndLen = viewer.getSelectedRange();
	int selStart = CoordinatesUtil.fromOffsetAndLengthToStartAndEnd(selOffsetAndLen).x;

	IDocument document = viewer.getDocument();
	try {
		String selectedText;
		if (selOffsetAndLen.y == 0) { // no characters selected
			String documentText = document.get();
			Point wordOffsetAndLen = TextUtil.findWordSurrounding(documentText, selStart);
			if (wordOffsetAndLen != null) {
				selectedText = document.get(wordOffsetAndLen.x, wordOffsetAndLen.y);
			} else {
				IRegion selectedLine = document.getLineInformationOfOffset(selStart);
				selectedText = document.get(selectedLine.getOffset(), selectedLine.getLength());
			}
		} else {
			selectedText = document.get(selOffsetAndLen.x, selOffsetAndLen.y);
		}

		LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup();

		FindReplaceDocumentAdapter findReplaceAdaptor = new FindReplaceDocumentAdapter(document);
		IRegion matchingRegion = findReplaceAdaptor.find(0, selectedText, true, true, false, false);
		while (matchingRegion != null) {
			linkedPositionGroup.addPosition(new LinkedPosition(document, matchingRegion.getOffset(), matchingRegion
					.getLength()));

			matchingRegion = findReplaceAdaptor.find(matchingRegion.getOffset() + matchingRegion.getLength(),
					selectedText, true, true, false, false);
		}

		LinkedModeModel model = new LinkedModeModel();
		model.addGroup(linkedPositionGroup);
		model.forceInstall();

		LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
		ui.setExitPolicy(new DeleteBlockingExitPolicy(document));
		ui.enter();

		// by default the text being edited is selected so restore original selection
		viewer.setSelectedRange(selOffsetAndLen.x, selOffsetAndLen.y);
	} catch (BadLocationException e) {
		throw new ExecutionException("Editing failed", e);
	}
}
 
Example 20
Source File: PythonSourceViewer.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a segmentation of the line of the given document appropriate for bidi rendering. The default implementation returns only the string literals of a Java code line as segments.
 *
 * @param document the document
 * @param lineOffset the offset of the line
 * @return the line's bidi segmentation
 * @throws BadLocationException in case lineOffset is not valid in document
 */
protected int[] getBidiLineSegments(int lineOffset) throws BadLocationException {
    IDocument document = getDocument();
    if (document == null) {
        return null;
    }
    IRegion line = document.getLineInformationOfOffset(lineOffset);
    ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength());

    /*
     * List segmentation= new ArrayList(); for (int i= 0; i < linePartitioning.length; i++) { // if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType())) //
     * segmentation.add(linePartitioning[i]); }
     *
     *
     * if (segmentation.size() == 0) return null;
     */
    int size = linePartitioning.length;
    int[] segments = new int[size * 2 + 1];

    int j = 0;
    for (int i = 0; i < size; i++) {
        // ITypedRegion segment= (ITypedRegion) segmentation.get(i);
        ITypedRegion segment = linePartitioning[i];

        if (i == 0) {
            segments[j++] = 0;
        }

        int offset = segment.getOffset() - lineOffset;
        if (offset > segments[j - 1]) {
            segments[j++] = offset;
        }

        if (offset + segment.getLength() >= line.getLength()) {
            break;
        }

        segments[j++] = offset + segment.getLength();
    }

    if (j < segments.length) {
        int[] result = new int[j];
        System.arraycopy(segments, 0, result, 0, j);
        segments = result;
    }

    return segments;
}