org.eclipse.jface.text.Document Java Examples

The following examples show how to use org.eclipse.jface.text.Document. 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: OccurrencesAnalyzerTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);

}
 
Example #2
Source File: PartitionCodeReaderTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #3
Source File: FindDefinitionModelVisitorTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: PyAutoIndentStrategyTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());

}
 
Example #5
Source File: OccurrencesAnalyzerTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);

}
 
Example #6
Source File: OccurrencesAnalyzer2Test.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: PyAutoIndentStrategyTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: AssistSurroundWithTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #9
Source File: UndefinedVariableFixParticipantTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);

}
 
Example #10
Source File: ModuleTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #11
Source File: PythonCompletionCalltipsTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #12
Source File: JavaAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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$
}
 
Example #13
Source File: OccurrencesAnalyzerTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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;
    }
}
 
Example #14
Source File: CodeFoldingVisitorTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #15
Source File: CodeFoldingSetterTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #16
Source File: JavaTemplatePreferencePage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #17
Source File: IgnoreErrorFixParticipantTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #18
Source File: TypeScriptTemplatePreferencePage.java    From typescript.java with MIT License 6 votes vote down vote up
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;
}
 
Example #19
Source File: FindActualDefinitionTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #20
Source File: PyOrganizeImportsTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #21
Source File: PyAutoIndentStrategyTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);

}
 
Example #22
Source File: OccurrencesAnalyzerTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);

}
 
Example #23
Source File: PyAutoIndentStrategyTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #24
Source File: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #25
Source File: UndefinedVariableFixParticipantTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #26
Source File: PythonCompletionWithoutBuiltinsTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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());
}
 
Example #27
Source File: CodeFoldingSetterTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #28
Source File: OccurrencesAnalyzerTest.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
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;
    }
}
 
Example #29
Source File: MarkerMaker.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #30
Source File: PythonCompletionWithoutBuiltinsTest.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public void testSubClassConstructorParams() throws Exception {
    String s;
    String original = "" +
            "class Foo:\n" +
            "    def __init__(self, a, b):pass\n\n" +
            "    def m1(self):pass\n\n" +
            "class Bar(Foo):\n" +
            "    pass\n\n"
            +
            "Bar(%s)" + //completion inside the empty parenthesis should: add the parameters in link mode (a, b) and let the calltip there.
            "";
    s = StringUtils.format(original, "");

    ICompletionProposalHandle[] proposals = requestCompl(s, s.length() - 1, -1, new String[] {});
    assertEquals(1, proposals.length);
    ICompletionProposalHandle prop = proposals[0];
    assertEquals("Bar(a, b)", prop.getDisplayString());

    IPyCalltipsContextInformation contextInformation = (IPyCalltipsContextInformation) prop.getContextInformation();
    assertEquals("a, b", contextInformation.getContextDisplayString());
    assertEquals("a, b", contextInformation.getInformationDisplayString());

    Document doc = new Document(s);
    prop.apply(doc);
    String expected = StringUtils.format(original, "a, b");
    assertEquals(expected, doc.get());
}