下面列出了怎么用org.eclipse.jface.text.Document的API类实例代码及写法,或者点击链接到github查看源代码。
public void testArgs() throws Exception {
String d = "" +
"def func(*args):\n" +
" args" +
"";
Document doc = new Document(d);
SourceModule module = AbstractModule.createModuleFromDoc("", null, doc, nature, true);
Module ast = (Module) module.getAst();
assertEquals(1, ast.body.length);
ICompletionState emptyCompletionState = CompletionStateFactory.getEmptyCompletionState("args", nature,
new CompletionCache());
Definition[] defs = module.findDefinition(emptyCompletionState, 2, 7, nature);
assertEquals(1, defs.length);
assertEquals(1, defs[0].line);
assertEquals(11, defs[0].col);
assertSame(module, defs[0].module);
}
public void testIndentParensPep8_2_tabs() throws Exception {
// New indent mode:
// pep8 indents aligned with the opening parens (if not directly after the opening parens)
// or with an additional level for vertical alignment of multiple vars after the parens.
TestIndentPrefs prefs = new TestIndentPrefs(true, 4);
prefs.indentToParAsPep8 = true;
prefs.setForceTabs(true);
strategy.setIndentPrefs(prefs);
String doc = "" +
"def testItrararara(aa, bb," + // indent 1 because of the def and an additional one for the parens.
"";
DocCmd docCmd = new DocCmd(doc.length(), 0, "\n");
strategy.customizeDocumentCommand(new Document(doc), docCmd);
String expected = "\n\t\t\t\t";
assertEquals(expected, docCmd.text);
}
public void testMod3() {
String doc = "" +
"def method(a, b):\n" +
" pass\n" +
"other = another = method\n" +
"";
ParseOutput obj = PyParser.reparseDocument(new PyParser.ParserInfo(new Document(doc),
IPythonNature.GRAMMAR_PYTHON_VERSION_2_5, null));
SimpleNode n = (SimpleNode) obj.ast;
IModule module = AbstractModule.createModule(n, null);
TokensList globalTokens = module.getGlobalTokens();
assertEquals(6, globalTokens.size());
compareReps(globalTokens, "__file__ __name__ __dict__ method other another");
int found = 0;
for (IterTokenEntry entry : globalTokens) {
IToken t = entry.getToken();
if (t.getRepresentation().equals("method") || t.getRepresentation().equals("other")
|| t.getRepresentation().equals("another")) {
assertEquals("( a, b )", t.getArgs());
found += 1;
}
}
assertEquals(3, found);
}
/**
* Cuts the visual equivalent of <code>toDelete</code> characters out of the
* indentation of line <code>line</code> in <code>document</code>. Leaves
* leading comment signs alone.
*
* @param document the document
* @param line the line
* @param toDelete the number of space equivalents to delete
* @param tabLength the length of a tab
* @throws BadLocationException on concurrent document modification
*/
private void cutIndent(Document document, int line, int toDelete, int tabLength) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT))
from += 2;
int to= from;
while (toDelete > 0 && to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
toDelete -= computeVisualLength(ch, tabLength);
if (toDelete >= 0)
to++;
else
break;
}
document.replace(from, to - from, ""); //$NON-NLS-1$
}
public void testElse2() {
strategy.setIndentPrefs(new TestIndentPrefs(true, 4, true));
String strDoc = "" +
"try:\n" +
" print a\n" +
"except RuntimeError:\n" +
" a = 20\n" +
" else";
int initialOffset = strDoc.length();
DocCmd docCmd = new DocCmd(initialOffset, 0, ":");
Document doc = new Document(strDoc);
strategy.customizeDocumentCommand(doc, docCmd);
String expected = ":";
assertEquals(docCmd.offset, initialOffset - 4);
assertEquals(expected, docCmd.text);
assertEquals("" +
"try:\n" +
" print a\n" +
"except RuntimeError:\n" +
" a = 20\n" +
"else", doc.get());
}
public void testNotUnusedVariable4() {
doc = new Document("def m1(): \n" +
" result = 10 \n" +
" \n"
+
" while result > 0: \n" +
" result = 0 \n" +
" \n" +
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzeDoc();
printMessages(msgs);
assertEquals(0, msgs.length);
}
public void testCalltips8() throws Exception {
String s0 = "class TestCase(object):\n" +
" def __init__(self, param1, param2):\n" +
" pass\n"
+
" \n" +
"TestCase(param1=10, para%s)";
String s = StringUtils.format(s0, "");
ICompletionProposalHandle[] proposals = requestCompl(s, s.length() - 1, -1, new String[] {});
assertEquals(2, proposals.length);
PyCompletionProposal paramProposal = (PyCompletionProposal) assertContains("param1=", proposals);
paramProposal = (PyCompletionProposal) assertContains("param2=", proposals);
Document document = new Document(s);
paramProposal.apply(document);
assertEquals(StringUtils.format(s0, "m2="), document.get());
}
public void testTryFinallyVersion25() throws Exception {
CodeFoldingVisitor visitor = new CodeFoldingVisitor();
String str = "" +
"try:\n" +
" print 4\n" +
"finally:\n" +
" print 5\n" +
"\n" +
"";
ParseOutput objects = PyParser.reparseDocument(new PyParser.ParserInfo(new Document(str),
IPythonNature.GRAMMAR_PYTHON_VERSION_2_5, null));
SimpleNode root = (SimpleNode) objects.ast;
root.accept(visitor);
Iterator<ASTEntry> iterator = visitor.getIterator();
check((ASTEntryWithChildren) iterator.next(), "TryFinally", 1, 1, 4, 0);
assertTrue(iterator.hasNext() == false);
}
@Override
protected SourceViewer createViewer(Composite parent) {
IDocument document= new Document();
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING, false);
viewer.configure(configuration);
viewer.setEditable(false);
viewer.setDocument(document);
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
new JavaSourcePreviewerUpdater(viewer, configuration, store);
Control control= viewer.getControl();
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
control.setLayoutData(data);
return viewer;
}
public void testFindActualDefinition2() throws Exception {
String str = "" +
"class Test(unittest.TestCase):\n" +
"\n" +
" def testCountCalls(self):\n"
+
" exp_format = '%*.*e' % (exp_format_digits + 8, exp_format_digits, datum)\n"
+
" mantissa, _exponent_str = exp_format.split('e')\n"
+
" mantissa = mantissa.strip().rjust(exp_format_digits + 3)\n" +
"";
IModule mod = SourceModule.createModuleFromDoc(null, new Document(str), nature);
ICompletionCache completionCache = new CompletionCache();
ArrayList<IDefinition> selected = new ArrayList<IDefinition>();
PyRefactoringFindDefinition.findActualDefinition(null, mod, "mantissa.strip", selected, 6, 20, nature,
completionCache);
assertEquals(0, selected.size());
}
public void testNewLine4() {
strategy.setIndentPrefs(new TestIndentPrefs(true, 4));
String str = "" +
"def a():\n" +
" print a" +
"";
final Document doc = new Document(str);
DocCmd docCmd = new DocCmd(doc.getLength() - " print a".length(), 0, "\n");
strategy.customizeDocumentCommand(doc, docCmd);
String expected = "" +
"def a():\n" +
" print a" +
"";
assertEquals(expected, doc.get());
assertEquals("\n", docCmd.text);
}
public void testNotUnusedVariable() {
doc = new Document("def m1(): \n" +
" result = 10 \n" +
" \n" +
" if False: \n"
+
" result = 20\n" +
" \n" +
" print result \n");
analyzer = new OccurrencesAnalyzer();
msgs = analyzeDoc();
printMessages(msgs);
assertEquals(0, msgs.length);
}
@Override
public boolean visit(CopySourceEdit edit) {
try {
if (edit.getTargetEdit() != null) {
org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));
Document doc = new Document(compilationUnit.getSource());
edit.apply(doc, TextEdit.UPDATE_REGIONS);
String content = doc.get(edit.getOffset(), edit.getLength());
if (edit.getSourceModifier() != null) {
content = applySourceModifier(content, edit.getSourceModifier());
}
te.setNewText(content);
converted.add(te);
}
return false;
} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
}
return super.visit(edit);
}
public void testFix2() throws Exception {
start = 6;
end = 13;
type = IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE;
marker = createMarkerStub(start, end, type);
// hard: undefined: testlib
// the result should be testlib.unittest because the token is actually a module. If it was
// not a module, there would be no problems
s = "print testlib.unittest";
ps = new PySelection(new Document(s));
line = s;
offset = s.length();
props = new ArrayList<ICompletionProposalHandle>();
participant.addProps(marker, prefs, line, ps, offset, nature, null, props);
printProps(2, props);
assertContains("Import testlib.unittest", props);
assertContains("Import testlib", props);
}
public void testClassmethod() throws Exception {
String s0 = "class Foo:\n" +
" @classmethod\n" +
" def method1(cls, a, b):\n" +
" pass\n"
+
" \n" +
"Foo.met%s";
String s = StringUtils.format(s0, "");
ICompletionProposalHandle[] proposals = requestCompl(s, s.length(), -1, new String[] {});
assertEquals(1, proposals.length);
PyCompletionProposal p = (PyCompletionProposal) proposals[0];
assertEquals("method1(a, b)", p.getDisplayString());
Document document = new Document(s);
p.apply(document);
assertEquals(StringUtils.format(s0, "hod1(a, b)"), document.get());
}
public void testDictComprehension() {
int initial = GRAMMAR_TO_USE_FOR_PARSING;
try {
GRAMMAR_TO_USE_FOR_PARSING = IPythonNature.GRAMMAR_PYTHON_VERSION_3_5;
doc = new Document("class Bar(object):\n" +
" def __init__(self, row):\n"
+
" self.__dict__.update({'Input.'+k: v for k,v in row.items()})\n" +
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzeDoc();
printMessages(msgs, 0);
} finally {
GRAMMAR_TO_USE_FOR_PARSING = initial;
}
}
public void testScopes10() {
doc = new Document("class C:\n" +
" def m1(self):\n" +
" print m2\n" + //should give error, as we are inside the method (and not in the class scope)
" def m2(self):\n" +
" print m1\n" + //should give error, as we are inside the method (and not in the class scope)
"\n" +
"\n" +
"\n" +
"\n" +
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzeDoc();
printMessages(msgs, 2);
}
public void testIfElifElseMarks() throws Exception {
setOptionTrue(PyDevCodeFoldingPrefPage.FOLD_IF);
Document doc = new Document("" +
"if a:\n" +
" print 1\n" +
"elif b:\n" +
" print 2\n" +
"else:\n"
+
" print 3\n" +
"\n");
List<FoldingEntry> marks = getMarks(doc);
Iterator<FoldingEntry> it = marks.iterator();
assertEquals(new FoldingEntry(FoldingEntry.TYPE_STATEMENT, 0, 2, null), it.next()); //end line not ok...
assertEquals(new FoldingEntry(FoldingEntry.TYPE_STATEMENT, 2, 4, null), it.next());
assertEquals(new FoldingEntry(FoldingEntry.TYPE_STATEMENT, 4, 6, null), it.next());
assertTrue(it.hasNext() == false);
}
public void testCommentsIndent2() {
strategy.setIndentPrefs(new TestIndentPrefs(true, 4));
//test not indent more
doc = " # comment:";
docCmd = new DocCmd(doc.length(), 0, "\n");
strategy.customizeDocumentCommand(new Document(doc), docCmd);
expected = "\n" +
" ";
assertEquals(expected, docCmd.text);
//test indent more
doc = " if False:";
docCmd = new DocCmd(doc.length(), 0, "\n");
strategy.customizeDocumentCommand(new Document(doc), docCmd);
expected = "\n" +
" ";
assertEquals(expected, docCmd.text);
}
public void testPep8ImportOrganizer2() throws Exception {
String s = ""
+ "import sys #comment\n"
+ "sys.path.insert(0, os.path.realpath(os.path.abspath('..')))\n"
+ "\n"
+ "import os\n"
+ "import pydevd_reload\n"
+ "import tempfile\n"
+ "import unittest\n"
+ "";
String result = ""
+ "import os\n"
+ "import pydevd_reload\n"
+ "import sys #comment\n"
+ "import tempfile\n"
+ "import unittest\n"
+ "\n"
+ "\n"
+ "sys.path.insert(0, os.path.realpath(os.path.abspath('..')))\n\n"
+ "";
Document doc = new Document(s);
PyOrganizeImports.performPep8ArrangeImports(doc, "\n", " ", true, edit);
assertEquals(result, doc.get());
}
protected SourceViewer createViewer(Composite parent) {
IDocument document= new Document();
JavaScriptTextTools tools= JSDTTypeScriptUIPlugin.getDefault().getJavaTextTools();
tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
IPreferenceStore store= JSDTTypeScriptUIPlugin.getDefault().getCombinedPreferenceStore();
SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false);
viewer.configure(configuration);
viewer.setEditable(false);
viewer.setDocument(document);
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
new TypeScriptSourcePreviewerUpdater(viewer, configuration, store);
Control control= viewer.getControl();
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
control.setLayoutData(data);
return viewer;
}
public void testFix5() throws Exception {
start = 0;
end = 0;
type = IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE;
marker = createMarkerStub(start, end, type);
s = " "; //only one space in doc
ps = new PySelection(new Document(s));
line = s;
offset = s.length();
participant.addProps(marker, prefs, line, ps, offset, nature, null, props);
printProps(1, props);
assertEquals("UndefinedVariable", props.get(0).getDisplayString());
props.get(0).apply(ps.getDoc());
assertEquals(" #@UndefinedVariable", ps.getDoc().get());
}
public void testTryFinally() throws Exception {
setAllOptions(true);
Document doc = new Document("" +
"try:\n" +
" pass\n" +
"finally:\n" +
" pass" +
"\n");
List<FoldingEntry> marks = getMarks(doc);
Iterator<FoldingEntry> it = marks.iterator();
assertEquals(new FoldingEntry(FoldingEntry.TYPE_FINALLY, 0, 2, null), it.next());
assertEquals(new FoldingEntry(FoldingEntry.TYPE_FINALLY, 2, 4, null), it.next());
assertTrue(it.hasNext() == false);
}
private int getLexemLen(Document doc, int offs) throws Exception {
char ch, beg = Character.toLowerCase(doc.getChar(offs));
boolean isName = isAlpha(beg);
boolean isNum = isDigit(beg);
boolean isString = beg == '"' || beg == '\'';
if (!isString && !isName && !isNum) {
return 1;
}
int len = 1;
for (; (ch = getch(doc, offs, len)) != 0; ++len) {
ch = getch(doc, offs, len);
if (isString && ch == beg) {
break;
} else if (isName && !isAlpha(ch) && !isDigit(ch)) {
break;
} else if (isNum && !isDigit(ch)) {
break;
}
}
return len;
}
public void testSurround3() throws Exception {
AssistSurroundWith assistSurroundWith = new AssistSurroundWith();
IDocument doc = new Document("" +
"def m1():\n" +
"\n" +
"#c\n" +
"# a = 10\n" +
"\n" +
"\n");
PySelection ps = new PySelection(doc, 1, 0, 14);
int offset = ps.getAbsoluteCursorOffset();
List<ICompletionProposalHandle> props = assistSurroundWith.getProps(ps, null, null, null, null, offset);
props.get(0).apply(doc);
TestCaseUtils.assertContentsEqual("" +
"def m1():\n" +
"try:\n" +
" \n" +
" #c\n" +
" # a = 10\n"
+
"except${cursor}:\n" +
" raise\n" +
"\n" +
"\n" +
"", doc.get());
}
public void testFix5() throws Exception {
start = 6;
end = 17;
type = IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE;
marker = createMarkerStub(start, end, type);
//try 3
s = "print AnotherTest";
ps = new PySelection(new Document(s));
line = s;
offset = s.length();
props = new ArrayList<ICompletionProposalHandle>();
participant.addProps(marker, prefs, line, ps, offset, nature, null, props);
printProps(1, props);
assertContains("Import AnotherTest (testlib.unittest.anothertest)", props);
}
public void testAnnotationMarksAsUsed() {
int initial = GRAMMAR_TO_USE_FOR_PARSING;
try {
GRAMMAR_TO_USE_FOR_PARSING = IPythonNature.GRAMMAR_PYTHON_VERSION_3_5;
doc = new Document("\n" +
"def method(*, t:threading=None):\n"
+ " print(t)\n" +
"");
analyzer = new OccurrencesAnalyzer();
msgs = analyzeDoc();
printMessages(msgs, 1);
} finally {
GRAMMAR_TO_USE_FOR_PARSING = initial;
}
}
public void testPartitionCodeReaderKeepingPositions() throws Exception {
PartitionCodeReader reader = new PartitionCodeReader(IDocument.DEFAULT_CONTENT_TYPE);
Document document = new Document("abcde");
String category = setupDocument(document);
document.addPosition(category, new TypedPosition(1, 1, "cat1")); //skip b
document.addPosition(category, new TypedPosition(3, 1, "cat1")); //skip d
reader.configureForwardReader(document, 3, document.getLength(), true);
FastStringBuffer buf = new FastStringBuffer(document.getLength());
readAll(reader, buf);
assertEquals("e", buf.toString());
reader.configureForwardReaderKeepingPositions(2, document.getLength());
buf.clear();
readAll(reader, buf);
assertEquals("ce", buf.toString());
reader.configureForwardReaderKeepingPositions(0, document.getLength());
buf.clear();
readAll(reader, buf);
assertEquals("ace", buf.toString());
}
public void testParameterAnalysis24() throws IOException {
doc = new Document("from extendable.parameters_check import Foo\n"
+ //class with __init__ == __init__(self, a, b)
"\n" +
"class X(object):\n" +
"\n" +
" def __init__(self, a, b):\n"
+
" Foo.__init__(self, a, b)\n" +
"\n" +
"\n" +
"\n" +
"class B(object):\n" +
"\n"
+
" def __init__(self, a, b, c):\n" +
" pass\n" +
"\n" +
" @classmethod\n"
+
" def Create(cls):\n" +
" return B(1, 2, 3)\n");
checkNoError();
}
public void testQtInit() throws Exception {
if (SharedCorePlugin.skipKnownFailures()) {
return;
}
if (TestDependent.PYTHON_QT4_PACKAGES != null) {
doc = new Document("import PyQt4.QtGui\n" +
"print PyQt4.QtGui.QWidget.__init__\n" +
"\n" +
"\n");
analyzer = new OccurrencesAnalyzer();
msgs = analyzeDoc();
printMessages(msgs, 0);
}
}