org.eclipse.jface.text.BadLocationException Java Examples

The following examples show how to use org.eclipse.jface.text.BadLocationException. 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: LanguageConfigurationAutoEditStrategy.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns <code>true</code> if the content after the given offset is followed
 * by the given <code>value</code> and false otherwise.
 *
 * @param document the document
 * @param offset   the offset
 * @param value    the content value to check
 * @return <code>true</code> if the content after the given offset is followed
 *         by the given <code>value</code> and false otherwise.
 */
private static boolean isFollowedBy(IDocument document, int offset, String value) {
	for (int i = 0; i < value.length(); i++) {
		if (document.getLength() <= offset) {
			return false;
		}
		try {
			if (document.getChar(offset) != value.charAt(i)) {
				return false;
			}
		} catch (BadLocationException e) {
			return false;
		}
		offset++;
	}
	return true;
}
 
Example #2
Source File: BibTexTemplateCompletion.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method overrides the default one (which is suited for Java
 * (i.e. result in NOT replacing anything before '.', which causes
 * inconvenience, when templates are named like "list.itemize"
 * 
 * @param viewer
 * @param offset Document offset
 * @return prefix (all character counting back from current cursont
 *     position, until a space(' '), linefeed('\n'), carriage return('\r'),
 *     a tab('\t') or the beginning of the file is encountered
 */
protected String extractPrefix(ITextViewer viewer, int offset) {
    int i = offset - 1;
    if (i == -1) {
        return "";
    }
    
    StringBuffer sb = new StringBuffer("");
    char c;
    try {
        c = viewer.getDocument().getChar(i);
        while (!Character.isWhitespace(c)) {
            sb.append(c);
            i--;
            if (i < 0) {
                break;
            } else {
                c = viewer.getDocument().getChar(i);
            }
        }
    } catch (BadLocationException e) {
        TexlipsePlugin.log("BibTemplateCompletion, extractPrefix.", e);
    }
    return sb.reverse().toString();
}
 
Example #3
Source File: IndentUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Indents the line range specified by <code>lines</code> in
 * <code>document</code>. The passed Java project may be
 * <code>null</code>, it is used solely to obtain formatter preferences.
 *
 * @param document the document to be changed
 * @param lines the line range to be indented
 * @param project the Java project to get the formatter preferences from, or
 *        <code>null</code> if global preferences should be used
 * @param result the result from a previous call to <code>indentLines</code>,
 *        in order to maintain comment line properties, or <code>null</code>.
 *        Note that the passed result may be changed by the call.
 * @return an indent result that may be queried for changes and can be
 *         reused in subsequent indentation operations
 * @throws BadLocationException if <code>lines</code> is not a valid line
 *         range on <code>document</code>
 */
public static IndentResult indentLines(IDocument document, ILineRange lines, IJavaProject project, IndentResult result) throws BadLocationException {
	int numberOfLines= lines.getNumberOfLines();

	if (numberOfLines < 1)
		return new IndentResult(null);

	result= reuseOrCreateToken(result, numberOfLines);

	JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
	JavaIndenter indenter= new JavaIndenter(document, scanner, project);
	boolean changed= false;
	int tabSize= CodeFormatterUtil.getTabWidth(project);
	for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) {
		changed |= indentLine(document, line, indenter, scanner, result.commentLinesAtColumnZero, i++, tabSize);
	}
	result.hasChanged= changed;

	return result;
}
 
Example #4
Source File: FormatQuickfixProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Semantic quickfix removing the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_ILLEGAL_CODE)
public void removeOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Remove override", "Remove override.", null, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment());
          rule.setOverride(false);
          return null;
        }
      });
    }
  });
}
 
Example #5
Source File: PythonSourceViewer.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public PythonSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
    super(parent, ruler, null, false, styles, new PyAbstractIndentGuidePreferencesProvider() {

        @Override
        public int getTabWidth() {
            return DefaultIndentPrefs.get(null).getTabWidth();
        }
    });
    StyledText text = this.getTextWidget();
    text.addBidiSegmentListener(new BidiSegmentListener() {
        @Override
        public void lineGetSegments(BidiSegmentEvent event) {
            try {
                event.segments = getBidiLineSegments(event.lineOffset);
            } catch (BadLocationException x) {
                // ignore
            }
        }
    });
    updateViewerFont();
    updateViewerColors();
    getPreferenceStore().addPropertyChangeListener(propertyChangeListener);
}
 
Example #6
Source File: CleanUpPostSaveListener.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void performEdit(IDocument document, long oldFileValue, LinkedList<UndoEdit> editCollector, long[] oldDocValue, boolean[] setContentStampSuccess) throws MalformedTreeException, BadLocationException, CoreException {
	if (document instanceof IDocumentExtension4) {
		oldDocValue[0]= ((IDocumentExtension4)document).getModificationStamp();
	} else {
		oldDocValue[0]= oldFileValue;
	}

	// perform the changes
	for (int index= 0; index < fUndos.length; index++) {
		UndoEdit edit= fUndos[index];
		UndoEdit redo= edit.apply(document, TextEdit.CREATE_UNDO);
		editCollector.addFirst(redo);
	}

	if (document instanceof IDocumentExtension4 && fDocumentStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) {
		try {
			((IDocumentExtension4)document).replace(0, 0, "", fDocumentStamp); //$NON-NLS-1$
			setContentStampSuccess[0]= true;
		} catch (BadLocationException e) {
			throw wrapBadLocationException(e);
		}
	}
}
 
Example #7
Source File: NonRuleBasedDamagerRepairer.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the end offset of the line that contains the specified offset or
 * if the offset is inside a line delimiter, the end offset of the next
 * line.
 * 
 * @param offset
 *            the offset whose line end offset must be computed
 * 
 * @return the line end offset for the given offset
 * 
 * @exception BadLocationException
 *                if offset is invalid in the current document
 */
protected int endOfLineOf( int offset ) throws BadLocationException
{
	IRegion info = fDocument.getLineInformationOfOffset( offset );

	if ( offset <= info.getOffset( ) + info.getLength( ) )
	{
		return info.getOffset( ) + info.getLength( );
	}

	int line = fDocument.getLineOfOffset( offset );

	try
	{
		info = fDocument.getLineInformation( line + 1 );

		return info.getOffset( ) + info.getLength( );
	}
	catch ( BadLocationException x )
	{
		return fDocument.getLength( );
	}
}
 
Example #8
Source File: LangCompletionProposal.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
protected String doGetAdditionalProposalInfo(IProgressMonitor monitor) {
	Document tempDocument = new Document(sourceOpContext.getSource());
	doApply(tempDocument, false);
	try {
		tempDocument.replace(endPositionAfterApply, 0, " ");
	} catch(BadLocationException e) {
		
	}
	
	DocumentSourceBuffer tempSourceBuffer = new DocumentSourceBuffer(tempDocument) {
		@Override
		public Location getLocation_orNull() {
			return sourceOpContext.getOptionalFileLocation().orElse(null);
		}
	};
	String doc = new DocDisplayInfoSupplier(tempSourceBuffer, getReplaceOffset())
			.doGetDocumentation(EclipseUtils.om(monitor));
	
	if(doc == null) {
		return null;
	}
	return BrowserControlCreator.wrapHTMLBody(doc);
}
 
Example #9
Source File: InteractiveConsoleCommand.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public void execute(PyEdit pyEdit) {
    IAction action = pyEdit.getAction("org.python.pydev.editor.actions.execLineInConsole");
    if (action instanceof IExecuteLineAction) {
        IExecuteLineAction executeLineAction = (IExecuteLineAction) action;
        String commandText = this.interactiveConsoleCommand.commandText;
        TextSelectionUtils ts = pyEdit.createTextSelectionUtils();
        String selectedText;
        try {
            selectedText = ts.getSelectedText();
        } catch (BadLocationException e) {
            selectedText = "";
        }
        if (selectedText.length() == 0) {
            selectedText = ts.getCursorLineContents();
        }
        executeLineAction.executeText(new FastStringBuffer(commandText, selectedText.length() * 2).replaceAll(
                "${text}",
                selectedText).toString());
    } else {
        Log.log("Expected: " + action + " to implement IExecuteLineAction.");
    }
}
 
Example #10
Source File: ScriptConsoleHistory.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Commits the currently added line (last called in update) to the history and keeps it there.
 */
public void commit() {
    String lineToAddToHistory = getBufferLine();
    try {
        historyAsDoc.replace(historyAsDoc.getLength(), 0, lineToAddToHistory + "\n");
    } catch (BadLocationException e) {
        Log.log(e);
    }

    if (lineToAddToHistory.length() == 0) {
        currLine = lines.size() - 1;
        return;
    }

    lines.set(lines.size() - 1, lineToAddToHistory);

    lines.add(""); //$NON-NLS-1$
    currLine = lines.size() - 1;
}
 
Example #11
Source File: DocumentLineList.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
	IDocument document = event.getDocument();
	try {
		int startLine = DocumentHelper.getStartLine(event);
		if (!DocumentHelper.isRemove(event)) {
			int endLine = DocumentHelper.getEndLine(event, false);
			// Insert new lines
			for (int i = startLine; i < endLine; i++) {
				DocumentLineList.this.addLine(i + 1);
			}
			if (startLine == endLine) {
				DocumentLineList.this.updateLine(startLine);
			}
		} else {
			// Update line
			DocumentLineList.this.updateLine(startLine);
		}
		invalidateLine(startLine);
	} catch (BadLocationException e) {
		TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
	}
}
 
Example #12
Source File: TextSelectionUtils.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return the complete dotted string given the current selection and the strings after
 *
 * e.g.: if we have a text of
 * 'value = aa.bb.cc()' and 'aa' is selected, this method would return the whole dotted string ('aa.bb.cc')
 * @throws BadLocationException
 */
public String getFullRepAfterSelection() throws BadLocationException {
    int absoluteCursorOffset = getAbsoluteCursorOffset();
    int length = doc.getLength();
    int end = absoluteCursorOffset;
    char ch = doc.getChar(end);
    while (Character.isLetterOrDigit(ch) || ch == '.') {
        end++;
        //check if we can still get some char
        if (length - 1 < end) {
            break;
        }
        ch = doc.getChar(end);
    }
    return doc.get(absoluteCursorOffset, end - absoluteCursorOffset);
}
 
Example #13
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
protected boolean isReplacedAreaEmpty(TemplateContext context) {
	// don't trim the buffer if the replacement area is empty
	// case: surrounding empty lines with block
	if (context instanceof DocumentTemplateContext) {
		DocumentTemplateContext dtc= (DocumentTemplateContext) context;
		if (dtc.getStart() == dtc.getCompletionOffset())
			try {
				IDocument document= dtc.getDocument();
				int lineOffset= document.getLineInformationOfOffset(dtc.getStart()).getOffset();
				//only if we are at the beginning of the line
				if (lineOffset != dtc.getStart())
					return false;

				//Does the selection only contain whitespace characters?
				if (document.get(dtc.getStart(), dtc.getEnd() - dtc.getStart()).trim().length() == 0)
					return true;
			} catch (BadLocationException x) {
				// ignore - this may happen when the document was modified after the initial invocation, and the
				// context does not track the changes properly - don't trim in that case
				return true;
			}
	}
	return false;
}
 
Example #14
Source File: LangCompletionProposal.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
	if(offset < getReplaceOffset())
		return false;
	
	String prefix;
	try {
		prefix = document.get(getReplaceOffset(), offset - getReplaceOffset());
	} catch (BadLocationException e) {
		return false;
	}
	boolean validPrefix = isValidPrefix(prefix);
	
	if(validPrefix && event != null) {
		// adapt replacement length to document event/ 
		int eventEndOffset = event.fOffset + event.fLength;
		// The event should be a common prefix completion (this should be true anyways) :
		int replaceEndPos = getReplaceOffset() + getReplaceLength();
		if(event.fOffset >= getReplaceOffset() && eventEndOffset <= replaceEndPos) {
			int delta = (event.fText == null ? 0 : event.fText.length()) - event.fLength;
			this.replaceLength = Math.max(getReplaceLength() + delta, 0);
		}
	}
	
	return validPrefix;
}
 
Example #15
Source File: MultiLineTerminalsEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Expects the cursor to be in the same line as the start terminal
 * puts any text between start terminal and cursor into a separate newline before the cursor.
 * puts any text between cursor and end terminal into a separate newline after the cursor.
 * puts the closing terminal into a separate line at the end.
 * adds a closing terminal if not existent.
 */
protected CommandInfo handleCursorInFirstLine(IDocument document, DocumentCommand command, IRegion startTerminal,
		IRegion stopTerminal) throws BadLocationException {
	CommandInfo newC = new CommandInfo();
	newC.isChange = true;
	newC.offset = command.offset;
	newC.text += command.text + indentationString;
	newC.cursorOffset = command.offset + newC.text.length();
	if (stopTerminal == null && atEndOfLineInput(document, command.offset)) {
		newC.text += command.text + getRightTerminal();
	}
	if (stopTerminal != null && stopTerminal.getOffset() >= command.offset && util.isSameLine(document, stopTerminal.getOffset(), command.offset)) {
		String string = document.get(command.offset, stopTerminal.getOffset() - command.offset);
		if (string.trim().length() > 0)
			newC.text += string.trim();
		newC.text += command.text;
		newC.length += string.length();
	}
	return newC;
}
 
Example #16
Source File: CountLinesBuffer.java    From e4macs with Eclipse Public License 1.0 6 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 {
	int offset = currentSelection.getOffset();
	IRegion lineInfo = document.getLineInformationOfOffset(offset);
	int lineTotal = document.getNumberOfLines();
	int lineNumber = document.getLineOfOffset(offset);
	// only include current, if at beginning of line
	if (offset != lineInfo.getOffset()) {
		++lineNumber;
	}
	if (document.getLength() == offset) {
		lineNumber = lineTotal;
	}
	setCmdResult(new Integer(lineTotal));
	EmacsPlusUtils.showMessage(editor, String.format(COUNT_BUFFER, lineTotal, lineNumber, lineTotal - lineNumber), false);
	return super.transform(editor, document, currentSelection, event);
}
 
Example #17
Source File: ChangeManager.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Applies all given changes to the given document. This method assumes that 'changes' contains only changes
 * intended for the given document; the actual URI stored in the changes is ignored.
 */
public void applyAllInSameDocument(Collection<? extends IAtomicChange> changes, IDocument document)
		throws BadLocationException {
	DocumentRewriteSession rewriteSession = null;
	try {
		// prepare
		if (document instanceof IDocumentExtension4) {
			rewriteSession = ((IDocumentExtension4) document).startRewriteSession(
					DocumentRewriteSessionType.UNRESTRICTED);
		}
		// perform replacements
		for (IAtomicChange currRepl : changes) {
			currRepl.apply(document);
		}
	} finally {
		// cleanup
		if (rewriteSession != null)
			((IDocumentExtension4) document).stopRewriteSession(rewriteSession);
	}
}
 
Example #18
Source File: WhitespaceHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Count the whitespace to the left and right of offset, potentially counting over EOLs.
 * @param document
 * @param offset
 * @param dir
 * @param ignoreCR - count over EOLs if true
 * @return the whitespace count
 * @throws BadLocationException
 */
protected int countWS(IDocument document, int offset, int dir, boolean ignoreCR) throws BadLocationException {
	String eol = getLineDelimiter();
	int lineOff = offset;
	int off = offset;
	int lastOff = document.getLength(); // -1;	// n
	char c;
	while ((-1 < off && off < lastOff) && (c = document.getChar(off)) <= ' ') { 
		if (eol.indexOf(c) != -1) {
			if (!ignoreCR) {
				break;
			}
			// preserve the position past the last EOL
			lineOff = off + dir;
		}
		off = off + dir;
	}
	// if ignoreCR == true, then we're interested in complete blank lines only
	return Math.abs(offset - (ignoreCR ? lineOff : off));
}
 
Example #19
Source File: ExpressionSyntaxColoringPage.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private String getNamedStyleAtOffset( int offset )
{
	// ensure the offset is clean
	if ( offset >= fDocument.getLength( ) )
		return getNamedStyleAtOffset( fDocument.getLength( ) - 1 );
	else if ( offset < 0 )
		return getNamedStyleAtOffset( 0 );
	try
	{
		String regionContext = fDocument.getPartition( offset ).getType( );

		String namedStyle = (String) fContextToStyleMap.get( regionContext );
		if ( namedStyle != null )
		{
			return namedStyle;
		}
	}
	catch ( BadLocationException e )
	{
	}
	return null;
}
 
Example #20
Source File: PySelectionTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @throws BadLocationException
 *
 */
public void testGeneral() throws BadLocationException {
    ps = new PySelection(doc, 0);
    assertEquals("TestLine1", ps.getCursorLineContents());
    assertEquals("", ps.getLineContentsToCursor());
    ps.selectCompleteLine();

    assertEquals("TestLine1", ps.getCursorLineContents());
    assertEquals("TestLine1", ps.getLine(0));
    assertEquals("TestLine2#comm2", ps.getLine(1));

    ps.deleteLine(0);
    assertEquals("TestLine2#comm2", ps.getLine(0));
    ps.addLine("TestLine1", 0);

}
 
Example #21
Source File: DefaultFoldedPosition.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public int computeCaptionOffset(IDocument document) throws BadLocationException {
	if (contentStart == UNSET) {
		return 0;
	}
	return contentStart;
}
 
Example #22
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns <code>true</code> if the comment being inserted at
 * <code>command.offset</code> is the first comment (the first javadoc
 * comment if <code>ignoreJavadoc</code> is <code>true</code>) of the given
 * member.
 * <p>
 * see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=55325 (don't add
 * parameters if the member already has a comment)
 * </p>
 */
private boolean isFirstComment(IDocument document, DocumentCommand command, IMember member,
		boolean ignoreNonJavadoc) throws BadLocationException, JavaScriptModelException {
	IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	ISourceRange sourceRange = member.getSourceRange();
	if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
		return false;
	int srcOffset = sourceRange.getOffset();
	int srcLength = sourceRange.getLength();
	int nameRelativeOffset = member.getNameRange().getOffset() - srcOffset;
	int partitionRelativeOffset = partition.getOffset() - srcOffset;
	String token = ignoreNonJavadoc ? "/**" : "/*"; //$NON-NLS-1$ //$NON-NLS-2$
	return document.get(srcOffset, srcLength).lastIndexOf(token, nameRelativeOffset) == partitionRelativeOffset;
}
 
Example #23
Source File: ImplementationsSearchQuery.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
public ImplementationsSearchQuery(int offset, LSPDocumentInfo info) throws BadLocationException {
	super("", false, false, null); //$NON-NLS-1$
	this.position = LSPEclipseUtils.toPosition(offset, info.getDocument());
	this.info = info;
	IResource resource = LSPEclipseUtils.findResourceFor(info.getFileUri().toString());
	this.filename = resource != null ? resource.getName() : info.getFileUri().toString();
}
 
Example #24
Source File: TMPresentationReconciler.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
private int getTokenLengh(int tokenStartIndex, TMToken nextToken, int line, IDocument document)
		throws BadLocationException {
	if (nextToken != null) {
		return nextToken.startIndex - tokenStartIndex;
	}
	return document.getLineLength(line) - tokenStartIndex;
}
 
Example #25
Source File: JdbcSQLContentAssistProcessor.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public ICompletionProposal[] computeCompletionProposals(
		ITextViewer viewer, int offset )
{
	try
	{
		if ( offset > viewer.getTopIndexStartOffset( ) )
		{
			//Check the character before the offset
			char ch = viewer.getDocument( ).getChar( offset - 1 );

			if ( ch == '.' ) //$NON-NLS-1$
			{
				lastProposals = getTableOrColumnCompletionProposals( viewer,
						offset );
				return lastProposals;
			}
			else
			{
				return getRelevantProposals( viewer, offset );
			}
		}
	}
	catch ( BadLocationException e )
	{
	}
	return null;
}
 
Example #26
Source File: ScriptConsoleDocumentListener.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the length of the current command line (all the currently
 * editable area)
 *
 * @throws BadLocationException
 */
public int getCommandLineLength() throws BadLocationException {
    int lastLine = doc.getNumberOfLines() - 1;
    int len = doc.getLineLength(lastLine) - getLastLineReadOnlySize();
    if (len <= 0) {
        return 0;
    }
    return len;
}
 
Example #27
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new tracker.
 * 
 * @param buffer the buffer to track
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
	Assert.isLegal(buffer != null);
	fBuffer= buffer;
	fDocument= new Document(fBuffer.getString());
	installJavaStuff(fDocument);
	fDocument.addPositionCategory(CATEGORY);
	fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
	fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
}
 
Example #28
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 #29
Source File: ToolMarkersHelper.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
protected int getCharEnd(int charStart, IDocument doc) {
	if(!readWordForCharEnd) {
		return charStart + 1;
	}
	
	int ix = charStart;
	try {
		ix++;
		char ch = doc.getChar(ix-1);
		
		if(Character.isDigit(ch)) {
			
			while(Character.isDigit(doc.getChar(ix))) {
				ix++;
			}
			
		} if(Character.isAlphabetic(ch)) {
			
			while(Character.isJavaIdentifierPart(doc.getChar(ix))) {
				ix++;
			}
			
		}
	} catch(BadLocationException e) {
		
	}
	
	return ix;
}
 
Example #30
Source File: ContentFormatter.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void format(IDocument document, IRegion region) {
	IXtextDocument doc = xtextDocumentUtil.getXtextDocument(document);
	TextEdit r = doc.priorityReadOnly(new FormattingUnitOfWork(doc, region));
	try {
		if (r != null)
			r.apply(document);
	} catch (BadLocationException e) {
		throw new RuntimeException(e);
	}
}