/** * Returns the indentation of the line <code>line</code> in <code>document</code>. The returned * string may contain pairs of leading slashes that are considered part of the indentation. The * space before the asterisk in a javadoc-like comment is not considered part of the indentation. * * @param document the document * @param line the line * @return the indentation of <code>line</code> in <code>document</code> * @throws BadLocationException if the document is changed concurrently */ private static String getCurrentIndent(Document document, int line) throws BadLocationException { IRegion region = document.getLineInformation(line); int from = region.getOffset(); int endOffset = region.getOffset() + region.getLength(); // go behind line comments int to = from; while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT)) to += 2; while (to < endOffset) { char ch = document.getChar(to); if (!Character.isWhitespace(ch)) break; to++; } // don't count the space before javadoc like, asterisk-style comment lines if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { // $NON-NLS-1$ String type = TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, to, true); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) to--; } return document.get(from, to - from); }
private void printProblemXML(IMarker marker, Document doc, StringBuilder sb) throws JavaModelException, CoreException { Object[] attribs = marker.getAttributes(MARKER_ATTRIBUTES); String problemType; int lineNumber = 0; int startOfLine = 0; int lineLength = 0; String lineOfCode = ""; try { lineNumber = Integer.parseInt(attribs[1].toString()) - 1; startOfLine = doc.getLineOffset(lineNumber); lineLength = doc.getLineLength(lineNumber); lineOfCode = doc.get(startOfLine, lineLength); } catch (NumberFormatException e) { e.printStackTrace(Constants.writer); } catch (BadLocationException e) { e.printStackTrace(Constants.writer); } if (attribs[0].equals(IMarker.SEVERITY_ERROR)) problemType = "ERROR"; else if (attribs[0].equals(IMarker.SEVERITY_WARNING)) problemType = "WARNING"; else problemType = "INFORMATION"; sb.append("<" + problemType + ">"); sb.append("<LINE>" + attribs[1] + "</LINE>"); sb.append("<MESSAGE>" + attribs[2] + "</MESSAGE>"); sb.append("<CODELINE>" + lineOfCode.trim() + "</CODELINE>"); sb.append("</" + problemType + ">"); }
/** * Indents line <code>line</code> in <code>document</code> with <code>indent</code>. Leaves * leading comment signs alone. * * @param document the document * @param line the line * @param indent the indentation to insert * @param tabLength the length of a tab * @throws BadLocationException on concurrent document modification */ private void addIndent(Document document, int line, CharSequence indent, int tabLength) throws BadLocationException { IRegion region = document.getLineInformation(line); int insert = region.getOffset(); int endOffset = region.getOffset() + region.getLength(); // Compute insert after all leading line comment markers int newInsert = insert; while (newInsert < endOffset - 2 && document.get(newInsert, 2).equals(LINE_COMMENT)) newInsert += 2; // Heuristic to check whether it is commented code or just a comment if (newInsert > insert) { int whitespaceCount = 0; int i = newInsert; while (i < endOffset - 1) { char ch = document.get(i, 1).charAt(0); if (!Character.isWhitespace(ch)) break; whitespaceCount = whitespaceCount + computeVisualLength(ch, tabLength); i++; } if (whitespaceCount != 0 && whitespaceCount >= CodeFormatterUtil.getIndentWidth(fProject)) insert = newInsert; } // Insert indent document.replace(insert, 0, indent.toString()); }
/** * Creates the text change for this proposal. This method is only called once and only when no * text change has been passed in {@link #TUCorrectionProposal(String, ITranslationUnit, * TextChange, int, Image)}. * * @return returns the created text change. * @throws CoreException thrown if the creation of the text change failed. */ protected TextChange createTextChange() throws CoreException { ITranslationUnit tu = getTranslationUnit(); String name = getName(); TextChange change; if (!tu.getResource().exists()) { String source; try { source = tu.getSource(); } catch (CModelException e) { CUIPlugin.log(e); source = ""; // $NON-NLS-1$ } Document document = new Document(source); document.setInitialLineDelimiter(StubUtility.getLineDelimiterUsed(tu)); change = new DocumentChange(name, document); } else { CTextFileChange tuChange = new CTextFileChange(name, tu); tuChange.setSaveMode(TextFileChange.LEAVE_DIRTY); change = tuChange; } TextEdit rootEdit = new MultiTextEdit(); change.setEdit(rootEdit); // Initialize text change. IDocument document = change.getCurrentDocument(new NullProgressMonitor()); addEdits(document, rootEdit); return change; }
private String getLineContent(Document document, int line) { try { int lineOffset = document.getLineOffset(line - 1); int lineLength = document.getLineLength(line - 1); return document.get(lineOffset, lineLength); } catch (BadLocationException e) { return null; } }
/** Return this {@link JavaSource} file as a String */ @Override public String toString() { Document document = new Document(this.document.get()); try { TextEdit edit = unit.rewrite(document, null); edit.apply(document); } catch (Exception e) { throw new ParserException("Could not modify source: " + unit.toString(), e); } return Formatter.format(document.get()); }
/** * It is OK to apply more than one insert {@link Edit} with the same offset. * * <p>For example Quick Fix "Implement Missing Overrides" inserts several method declarations. */ public void test_toLTK_SourceChange_twoInserts() throws Exception { Source source = createTestFileSource(); // fill SourceChange SourceChange sourceChange = new SourceChange("My change", source); sourceChange.addEdit(new Edit(2, 0, "a")); sourceChange.addEdit(new Edit(2, 0, "b")); // toLTK TextFileChange ltkChange = ServiceUtils.toLTK(sourceChange); TextEdit textEdit = ltkChange.getEdit(); // apply Document document = new Document("01234"); textEdit.apply(document); assertEquals("01ab234", document.get()); }
public void testUncommentBlock() throws Exception { doc = new Document("#a\n" + "#b"); ps = new PySelection(doc, 0, 0, 0); new PyRemoveBlockComment().perform(ps); expected = "a\n" + "b"; assertEquals(expected, doc.get()); doc = new Document("#----\n" + "#a\n" + "#b\n" + "#----"); ps = new PySelection(doc, 0, 0, 0); new PyRemoveBlockComment().perform(ps); expected = "a\n" + "b\n"; assertEquals(expected, doc.get()); }
public void reparseAll() { SwtMateTextLocation startLocation = new SwtMateTextLocation(0, this); SwtMateTextLocation endLocation = new SwtMateTextLocation(0 + document.getLength(), this); if (this.mateText.parser.enabled) { this.mateText.parser.changes.add(startLocation.getLine(), endLocation.getLine()); this.mateText.parser.processChanges(); } }
public int getLineLength(int line) { try { int startOffset = document.getLineOffset(line); int endOffset; if (line + 1 < getLineCount()) { endOffset = document.getLineOffset(line + 1); } else { endOffset = document.getLength(); } return endOffset - startOffset; } catch (BadLocationException e) { System.out.printf("*** Warning BadLocationException"); e.printStackTrace(); return -1; } }
public void test2() throws Exception { doc = new Document("#---- aa\n" + "#---- b\n" + "#---- c"); ps = new PySelection(doc, 0, 0, 0); new PyRemoveBlockComment().perform(ps); expected = "aa\n" + "b\n" + "c"; assertEquals(expected, doc.get()); }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((body == null) ? 0 : body.hashCode()); result = prime * result + ((document == null) ? 0 : document.hashCode()); result = prime * result + ((enclosingType == null) ? 0 : enclosingType.hashCode()); result = prime * result + ((unit == null) ? 0 : unit.hashCode()); return result; }
private void textModified(String text) { fRefactoring.setMethodName(text); RefactoringStatus status = validatePage(true); if (!status.hasFatalError()) { updatePreview(text); } else { fSignaturePreviewDocument.set(""); // $NON-NLS-1$ } setPageComplete(status); }
@Test public void indentFromPreviousLineShouldBeAdded() { document.set(" abc"); command.offset = 7; command.text = "\n"; strategy.customizeDocumentCommand(document, command); assertThat(command.text).isEqualTo("\n "); }
@Test public void indentShouldNotBeAdded_whenPreviousLineDoesNotStartFromIndent() { document.set("xyz"); command.offset = 3; command.text = "\n"; strategy.customizeDocumentCommand(document, command); assertThat(command.text).isEqualTo("\n"); }
@Test public void commandShouldNotBeChanged_whenItIsNotLineBreak() { document.set("x"); command.offset = 1; command.text = "q"; strategy.customizeDocumentCommand(document, command); assertThat(command.text).isEqualTo("q"); }
/** Determine the value type for a give propertyName. */ protected Type getValueType(String propertyName) { try { PropertyInfo prop = getIndex().get(propertyName); if (prop != null) { return TypeParser.parse(prop.getType()); } else { prop = findLongestValidProperty(getIndex(), propertyName); if (prop != null) { Document doc = new Document(propertyName); PropertyNavigator navigator = new PropertyNavigator(doc, null, typeUtil, new Region(0, doc.getLength())); return navigator.navigate(prop.getId().length(), TypeParser.parse(prop.getType())); } } } catch (Exception e) { BootActivator.log(e); } return null; }
public void run(IStructuredSelection selection) { final ModuleCollector collector = new ModuleCollector(); // Add by Oliver. Fill the source model into collector.modules. initSelectedVjoType(selection, collector); if (!collector.modules.isEmpty()) { for (Iterator i = collector.modules.iterator(); i.hasNext(); ) { final ISourceModule module = (ISourceModule) i.next(); final IResource resource = module.getResource(); if (resource != null && resource.getType() == IResource.FILE && resource.exists()) { final IScriptProject project = module.getScriptProject(); final IScriptFormatterFactory formatterFactory = ScriptFormatterManager.getSelected(project); if (formatterFactory != null) { try { final String source = module.getSource(); final Document document = new Document(source); final String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document); final Map preferences = formatterFactory.retrievePreferences(new PreferencesLookupDelegate(project)); final IScriptFormatter formatter = formatterFactory.createFormatter(lineDelimiter, preferences); final TextEdit edit = formatter.format(source, 0, source.length(), 0); if (edit != null) { edit.apply(document); final String newSource = document.get(); if (!source.equals(newSource)) { module.becomeWorkingCopy(null, null); module.getBuffer().setContents(newSource); module.commitWorkingCopy(true, null); } } } catch (Exception e) { DLTKUIPlugin.log(e); break; } } } } } }
@Override protected void fireDocumentChanged(final DocumentEvent event) { if (reparseInSameThread) { // short documents can be reparsed in the same thread as this does not // affect performance too much reparse(); } else { reparseInSeparateThread(); } super.fireDocumentChanged(event); }
/** * 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$ }
@Override protected void doFormatPreview() { if (fSnippets.isEmpty()) { fPreviewDocument.set(""); // $NON-NLS-1$ return; } // This delimiter looks best for invisible characters final String delimiter = "\n"; // $NON-NLS-1$ final StringBuilder buffer = new StringBuilder(); for (PreviewSnippet snippet : fSnippets) { String formattedSource; try { TextEdit edit = CodeFormatterUtil.format(snippet.kind, snippet.source, 0, delimiter, fWorkingValues); if (edit == null) { formattedSource = snippet.source; } else { Document document = new Document(snippet.source); edit.apply(document, TextEdit.NONE); formattedSource = document.get(); } } catch (Exception e) { final IStatus status = new Status( IStatus.ERROR, CUIPlugin.getPluginId(), ICStatusConstants.INTERNAL_ERROR, FormatterMessages.CPreview_formatter_exception, e); CUIPlugin.log(status); continue; } buffer.append(delimiter); buffer.append(formattedSource); buffer.append(delimiter); buffer.append(delimiter); } fPreviewDocument.set(buffer.toString()); }
@Test public void useCase_ex1() { when(stepLocator.findFirstStep(Mockito.anyString())) .thenAnswer( new Answer<StepCandidate>() { @Override public StepCandidate answer(InvocationOnMock invocation) throws Throwable { System.out.println("StepScannerStyledTest.useCase_ex1(" + invocation + ")"); return candidate; } }); String[] expected = { // "step_keyword ~ offset: 0, length: 6", // "step_default ~ offset: 6, length: 18", // "step_parameter_value ~ offset: 24, length: 6", // "step_default ~ offset: 30, length: 33", // "step_example_table_separator ~ offset: 63, length: 1", // "step_example_table_cell ~ offset: 64, length: 3", // "step_example_table_separator ~ offset: 67, length: 1", // "step_example_table_cell ~ offset: 68, length: 5", // "step_example_table_separator ~ offset: 73, length: 1", // "step_default ~ offset: 74, length: 1", // "comment ~ offset: 75, length: 17", // "step_example_table_separator ~ offset: 92, length: 1", // "step_example_table_cell ~ offset: 93, length: 5", // "step_example_table_separator ~ offset: 98, length: 1", // "step_example_table_cell ~ offset: 99, length: 6", // "step_example_table_separator ~ offset: 105, length: 1", // "step_default ~ offset: 106, length: 1", // "step_example_table_separator ~ offset: 107, length: 1", // "step_example_table_cell ~ offset: 108, length: 8", // "step_example_table_separator ~ offset: 116, length: 1", // "step_example_table_cell ~ offset: 117, length: 6", // "step_example_table_separator ~ offset: 123, length: 1", // "step_default ~ offset: 124, length: 1" // }; int index = 0; scanner.setRange(document, 0, document.getLength()); IToken token = scanner.nextToken(); while (!token.isEOF()) { String actual = (token.getData() + " ~ offset: " + scanner.getTokenOffset() + ", length: " + scanner.getTokenLength()); assertThat(actual, equalTo(expected[index++])); token = scanner.nextToken(); } assertThat(index, equalTo(expected.length)); }
private void updateSignaturePreview() { try { int top = fSignaturePreview.getTextWidget().getTopPixel(); fSignaturePreviewDocument.set(getChangeMethodSignatureProcessor().getNewMethodSignature()); fSignaturePreview.getTextWidget().setTopPixel(top); } catch (JavaModelException e) { ExceptionHandler.handle( e, RefactoringMessages.ChangeSignatureRefactoring_modify_Parameters, RefactoringMessages.ChangeSignatureInputPage_exception); } }
public void testApply$() throws Exception { // Test a regression in apply String source = "void foo(); Int blah"; ToolCompletionProposal tcp = new ToolCompletionProposal( source.indexOf("Int"), 3, "interface", "label", CompletionProposalKind.values()[0], new ElementAttributes(null), "moduleName", null); LangCompletionProposal completionProposal = new LangCompletionProposal(tcp, null, null); Document document = new Document(source); completionProposal.doApply(document, true); assertEquals(document.get(), "void foo(); interface blah"); }
@Override protected void fireDocumentAboutToBeChanged(final DocumentEvent event) { createParserIfNeeded(); reparseInSameThread = getNumberOfLines() < LIMIT; if (!reparseInSameThread && hasNewestVersion.getAndSet(false)) { try { // it will be acquired only by the first event parsingSemaphore.acquire(); } catch (final InterruptedException e) { throw new IllegalStateException("Document reparsing interrupted!", e); } } super.fireDocumentAboutToBeChanged(event); }
public SwtMateDocument(MateText mateText) { this.mateText = mateText; this.document = (Document) mateText.getDocument(); for (IPositionUpdater u : document.getPositionUpdaters()) { document.removePositionUpdater(u); } document.addPositionCategory("scopes"); document.addPositionUpdater( new SwtScopePositionUpdater("scopes", SwtScopePositionUpdater.RIGHT_GRAVITY)); document.addPositionCategory("lefts"); document.addPositionUpdater( new SwtScopePositionUpdater("lefts", SwtScopePositionUpdater.LEFT_GRAVITY)); document.addPositionCategory("rights"); document.addPositionUpdater( new SwtScopePositionUpdater("rights", SwtScopePositionUpdater.RIGHT_GRAVITY)); }
/** * Installs a java partitioner with <code>document</code>. * * @param document the document */ private static void installJavaStuff(Document document) { String[] types = new String[] { IJavaPartitions.JAVA_DOC, IJavaPartitions.JAVA_MULTI_LINE_COMMENT, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT, IJavaPartitions.JAVA_STRING, IJavaPartitions.JAVA_CHARACTER, IDocument.DEFAULT_CONTENT_TYPE, SqlJSourceScanner.SQLJ_source }; FastPartitioner partitioner = new FastPartitioner(new FastJavaPartitionScanner(), types); partitioner.connect(document); document.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner); }
private void updatePreview(String text) { if (fSignaturePreview == null) { return; } if (text.length() == 0) { text = "someMethodName"; // $NON-NLS-1$ } int top = fSignaturePreview.getTextWidget().getTopPixel(); String signature; try { signature = fRefactoring.getSignature(text); } catch (IllegalArgumentException e) { signature = ""; // $NON-NLS-1$ } fSignaturePreviewDocument.set(signature); fSignaturePreview.getTextWidget().setTopPixel(top); }
public void testBlock() throws Exception { Document doc = null; FormatStd std = new FormatStd(); doc = new Document("cc"); new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals("" + "#---------\r\n" + "# cc\r\n" + "#---------", doc.get()); doc = new Document("\t cc"); new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals("" + "\t #----\r\n" + "\t # cc\r\n" + "\t #----", doc.get()); doc = new Document("class Foo(object):"); new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals( "" + "#---------\r\n" + "# Foo\r\n" + "#---------\r\n" + "class Foo(object):", doc.get()); doc = new Document("class Information( UserDict.UserDict, IInformation ):"); new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals( "" + "#---------\r\n" + "# Information\r\n" + "#---------\r\n" + "class Information( UserDict.UserDict, IInformation ):", doc.get()); doc = new Document("def Information( (UserDict, IInformation) ):"); new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals( "" + "#---------\r\n" + "# Information\r\n" + "#---------\r\n" + "def Information( (UserDict, IInformation) ):", doc.get()); // without class behavior doc = new Document("class Foo(object):"); new PyAddBlockComment(std, 10, true, false, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals( "" + "#---------\r\n" + "# class Foo(object):\r\n" + "#---------" + "", doc.get()); // aligned class doc = new Document(" class Foo(object):"); new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0)); PySelectionTest.checkStrEquals( "" + " #-----\r\n" + " # Foo\r\n" + " #-----\r\n" + " class Foo(object):" + "", doc.get()); }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractJavaSource<?> other = (AbstractJavaSource<?>) obj; if (body == null) { if (other.body != null) return false; } else if (!body.equals(other.body)) return false; if (document == null) { if (other.document != null) return false; } else if (!document.equals(other.document)) return false; if (enclosingType == null) { if (other.enclosingType != null) return false; } else if (!enclosingType.equals(other.enclosingType)) return false; if (unit == null) { if (other.unit != null) return false; } else if (!unit.equals(other.unit)) return false; return true; }