org.eclipse.jface.text.IDocument#getLength ( )源码实例Demo

下面列出了org.eclipse.jface.text.IDocument#getLength ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: n4js   文件: N4JSStackTraceConsole.java
/**
 * Saves the pasted text into a hidden document so that it will be available the next time the console will be
 * opened.
 */
public void saveDocument() {
	try (FileOutputStream fout = new FileOutputStream(FILE_NAME)) {
		IDocument document = getDocument();
		if (document != null) {
			if (document.getLength() > 0) {
				String contents = document.get();
				fout.write(contents.getBytes());
			} else {
				File file = new File(FILE_NAME);
				file.delete();
			}
		}
	} catch (IOException e) {
		// just ignore that, not important
	}
}
 
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
		throws BadLocationException {
	if (command.text.equals("") && command.length == 1) {
		if (command.offset + right.length() + left.length() > document.getLength())
			return;
		if (command.offset + command.length - left.length() < 0)
			return;
		if (command.length != left.length())
			return;
		String string = document.get(command.offset, left.length() + right.length());
		if (string.equals(left + right)) {
			command.length = left.length() + right.length();
		}
	}
}
 
源代码3 项目: xds-ide   文件: XdsConsoleViewer.java
@Override
public void lineGetStyle(LineStyleEvent event) {
    // Overrided to don't show hyperlinks as original console do it 
    IDocument document = getDocument();
    if (document != null && document.getLength() > 0) {
        ArrayList<StyleRange> ranges = new ArrayList<StyleRange>();
        int offset = event.lineOffset;
        int length = event.lineText.length();

        StyleRange[] partitionerStyles = ((IConsoleDocumentPartitioner) document.getDocumentPartitioner()).getStyleRanges(event.lineOffset, event.lineText.length());
        if (partitionerStyles != null) {
            for (int i = 0; i < partitionerStyles.length; i++) {
                ranges.add(partitionerStyles[i]);
            }
        } else {
            ranges.add(new StyleRange(offset, length, null, null));
        }

        if (ranges.size() > 0) {
            event.styles = (StyleRange[]) ranges.toArray(new StyleRange[ranges.size()]);
        }
    }
}
 
源代码4 项目: xtext-eclipse   文件: DocumentUtil.java
/**
 * searches for the given string within the same partition type
 * 
 * @return the region of the match or <code>null</code> if no match were found
 * @since 2.4
 */
public IRegion searchInSamePartition(String toFind, String documentText, IDocument document, int startOffset)
		throws BadLocationException {
	if (startOffset >= document.getLength()) {
		return null;
	}
	String text = preProcessSearchString(documentText);
	ITypedRegion partition = document.getPartition(startOffset);
	
	int indexOf = text.indexOf(toFind, getOffset(toFind, startOffset));
	while (indexOf >= 0 && indexOf < document.getLength()) {
		ITypedRegion partition2 = document.getPartition(indexOf);
		if (partition2.getType().equals(partition.getType())) {
			return new Region(indexOf, toFind.length());
		}
		indexOf = text.indexOf(toFind, partition2.getOffset() + partition2.getLength());
	}
	String trimmed = toFind.trim();
	if (trimmed.length() > 0 && trimmed.length() != toFind.length()) {
		return searchInSamePartition(trimmed, documentText, document, startOffset);
	}
	return null;
}
 
源代码5 项目: e4macs   文件: TransposeLineHandler.java
private void swapLines(IDocument document, Lines lines) throws BadLocationException {

		if (lines.isOk() && (lines.getLine2().getOffset() < document.getLength())) {
			IRegion line1 = lines.getLine1();
			IRegion line2 = lines.getLine2();
			String line1Text = document.get(line1.getOffset(), line1.getLength());
			String line2Text = document.get(line2.getOffset(), line2.getLength());
			// swap the text from bottom up
			updateText(document, line2.getOffset(), line2.getLength(), line1Text);
			updateText(document, line1.getOffset(), line1.getLength(), line2Text);
		}
	}
 
源代码6 项目: Pydev   文件: ScopeSelectionAction.java
private static String getCurrentSelectionCacheKey(BaseEditor pyEdit) {
    IDocument doc = pyEdit.getDocument();

    int length = doc.getLength();
    String key = Integer.toString(length);
    if (doc instanceof IDocumentExtension4) {
        IDocumentExtension4 document = (IDocumentExtension4) doc;
        long modificationStamp = document.getModificationStamp();
        key += " - " + modificationStamp;
    }
    return key;
}
 
源代码7 项目: xds-ide   文件: QuickXFind.java
private static SearchRegion getSearchRegion(IDocument document, int offset) 
{
    SearchRegion searchRegion = null;

    if ((offset >= 0) && (offset <= document.getLength())) {
        int start = offset;
        int end   = offset;
        try {
            boolean isCursorOnDelimiter = (offset == document.getLength())
                                       || document.get(offset, 1).matches(WORD_DELIMETERS);

            if (isCursorOnDelimiter) {
                start--;
            }
            while ((start >= 0) && !document.get(start, 1).matches(WORD_DELIMETERS)) {
                start--;
            }
            if (start !=  offset) {
                start++;
            }
            
            while ((end < document.getLength()) && !document.get(end, 1).matches(WORD_DELIMETERS)) {
                end++;
            }

            if (start != end) {
                int length = end - start;
                searchRegion = new SearchRegion(
                    document.get(start, length), start, length 
                );
            }
        } catch (BadLocationException e) {
        }
        
    }
    return searchRegion;
}
 
源代码8 项目: http4e   文件: XMLDoubleClickStrategy.java
protected boolean selectWord(int caretPos) {

		IDocument doc = fText.getDocument();
		int startPos, endPos;

		try {

			int pos = caretPos;
			char c;

			while (pos >= 0) {
				c = doc.getChar(pos);
				if (!Character.isJavaIdentifierPart(c))
					break;
				--pos;
			}

			startPos = pos;

			pos = caretPos;
			int length = doc.getLength();

			while (pos < length) {
				c = doc.getChar(pos);
				if (!Character.isJavaIdentifierPart(c))
					break;
				++pos;
			}

			endPos = pos;
			selectRange(startPos, endPos);
			return true;

		} catch (BadLocationException x) {
		}

		return false;
	}
 
源代码9 项目: e4macs   文件: WhatCursorPosition.java
/**
 * @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);

}
 
源代码10 项目: Pydev   文件: PyCreateClassTest.java
public void testPyCreateClassInSameModule5() throws Exception {
    PyCreateClass pyCreateClass = new PyCreateClass();

    String source = "" +
            "a = 10\n" +
            "#=============\n" +
            "#Comment\n" +
            "#=============\n"
            +
            "class Existing(object):\n" +
            "    pass\n" +
            "\n" +
            "MyClass()";
    IDocument document = new Document(source);
    ICoreTextSelection selection = new CoreTextSelection(document, document.getLength() - 5, 0);
    RefactoringInfo info = new RefactoringInfo(document, selection, PY_27_ONLY_GRAMMAR_VERSION_PROVIDER);

    pyCreateClass.execute(info, PyCreateClass.LOCATION_STRATEGY_BEFORE_CURRENT);

    assertContentsEqual("" +
            "a = 10\n" +
            "#=============\n" +
            "#Comment\n" +
            "#=============\n"
            +
            "class Existing(object):\n" +
            "    pass\n" +
            "\n" +
            "\n" +
            "class MyClass(${object}):\n"
            +
            "    ${pass}${cursor}\n" +
            "\n" +
            "\n" +
            "MyClass()" +
            "", document.get());
}
 
源代码11 项目: e4macs   文件: KillLineHandler.java
/**
 * When called from a console context, will use ST.CUT
 * 
 * @see com.mulgasoft.emacsplus.commands.ConsoleCmdHandler#consoleDispatch(TextConsoleViewer,
 *      IConsoleView, ExecutionEvent)
 */
public Object consoleDispatch(TextConsoleViewer viewer, IConsoleView activePart, ExecutionEvent event) {
	if (viewer.isEditable()) {
		IDocument doc = viewer.getDocument();
		StyledText st = viewer.getTextWidget();
		int offset = st.getCaretOffset();
		try {
			IRegion info = doc.getLineInformationOfOffset(offset);
			int noffset = info.getOffset() + info.getLength();
			if (offset == noffset) {
				int line = doc.getLineOfOffset(offset);
				if (++line < doc.getNumberOfLines()) {
					noffset = doc.getLineOffset(line);
					if (noffset == doc.getLength()) {
						noffset = offset;
					}
				}
			}
			if (offset != noffset) {
				st.redraw();
				st.setSelection(offset, noffset);
				KillRing.getInstance().setKill(CUT_LINE_TO_END, false);
				return super.consoleDispatch(viewer, activePart, event);
			}
			viewer.refresh();
		} catch (BadLocationException e) {
		}
	}
	return null;
}
 
public ISelection getSelection() {
	if (fControl instanceof StyledText) {
		IDocument document= new Document(((StyledText)fControl).getSelectionText());
		return new TextSelection(document, 0, document.getLength());
	} else {
		// FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
		return StructuredSelection.EMPTY;
	}
}
 
源代码13 项目: Pydev   文件: PyCreateMethodTest.java
public void testPyCreateMethod() {
    PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();

    String source = "" +
            "class A(object):\n" +
            "\n" +
            "\n" +
            "\n" +
            "    def m1(self):\n" +
            "        self.m2()";
    IDocument document = new Document(source);
    ICoreTextSelection selection = new CoreTextSelection(document, document.getLength() - "2()".length(), 0);
    RefactoringInfo info = new RefactoringInfo(document, selection, PY_27_ONLY_GRAMMAR_VERSION_PROVIDER);

    pyCreateMethod.setCreateInClass("A");
    pyCreateMethod.setCreateAs(PyCreateMethodOrField.BOUND_METHOD);
    pyCreateMethod.execute(info, AbstractPyCreateAction.LOCATION_STRATEGY_BEFORE_CURRENT);

    String expected = "" +
            "class A(object):\n" +
            "\n" +
            "\n" +
            "\n" +
            "    def m2(self):\n"
            +
            "        ${pass}${cursor}\n" +
            "    \n" +
            "    \n" +
            "    def m1(self):\n" +
            "        self.m2()";

    assertContentsEqual(expected, document.get());
}
 
源代码14 项目: Pydev   文件: TddTestWorkbench.java
private void checkCreateField() throws CoreException, BadLocationException, MisconfigurationException {
    String mod1Contents = "" +
            "class Err(object):\n" +
            "\n" +
            "   def Foo(self):\n"
            +
            "       self._suggestion_not_there.get()" +
            "";
    setContentsAndWaitReparseAndError(mod1Contents, false); //no error here

    TddCodeGenerationQuickFixParticipant quickFix = new TddCodeGenerationQuickFixParticipant();
    IDocument doc = editor.getDocument();
    int offset = doc.getLength();
    PySelection ps = new PySelection(doc, offset);
    assertTrue(quickFix.isValid(ps, "", editor, offset));
    try {
        waitForQuickFixProps(quickFix, ps, offset, "Create _suggestion_not_there field at Err").apply(
                editor.getISourceViewer(), '\n', 0, offset);
        assertContentsEqual("" +
                "class Err(object):\n" +
                "\n" +
                "   \n" +
                "   def __init__(self):\n"
                +
                "       self._suggestion_not_there = None\n" +
                "   \n" +
                "   \n" +
                "\n" +
                "   def Foo(self):\n"
                +
                "       self._suggestion_not_there.get()" +
                "", editor.getDocument().get());
    } finally {
        editor.doRevertToSaved();
    }
}
 
源代码15 项目: Pydev   文件: TddTestWorkbench.java
private void checkCreateMethodAtField() throws CoreException, BadLocationException, MisconfigurationException {
    String mod1Contents = "" +
            "class Bar(object):\n" +
            "   pass\n" +
            "\n" +
            "class MyTestClass(object):\n"
            +
            "    \n" +
            "    def __init__(self):\n" +
            "        self.bar = Bar()\n" +
            "    \n"
            +
            "    def test_1(self):\n" +
            "        self.bar.something()" +
            "";
    setContentsAndWaitReparseAndError(mod1Contents, false); //no error here

    TddCodeGenerationQuickFixParticipant quickFix = new TddCodeGenerationQuickFixParticipant();
    IDocument doc = editor.getDocument();
    int offset = doc.getLength();
    PySelection ps = new PySelection(doc, offset);
    assertTrue(quickFix.isValid(ps, "", editor, offset));
    try {
        waitForQuickFixProps(quickFix, ps, offset, "Create something method at Bar (pack1.pack2.mod1)").apply(
                editor.getISourceViewer(), '\n', 0, offset);
        assertContentsEqual("" +
                "class Bar(object):\n" +
                "   \n" +
                "   \n" +
                "   def something(self):\n"
                +
                "       pass\n" +
                "   \n" +
                "   \n" +
                "\n" +
                "\n" +
                "class MyTestClass(object):\n" +
                "    \n"
                +
                "    def __init__(self):\n" +
                "        self.bar = Bar()\n" +
                "    \n" +
                "    def test_1(self):\n"
                +
                "        self.bar.something()" +
                "", editor.getDocument().get());
    } finally {
        editor.doRevertToSaved();
    }
}
 
源代码16 项目: Pydev   文件: TddTestWorkbench.java
private void checkCreateFieldAtField() throws CoreException, BadLocationException, MisconfigurationException {
    String mod1Contents = "" +
            "class Bar(object):\n" +
            "    pass\n" +
            "\n" +
            "class MyTestClass(object):\n"
            +
            "    \n" +
            "    def __init__(self):\n" +
            "        self.bar = Bar()\n" +
            "    \n"
            +
            "    def test_1(self):\n" +
            "        self.bar.something" +
            "";
    setContentsAndWaitReparseAndError(mod1Contents, false); //no error here

    TddCodeGenerationQuickFixParticipant quickFix = new TddCodeGenerationQuickFixParticipant();
    IDocument doc = editor.getDocument();
    int offset = doc.getLength();
    PySelection ps = new PySelection(doc, offset);
    assertTrue(quickFix.isValid(ps, "", editor, offset));
    try {
        waitForQuickFixProps(quickFix, ps, offset, "Create something field at Bar (pack1.pack2.mod1)").apply(
                editor.getISourceViewer(), '\n', 0, offset);
        assertContentsEqual("" +
                "class Bar(object):\n" +
                "    \n" +
                "    \n" +
                "    def __init__(self):\n"
                +
                "        self.something = None\n" +
                "    \n" +
                "    \n" +
                "\n" +
                "\n"
                +
                "class MyTestClass(object):\n" +
                "    \n" +
                "    def __init__(self):\n"
                +
                "        self.bar = Bar()\n" +
                "    \n" +
                "    def test_1(self):\n"
                +
                "        self.bar.something" +
                "", editor.getDocument().get());
    } finally {
        editor.doRevertToSaved();
    }
}
 
源代码17 项目: xtext-eclipse   文件: TextViewerMoveLinesAction.java
@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;
	}
}
 
private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
	if (c.offset < 1 || d.getLength() == 0)
		return;

	JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);

	int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);

	try {
		// current line
		int line= d.getLineOfOffset(p);
		int lineOffset= d.getLineOffset(line);

		// make sure we don't have any leading comments etc.
		if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
			return;

		// line of last Java code
		int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
		if (pos == -1)
			return;
		int lastLine= d.getLineOfOffset(pos);

		// only shift if the last java line is further up and is a braceless block candidate
		if (lastLine < line) {

			TypeScriptIndenter indenter= new TypeScriptIndenter(d, scanner, fProject);
			StringBuffer indent= indenter.computeIndentation(p, true);
			String toDelete= d.get(lineOffset, c.offset - lineOffset);
			if (indent != null && !indent.toString().equals(toDelete)) {
				c.text= indent.append(c.text).toString();
				c.length += c.offset - lineOffset;
				c.offset= lineOffset;
			}
		}

	} catch (BadLocationException e) {
		JSDTTypeScriptUIPlugin.log(e);
	}

}
 
/**
 * @param d
 *            the document to work on
 * @param c
 *            the command to deal with
 * @return true if the indentation occurred, false otherwise
 */
protected boolean autoIndent(IDocument d, DocumentCommand c)
{
	if (c.offset <= 0 || d.getLength() == 0 || !shouldAutoIndent())
	{
		return false;
	}

	String newline = c.text;
	try
	{
		// Get the line and run a regexp check against it
		IRegion curLineRegion = d.getLineInformationOfOffset(c.offset);
		String scope = getScopeAtOffset(d, c.offset);
		RubyRegexp increaseIndentRegexp = getIncreaseIndentRegexp(scope);
		String lineContent = d.get(curLineRegion.getOffset(), c.offset - curLineRegion.getOffset());

		if (matchesRegexp(increaseIndentRegexp, lineContent))
		{
			String previousLineIndent = getAutoIndentAfterNewLine(d, c);
			String restOfLine = d.get(c.offset, curLineRegion.getLength() - (c.offset - curLineRegion.getOffset()));
			String startIndent = newline + previousLineIndent + getIndentString();
			if (indentAndPushTrailingContentAfterNewlineAndCursor(lineContent, restOfLine))
			{
				c.text = startIndent + newline + previousLineIndent;
			}
			else
			{
				c.text = startIndent;
			}
			c.shiftsCaret = false;
			c.caretOffset = c.offset + startIndent.length();
			return true;
		}
	}
	catch (BadLocationException e)
	{
		IdeLog.logError(CommonEditorPlugin.getDefault(), e);
	}

	return false;
}
 
源代码20 项目: Pydev   文件: DocumentCharacterIterator.java
/**
 * Creates an iterator, starting at offset <code>first</code>.
 * 
 * @param document the document backing this iterator
 * @param first the first character to consider
 * @throws BadLocationException if the indices are out of bounds
 */
public DocumentCharacterIterator(IDocument document, int first) throws BadLocationException {
    this(document, first, document.getLength());
}