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

The following examples show how to use org.eclipse.jface.text.IDocument#getLineInformation() . 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: ReverseRegionHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @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 {
   	ITextSelection selection = getLineSelection(editor,document,currentSelection);
   	if (selection != null) {
   		int offset = selection.getOffset();
   		int endOffset = offset+selection.getLength(); 
   		int begin = document.getLineOfOffset(offset);
   		int end = document.getLineOfOffset(endOffset);
		if (begin != end && begin < end) {
			// grab the lines
			int len = end-begin+1; 
			String[] array = new String[len];
			for (int i = 0; i < len; i++) {
				IRegion region = document.getLineInformation(begin+i);
				array[i] = document.get(region.getOffset(),region.getLength());
			}
			// and reverse them
			updateLines(document,new TextSelection(document,offset,endOffset-offset),reverse(array));
		}
	} else {
		EmacsPlusUtils.showMessage(editor, NO_REGION, true);
	}
	return NO_OFFSET;
}
 
Example 2
Source File: ToggleCommentHandler.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
protected boolean isSelectionCommented(IDocument document, ITextSelection selection, String commentPrefix) 
{
    try {
        for (int lineNum = selection.getStartLine(); lineNum <= selection.getEndLine(); ++lineNum) {
            IRegion r  = document.getLineInformation(lineNum);
            String str = document.get(r.getOffset(), r.getLength()).trim();
            if (!str.startsWith(commentPrefix)) {
                return false;
            }
        }
        return true;
    } catch (Exception x) {
    }

    return false;
}
 
Example 3
Source File: JavaMoveLinesAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IRegion getRegion(IDocument document, ILineRange lineRange) throws BadLocationException {
	final int startLine= lineRange.getStartLine();
	int offset= document.getLineOffset(startLine);
	final int numberOfLines= lineRange.getNumberOfLines();
	if (numberOfLines < 1)
		return new Region(offset, 0);
	int endLine= startLine + numberOfLines - 1;
	int endOffset;
	if (fSharedState.fEditor.isBlockSelectionModeEnabled()) {
		// in block selection mode, don't select the last delimiter as we count an empty selected line
		IRegion endLineInfo= document.getLineInformation(endLine);
		endOffset= endLineInfo.getOffset() + endLineInfo.getLength();
	} else {
		endOffset= document.getLineOffset(endLine) + document.getLineLength(endLine);
	}
	return new Region(offset, endOffset - offset);
}
 
Example 4
Source File: RubyRegexpAutoIndentStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method attempts to determine tab width in the file as it already exists. It checks for two indents of
 * different sizes and returns their GCD if it's not 1. If we can't get two lines of different lenths, or their GCD
 * is 1 then we'll fall back to using the editor's expressed tab width via the preferences.
 * 
 * @param d
 * @param startLine
 * @return
 */
private int guessTabWidth(IDocument d, int startLine)
{
	try
	{
		List<Integer> lengths = new ArrayList<Integer>(3);
		for (int i = startLine; i >= 0; i--)
		{
			IRegion line = d.getLineInformation(i);
			int endofWhitespace = findEndOfWhiteSpace(d, line.getOffset(), line.getOffset() + line.getLength());
			int length = endofWhitespace - line.getOffset();
			if (length == 0)
				continue;
			// We need two different lengths to guess at tab width
			if (lengths.size() < 2 && !lengths.contains(length))
				lengths.add(length);
			if (lengths.size() >= 2)
				break;
		}
		// now we need to do a GCD of the lengths
		int tabWidth = gcd(lengths.get(0), lengths.get(1));
		if (tabWidth != 1)
			return tabWidth;
	}
	catch (BadLocationException e)
	{
		IdeLog.logError(CommonEditorPlugin.getDefault(), e);
	}

	return getTabWidth();
}
 
Example 5
Source File: CountLinesRegion.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusNoEditHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
throws BadLocationException {
	String msg = NO_COUNT_REGION;
	int lineTotal = 0;		
	int mark = getMark(editor);
	if (mark != -1) {
		int offset = getCursorOffset(editor,currentSelection);
		if (offset > mark) {
			int tmp = mark;
			mark = offset;
			offset = tmp;
		}
		int oline= document.getLineOfOffset(offset);
		int mline= document.getLineOfOffset(mark);
		IRegion mReg = document.getLineInformation(mline);
		lineTotal = Math.abs(mline - oline);
		// if not at beginning of line, then increment count to include current line
		if (mReg.getOffset() != mark) {
			++lineTotal;
		} else if (document.getLength() == mark) {
			// only if at eof and preceding didn't fire (so only eol at eof)
			++lineTotal;
		}
		int charTotal = document.get(offset, mark-offset).length();
		msg = String.format(COUNT_REGION, lineTotal, charTotal);
	}
	setCmdResult(new Integer(lineTotal));		
	EmacsPlusUtils.showMessage(editor, msg, false);
	return super.transform(editor, document, currentSelection, event);
}
 
Example 6
Source File: TextSelectionUtils.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets line from document.
 *
 * @param i Line number
 * @return String line in String form
 */
public static String getLine(IDocument doc, int i) {
    try {
        IRegion lineInformation = doc.getLineInformation(i);
        return doc.get(lineInformation.getOffset(), lineInformation.getLength());
    } catch (Exception e) {
        return "";
    }
}
 
Example 7
Source File: LineBackgroundPainter.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calculates the common scope between the end of one line and the beginning of the next.
 * 
 * @param document
 * @param line
 * @param endOfLineScope
 * @return
 * @throws BadLocationException
 */
private String getScope(IDocument document, int line, String endOfLineScope) throws BadLocationException
{
	// if this is the last line, just use the scope at the end of it.
	int lines = document.getNumberOfLines();
	if (line + 1 >= lines)
	{
		return endOfLineScope;
	}

	// now grab the scope at the beginning of the next line...
	IRegion nextLine = document.getLineInformation(line + 1);
	// If the next line is empty, take our end of line scope
	if (nextLine.getLength() == 0)
	{
		return endOfLineScope;
	}
	String startOfNextLineScope = getScopeManager().getScopeAtOffset(document, nextLine.getOffset());

	// Calculate the common prefix between the two!
	StringBuilder builder = new StringBuilder();
	int length = Math.min(endOfLineScope.length(), startOfNextLineScope.length());
	for (int i = 0; i < length; i++)
	{
		char c = endOfLineScope.charAt(i);
		char o = startOfNextLineScope.charAt(i);
		if (c == o)
		{
			builder.append(c);
		}
	}
	return builder.toString();
}
 
Example 8
Source File: IndentUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
 * Leaves leading comment signs alone.
 *
 * @param document the document
 * @param line the line
 * @param indent the indentation to insert
 * @param commentlines
 * @throws BadLocationException on concurrent document modification
 */
private static void addIndent(IDocument document, int line, CharSequence indent, boolean[] commentlines, int relative) throws BadLocationException {
	IRegion region= document.getLineInformation(line);
	int insert= region.getOffset();
	int endOffset= region.getOffset() + region.getLength();

	// go behind line comments
	if (!commentlines[relative]) {
		while (insert < endOffset - 2 && document.get(insert, 2).equals(SLASHES))
			insert += 2;
	}

	// insert indent
	document.replace(insert, 0, indent.toString());
}
 
Example 9
Source File: WhitespaceHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected String calculateLeadingWhitespace(IDocument document) {
	try {
		IRegion line = document.getLineInformationOfOffset(offset);
		if (line != null) {
			String linePrefix = document.get(line.getOffset(), offset - line.getOffset());
			if (isEmpty(linePrefix.trim())) {
				int lineNr = document.getLineOfOffset(offset);
				if (lineNr > 0) {
					IRegion lineInformation = document.getLineInformation(lineNr - 1);
					if (isEmpty(document.get(lineInformation.getOffset(), lineInformation.getLength()).trim())) {
						int lineDelimiterLength = document.getLineDelimiter(lineNr - 1).length();
						int skipLeadingWhitespace = linePrefix.length() + lineDelimiterLength;
						offset -= skipLeadingWhitespace;
						length += skipLeadingWhitespace;
						return lineSeparator;
					} else {
						return lineSeparator;
					}
				}
			} else {
				return lineSeparator + lineSeparator;
			}
		}
	} catch (BadLocationException e) {
		LOG.error("Error calculating leading whitespace", e);
	}
	return null;
}
 
Example 10
Source File: RubyRegexpAutoIndentStrategy.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A less intelligent way of determining new indent on dedent trigger. We look at previous line and if our indent is
 * of same length or greater, we just assume we need to dedent from that previous line.
 * 
 * @param d
 * @param lineNumber
 * @param currentLineIndent
 * @return
 * @throws BadLocationException
 */
protected String dedentBasedOnPreviousLine(IDocument d, int lineNumber, String currentLineIndent)
		throws BadLocationException
{
	int endIndex;
	// Grab previous line's indent level
	IRegion previousLine = d.getLineInformation(lineNumber - 1);
	endIndex = findEndOfWhiteSpace(d, previousLine.getOffset(), previousLine.getOffset() + previousLine.getLength());
	String previousLineIndent = d.get(previousLine.getOffset(), endIndex - previousLine.getOffset());

	// Try to generate a string for a decreased indent level... First, just set to previous line's indent.
	String decreasedIndent = previousLineIndent;
	if (previousLineIndent.length() >= currentLineIndent.length())
	{
		// previous indent level is same or greater than current line's, we should shift current back one
		// level
		if (previousLineIndent.endsWith(TAB_CHAR))
		{
			// Just remove the tab at end
			decreasedIndent = decreasedIndent.substring(0, decreasedIndent.length() - 1);
		}
		else
		{
			// We need to try and remove upto tab-width spaces from end, stop if we hit a tab first
			int tabWidth = guessTabWidth(d, lineNumber);
			String toRemove = decreasedIndent.substring(decreasedIndent.length() - tabWidth);
			int lastTabIndex = toRemove.lastIndexOf(TAB_CHAR);
			if (lastTabIndex != -1)
			{
				// compare last tab index to number of spaces we want to remove.
				tabWidth -= lastTabIndex + 1;
			}
			decreasedIndent = decreasedIndent.substring(0, decreasedIndent.length() - tabWidth);
		}
	}
	return decreasedIndent;
}
 
Example 11
Source File: FixCompletionProposal.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void apply(IDocument document) {
    try {
        document.replace(fReplacementOffset, fReplacementLength, fReplacementString);
        if (lineToRemove >= 0 && lineToRemove <= document.getNumberOfLines()) {
            IRegion lineInformation = document.getLineInformation(lineToRemove);
            document.replace(lineInformation.getOffset(), lineInformation.getLength(), "");
        }
    } catch (BadLocationException x) {
        // ignore
    }
}
 
Example 12
Source File: ParagraphTransposeHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
private int swapParagraphs(IDocument document, Paragraph para1, Paragraph para2) throws BadLocationException {
	int result = -1;
	if (para1.isOk() && para2.isOk()) {
		// we're cool, so swap
		// check that we're not at a non-blank line (top) before adjusting line 
		int bline = document.getLineOfOffset(para1.getBegin());
		if (isBlank(document,bline)) {
			++bline;
		}
		// check that we're not at a non-blank line (bottom) before adjusting line 
		int eline = document.getLineOfOffset(para2.getEnd());
		if (isBlank(document,eline)) {
			--eline;
		}
		// get the text for paragraph 1
		IRegion line1Begin = document.getLineInformation(bline); 
		IRegion lineEnd = document.getLineInformation(document.getLineOfOffset(para1.getEnd()) -1);
		int para1len = lineEnd.getOffset() + lineEnd.getLength() - line1Begin.getOffset(); 
		String para1text = document.get(line1Begin.getOffset(), para1len);
		// get the text for paragraph 2
		IRegion line2Begin = document.getLineInformation(document.getLineOfOffset(para2.getBegin()) + 1); 
		lineEnd = document.getLineInformation(eline);
		int para2len = lineEnd.getOffset() + lineEnd.getLength() - line2Begin.getOffset(); 
		String para2text = document.get(line2Begin.getOffset(), para2len);
		// swap the text from bottom up
		updateText(document,line2Begin.getOffset(), para2len, para1text);
		updateText(document,line1Begin.getOffset(), para1len, para2text);
		// cursor goes below swapped paragraphs
		result = para2.getEnd();
	}		
	return result;
}
 
Example 13
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Guesses if the command operates within a newly created javadoc comment or
 * not. If in doubt, it will assume that the javadoc is new.
 *
 * @param document
 *            the document
 * @param commandOffset
 *            the command offset
 * @return <code>true</code> if the comment should be closed,
 *         <code>false</code> if not
 */
private boolean isNewComment(IDocument document, int commandOffset) {

	try {
		int lineIndex = document.getLineOfOffset(commandOffset) + 1;
		if (lineIndex >= document.getNumberOfLines())
			return true;

		IRegion line = document.getLineInformation(lineIndex);
		ITypedRegion partition = TextUtilities.getPartition(document, fPartitioning, commandOffset, false);
		int partitionEnd = partition.getOffset() + partition.getLength();
		if (line.getOffset() >= partitionEnd)
			return false;

		if (document.getLength() == partitionEnd)
			return true; // partition goes to end of document - probably a
							// new comment

		String comment = document.get(partition.getOffset(), partition.getLength());
		if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$
			return true; // enclosed another comment -> probably a new
							// comment

		return false;

	} catch (BadLocationException e) {
		return false;
	}
}
 
Example 14
Source File: ToggleCommentAction.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Determines whether each line is prefixed by one of the prefixes.
 *
 * @param startLine Start line in document
 * @param endLine End line in document
 * @param prefixes Possible comment prefixes
 * @param document The document
 * @return <code>true</code> iff each line from <code>startLine</code>
 *             to and including <code>endLine</code> is prepended by one
 *             of the <code>prefixes</code>, ignoring whitespace at the
 *             begin of line
 */
protected boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) {

	try {

		// check for occurrences of prefixes in the given lines
		for (int i= startLine; i <= endLine; i++) {

			IRegion line= document.getLineInformation(i);
			String text= document.get(line.getOffset(), line.getLength());

			int[] found= TextUtilities.indexOf(prefixes, text, 0);

			if (found[0] == -1)
				// found a line which is not commented
				return false;

			String s= document.get(line.getOffset(), found[0]);
			s= s.trim();
			if (s.length() != 0)
				// found a line which is not commented
				return false;

		}

		return true;

	} catch (BadLocationException x) {
		// should not happen
		LangCore.logError("Unexpected error.", x);
	}

	return false;
}
 
Example 15
Source File: LangAutoEditStrategy.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
protected String calculateDeletableIndent(IDocument doc, int indentedLine, int indentEnd)
		throws BadLocationException {
	IRegion indentedLineRegion = doc.getLineInformation(indentedLine);

	String expectedIndentStr = determineExpectedIndent(doc, indentedLine-1);
	int indentLength = indentEnd - indentedLineRegion.getOffset(); 
	if(indentLength < expectedIndentStr.length()) {
		// cap expected length
		expectedIndentStr = expectedIndentStr.substring(0, indentLength);
	}
	return expectedIndentStr;
}
 
Example 16
Source File: MultiLineTerminalsEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * determines whether the given offset is at the beginning of the input in the line. leading whitespace is disregarded.
 */
private boolean atBeginningOfLineInput(IDocument document, int offset) throws BadLocationException {
	IRegion line = document.getLineInformation(document.getLineOfOffset(offset));
	return document.get(line.getOffset(), offset - line.getOffset()).trim().length() == 0;
}
 
Example 17
Source File: ToggleBreakpointAdapter.java    From typescript.java with MIT License 4 votes vote down vote up
void toggleLineBreakpoint(final IWorkbenchPart part, final ITextSelection selection, final int linenumber) {
	Job job = new Job("Toggle Line Breakpoints") {
           protected IStatus run(IProgressMonitor monitor) {
           	try {
           		ITextEditor editor = getTextEditor(part);
				if(editor != null && part instanceof IEditorPart) {
					IResource resource = getResource((IEditorPart)part);
					if(resource == null) {
						resource = getResource((IEditorPart)part);
						reportToStatusLine(part, "Failed to create Javascript line breakpoint - the resource could no be computed");
						return Status.CANCEL_STATUS;
					}
					IBreakpoint bp = lineBreakpointExists(resource, linenumber);
					if(bp != null) {
						DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(bp, true);
						return Status.OK_STATUS;
					}
					IDocumentProvider documentProvider = editor.getDocumentProvider();
					IDocument document = documentProvider.getDocument(editor.getEditorInput());
					int charstart = -1, charend = -1;
					try {
						IRegion line = document.getLineInformation(linenumber - 1);
						charstart = line.getOffset();
						charend = charstart + line.getLength();
					}
					catch (BadLocationException ble) {}
					HashMap<String, String> attributes = new HashMap<String, String>();
					attributes.put(IJavaScriptBreakpoint.TYPE_NAME, null);
					attributes.put(IJavaScriptBreakpoint.SCRIPT_PATH, resource.getFullPath().makeAbsolute().toString());
					attributes.put(IJavaScriptBreakpoint.ELEMENT_HANDLE, null);
					JavaScriptDebugModel.createLineBreakpoint(resource, linenumber, charstart, charend, attributes, true);
					return Status.OK_STATUS;
				}
				reportToStatusLine(part, "Failed to create Javascript line breakpoint");
				return Status.CANCEL_STATUS;
            }
        	catch(CoreException ce) {
        		return ce.getStatus();
       		}
       	}
	};
	job.setPriority(Job.INTERACTIVE);
       job.setSystem(true);
       job.schedule();
}
 
Example 18
Source File: TextSelectionUtils.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public static String getLineContentsToCursor(IDocument doc, int offset) throws BadLocationException {
    int lineOfOffset = doc.getLineOfOffset(offset);
    IRegion lineInformation = doc.getLineInformation(lineOfOffset);
    String lineToCursor = doc.get(lineInformation.getOffset(), offset - lineInformation.getOffset());
    return lineToCursor;
}
 
Example 19
Source File: JavadocConsoleLineTracker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void revealLine(ITextEditor editor, int lineNumber) throws BadLocationException {
	IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
	IRegion region= document.getLineInformation(lineNumber - 1);
	editor.selectAndReveal(region.getOffset(), 0);
}
 
Example 20
Source File: AbapGitStagingView.java    From ADT_Frontend with MIT License 4 votes vote down vote up
/**
 * Validates the UI inputs
 */
protected int validateInputs() {
	int errorCode = 0;
	boolean valid = true;

	//check commit message
	String commitMessage = this.commitMessageTextViewer.getTextWidget().getText();
	IDocument commitMessageDocument = new Document(commitMessage);
	if (commitMessageDocument.getNumberOfLines() > 1) {
		try {
			IRegion lineInfo = commitMessageDocument.getLineInformation(1);
			if (lineInfo.getLength() > 0) {
				valid = false;
				errorCode = 1;
				setWarnings(Messages.AbapGitStaging_commit_message_second_line_not_empty);
			}
		} catch (BadLocationException e) {
			AbapGitUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, AbapGitUIPlugin.PLUGIN_ID, e.getMessage(), e));
		}
	}

	//check author
	String authorText = this.authorText.getText();
	if (getAuthorFromUIText(authorText) == null) {
		setWarnings(Messages.AbapGitStaging_invalid_author);
		valid = false;
		errorCode = 2;
	}

	//check committer
	String committerText = this.committerText.getText();
	if (getCommitterFromUIText(committerText) == null) {
		setWarnings(Messages.AbapGitStaging_invalid_committer);
		valid = false;
		errorCode = 3;
	}

	if (valid) {
		hideWarnings();
	}

	return errorCode;
}