org.eclipse.jface.text.IDocument Java Examples
The following examples show how to use
org.eclipse.jface.text.IDocument.
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: GetterSetterCompletionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
/** * @param document * @param offset * @param importRewrite * @param completionSnippetsSupported * @param addComments * @return * @throws CoreException * @throws BadLocationException */ public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported, boolean addComments) throws CoreException, BadLocationException { int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic); String stub; if (fIsGetter) { String getterName= GetterSetterUtil.getGetterName(fField, null); stub = GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags); } else { String setterName= GetterSetterUtil.getSetterName(fField, null); stub = GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags); } // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject()); if (replacement.endsWith(lineDelim)) { replacement = replacement.substring(0, replacement.length() - lineDelim.length()); } return replacement; }
Example #2
Source File: DocumentUtils.java From http4e with Apache License 2.0 | 6 votes |
public static IDocument createDocument1(){ IDocument doc = new Document(){ public String getDefaultLineDelimiter(){ return String.valueOf(AssistConstants.LINE_DELIM_NL) /*super.getDefaultLineDelimiter()*/; } }; IDocumentPartitioner partitioner = new DefaultPartitioner( new HPartitionScanner(), new String[] { HPartitionScanner.COMMENT, HPartitionScanner.PROPERTY_VALUE}); partitioner.connect(doc); doc.setDocumentPartitioner(partitioner); return doc; }
Example #3
Source File: JavaParameterListValidator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * @see IContextInformationValidator#isContextInformationValid(int) */ public boolean isContextInformationValid(int position) { try { if (position < fPosition) return false; IDocument document= fViewer.getDocument(); IRegion line= document.getLineInformationOfOffset(fPosition); if (position < line.getOffset() || position >= document.getLength()) return false; return getCharCount(document, fPosition, position, "(<", ")>", false) >= 0; //$NON-NLS-1$ //$NON-NLS-2$ } catch (BadLocationException x) { return false; } }
Example #4
Source File: TypeScriptCompletionProposal.java From typescript.java with MIT License | 6 votes |
private String computeReplacementString(IDocument document, int offset) { try { if (super.isFunction()) { List<CompletionEntryDetails> entryDetails = super.getEntryDetails(); if (entryDetails != null && entryDetails.size() > 0) { // It's a function // compute replacement string String indentation = getIndentation(document, offset); arguments = new Arguments(); StringBuilder replacement = new StringBuilder(super.getName()); replacement.append(LPAREN); setCursorPosition(replacement.length()); computeReplacementString(entryDetails.get(0).getDisplayParts(), replacement, arguments, indentation, 1, true); replacement.append(RPAREN); return replacement.toString(); } } } catch (TypeScriptException e) { } return getReplacementString(); }
Example #5
Source File: XMLConfiguration.java From http4e with Apache License 2.0 | 6 votes |
public IContentFormatter getContentFormatter( ISourceViewer sourceViewer){ ContentFormatter formatter = new ContentFormatter(); XMLFormattingStrategy formattingStrategy = new XMLFormattingStrategy(); DefaultFormattingStrategy defaultStrategy = new DefaultFormattingStrategy(); TextFormattingStrategy textStrategy = new TextFormattingStrategy(); DocTypeFormattingStrategy doctypeStrategy = new DocTypeFormattingStrategy(); PIFormattingStrategy piStrategy = new PIFormattingStrategy(); formatter.setFormattingStrategy(defaultStrategy, IDocument.DEFAULT_CONTENT_TYPE); formatter.setFormattingStrategy(textStrategy, XMLPartitionScanner.XML_TEXT); formatter.setFormattingStrategy(doctypeStrategy, XMLPartitionScanner.XML_DOCTYPE); formatter.setFormattingStrategy(piStrategy, XMLPartitionScanner.XML_PI); formatter.setFormattingStrategy(textStrategy, XMLPartitionScanner.XML_CDATA); formatter.setFormattingStrategy(formattingStrategy, XMLPartitionScanner.XML_START_TAG); formatter.setFormattingStrategy(formattingStrategy, XMLPartitionScanner.XML_END_TAG); return formatter; }
Example #6
Source File: ScriptEditor.java From birt with Eclipse Public License 1.0 | 6 votes |
public String getScript( ) { IDocumentProvider provider = getDocumentProvider( ); String script = ""; //$NON-NLS-1$ if ( provider != null ) { IDocument document = provider.getDocument( getEditorInput( ) ); if ( document != null ) { script = document.get( ); } } return script; }
Example #7
Source File: TLAPartitionScanner.java From tlaplus with MIT License | 6 votes |
public void setRange(IDocument document, int offset, int length) { fScanner.setRange(document, offset, length); fTokenOffset = offset; fTokenLength = 0; fPrefixLength = 0; fCommentDepth = 0; fLast = NONE; fState = TLA; fDocument = document ; // added for PlusCal, probably unnecessary fpcalMode = TLAFastPartitioner.BEFORE_PCAL ; // " outputEndPcalComment = false ; // " // emulate TLAPartitionScanner if (fEmulate) { fTLAOffset = -1; fTLALength = 0; } }
Example #8
Source File: N4JSHyperlinkDetector.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * Method copied from super class with only a minor change: call to "readOnly" changed to "tryReadOnly". */ @Override public IHyperlink[] detectHyperlinks(final ITextViewer textViewer, final IRegion region, final boolean canShowMultipleHyperlinks) { final IDocument xtextDocument = textViewer.getDocument(); if (!(xtextDocument instanceof N4JSDocument)) { return super.detectHyperlinks(textViewer, region, canShowMultipleHyperlinks); } final IHyperlinkHelper helper = getHelper(); return ((N4JSDocument) xtextDocument).tryReadOnly(new IUnitOfWork<IHyperlink[], XtextResource>() { @Override public IHyperlink[] exec(XtextResource resource) throws Exception { resource = tryConvertToFileResource(resource); if (resource == null) { return null; } if (helper instanceof ISourceViewerAware && textViewer instanceof ISourceViewer) { ((ISourceViewerAware) helper).setSourceViewer((ISourceViewer) textViewer); } return helper.createHyperlinksByOffset(resource, region.getOffset(), canShowMultipleHyperlinks); } }, (IHyperlink[]) null); }
Example #9
Source File: ModulesManagerWithBuild.java From Pydev with Eclipse Public License 1.0 | 6 votes |
public void rebuildModule(File f, ICallback0<IDocument> doc, final IProject project, IProgressMonitor monitor, IPythonNature nature) { final String m = pythonPathHelper.resolveModule(FileUtils.getFileAbsolutePath(f), false, project); if (m != null) { addModule(new ModulesKey(m, f)); } else if (f != null) { //ok, remove the module that has a key with this file, as it can no longer be resolved synchronized (modulesKeysLock) { Set<ModulesKey> toRemove = new HashSet<ModulesKey>(); for (Iterator<ModulesKey> iter = modulesKeys.keySet().iterator(); iter.hasNext();) { ModulesKey key = iter.next(); if (key.file != null && key.file.equals(f)) { toRemove.add(key); } } removeThem(toRemove); } } }
Example #10
Source File: DelegateCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Performs the actual rewriting and adds an edit to the ASTRewrite set with * {@link #setSourceRewrite(CompilationUnitRewrite)}. * * @throws JavaModelException */ public void createEdit() throws JavaModelException { try { IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents()); TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true)); edit.apply(document, TextEdit.UPDATE_REGIONS); String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()), fPreferences.tabWidth, fPreferences.indentWidth, false); ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType()); CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE); ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty()); if (fCopy) if (fInsertBefore) bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription); else bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription); else bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription); } catch (BadLocationException e) { JavaPlugin.log(e); } }
Example #11
Source File: SpellChecker.java From texlipse with Eclipse Public License 1.0 | 6 votes |
/** * Check spelling of the entire document. * * @param doc the document * @param file */ private void checkDocumentSpelling(IDocument doc, IFile file, IProgressMonitor monitor) { deleteOldProposals(file); //doc.addDocumentListener(instance); try { int num = doc.getNumberOfLines(); monitor.beginTask("Check spelling", num); for (int i = 0; i < num; i++) { if (monitor.isCanceled()) break; int offset = doc.getLineOffset(i); int length = doc.getLineLength(i); String line = doc.get(offset, length); checkLineSpelling(line, offset, i+1, file); monitor.worked(1); } } catch (BadLocationException e) { TexlipsePlugin.log("Checking spelling on a line", e); } stopProgram(); }
Example #12
Source File: PartEventListener.java From scava with Eclipse Public License 2.0 | 6 votes |
private void subscribeDocumentEventListener(IWorkbenchPartReference partRef) { IWorkbenchPart part = partRef.getPart(false); if (part instanceof IEditorPart) { IEditorPart editor = (IEditorPart) part; IEditorInput input = editor.getEditorInput(); if (editor instanceof ITextEditor && input instanceof FileEditorInput) { ITextEditor textEditor = (ITextEditor) editor; // EventManager.setEditor(textEditor); saveListener(textEditor); IDocument document = textEditor.getDocumentProvider().getDocument(input); DocumentEventListener documentListener = new DocumentEventListener(textEditor.getTitle()); document.addDocumentListener(documentListener); } } }
Example #13
Source File: AbstractJavaCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void handleSmartTrigger(IDocument document, char trigger, int referenceOffset) throws BadLocationException { DocumentCommand cmd= new DocumentCommand() { }; cmd.offset= referenceOffset; cmd.length= 0; cmd.text= Character.toString(trigger); cmd.doit= true; cmd.shiftsCaret= true; cmd.caretOffset= getReplacementOffset() + getCursorPosition(); SmartSemicolonAutoEditStrategy strategy= new SmartSemicolonAutoEditStrategy(IJavaPartitions.JAVA_PARTITIONING); strategy.customizeDocumentCommand(document, cmd); replace(document, cmd.offset, cmd.length, cmd.text); setCursorPosition(cmd.caretOffset - getReplacementOffset() + cmd.text.length()); }
Example #14
Source File: OverrideMethodCompletionProposal.java From Pydev with Eclipse Public License 1.0 | 6 votes |
@Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document = viewer.getDocument(); int finalOffset = applyOnDocument(viewer, document, trigger, stateMask, offset); if (finalOffset >= 0) { try { PySelection ps = new PySelection(document, finalOffset); int firstCharPosition = PySelection.getFirstCharPosition(ps.getLine()); int lineOffset = ps.getLineOffset(); int location = lineOffset + firstCharPosition; int len = finalOffset - location; fCursorPosition = location; fReplacementLength = len; } catch (Exception e) { Log.log(e); } } }
Example #15
Source File: ToggleCommentAction.java From tlaplus with MIT License | 6 votes |
/** * Creates a region describing the text block (something that starts at * the beginning of a line) completely containing the current selection. * * @param selection The selection to use * @param document The document * @return the region describing the text block comprising the given selection */ private IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) { try { IRegion line = document.getLineInformationOfOffset(selection.getOffset()); int length = selection.getLength() == 0 ? line.getLength() : selection.getLength() + (selection.getOffset() - line.getOffset()); return new Region(line.getOffset(), length); } catch (BadLocationException x) { // should not happen // TODO } return null; }
Example #16
Source File: TextEditCreation.java From Pydev with Eclipse Public License 1.0 | 6 votes |
public static void checkExpectedInput(IDocument doc, int line, int offset, String initialName, RefactoringStatus status, IPath workspaceFile) { try { String string = doc.get(offset, initialName.length()); if (!(string.equals(initialName))) { status.addFatalError(StringUtils .format("Error: file %s changed during analysis.\nExpected doc to contain: '%s' and it contained: '%s' at offset: %s (line: %s).", workspaceFile != null ? workspaceFile : "has", initialName, string, offset, line)); return; } } catch (BadLocationException e) { status.addFatalError(StringUtils .format("Error: file %s changed during analysis.\nExpected doc to contain: '%s' at offset: %s (line: %s).", workspaceFile != null ? workspaceFile : "has", initialName, offset, line)); } }
Example #17
Source File: PartitionDeletionEditStrategy.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
@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(); } } }
Example #18
Source File: XtextEditor.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Override protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type = IDocument.DEFAULT_CONTENT_TYPE; try { type = TextUtilities.getContentType(document, IDocumentExtension3.DEFAULT_PARTITIONING, offset, false); } catch (BadLocationException exception) { // Should not happen } int lineStartPosition = super.getLineStartPosition(document, line, length, offset); if (tokenTypeToPartitionTypeMapperExtension.isMultiLineComment(type) || tokenTypeToPartitionTypeMapperExtension.isSingleLineComment(type)) { try { IRegion lineInformation = document.getLineInformationOfOffset(offset); int offsetInLine = offset - lineInformation.getOffset(); return getCommentLineStartPosition(line, length, offsetInLine, lineStartPosition); } catch(BadLocationException e) { // Should not happen } } if (type.equals(IDocument.DEFAULT_CONTENT_TYPE)) { if (isStartOfSingleLineComment(line, length, lineStartPosition) && !isStartOfMultiLineComment(line, length, lineStartPosition)) { return getTextStartPosition(line, length, lineStartPosition + 1); } } return lineStartPosition; }
Example #19
Source File: DocumentHelper.java From tlaplus with MIT License | 5 votes |
/** * At a given position in text retrieves the region marking the word, starting at and ending after the current position * @param document document * @param documentOffset offset (position of the cursor) * @param detector for identification of words * @return a region expanded forward */ public static IRegion getRegionExpandedForwards(IDocument document, int documentOffset, IWordDetector detector) { // Use string buffer to collect characters int charCounter = 0; while (true) { try { // Read character forward char c = document.getChar(++documentOffset); // This was the start of a word if (!detector.isWordPart(c)) break; // Count character charCounter++; } catch (BadLocationException e) { // Document end reached, no word break; } } return new Region(documentOffset - charCounter, charCounter + 1); }
Example #20
Source File: TypeScriptCompletionProposal.java From typescript.java with MIT License | 5 votes |
/** * Compute new replacement length for string replacement. * * @param document * @param offset * @param replacement */ protected void updateReplacementLengthForString(IDocument document, int offset, String replacement) { boolean isString = replacement.startsWith("\"") || replacement.startsWith("'"); if (isString) { int length = document.getLength(); int pos = offset; char c; while (pos < length) { try { c = document.getChar(pos); switch (c) { case '\r': case '\n': case '\t': case ' ': return; case '"': case '\'': setReplacementLength(getReplacementLength() + pos - offset + 1); return; } ++pos; } catch (BadLocationException e) { e.printStackTrace(); } } } }
Example #21
Source File: SourceEditor.java From textuml with Eclipse Public License 1.0 | 5 votes |
private void doFormat() { ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); IDocument document = getWorkingCopy().getDocument(); String toFormat = document.get(); String formatted = new TextUMLCompiler().format(toFormat); document.set(formatted); getSelectionProvider().setSelection(selection); }
Example #22
Source File: CompletionProposalPopup.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
/** * Unregister this completion proposal popup. * * @since 3.0 */ private void unregister() { if (fDocumentListener != null) { IDocument document = fContentAssistSubjectControlAdapter.getDocument(); if (document != null) { document.removeDocumentListener(fDocumentListener); } fDocumentListener = null; } fDocumentEvents.clear(); if (fKeyListener != null && Helper.okToUse(fContentAssistSubjectControlAdapter.getControl())) { fContentAssistSubjectControlAdapter.removeKeyListener(fKeyListener); fKeyListener = null; } if (fLastProposal != null) { if (fLastProposal instanceof ICompletionProposalExtension2 && fViewer != null) { ICompletionProposalExtension2 extension = (ICompletionProposalExtension2) fLastProposal; extension.unselected(fViewer); } fLastProposal = null; } fFilteredProposals = null; fComputedProposals = null; fContentAssistant.possibleCompletionsClosed(); }
Example #23
Source File: WorkingCopyRegistry.java From textuml with Eclipse Public License 1.0 | 5 votes |
public WorkingCopy getWorkingCopy(IDocument document) { for (Iterator<WorkingCopy> iter = copies.iterator(); iter.hasNext();) { WorkingCopy copy = iter.next(); if (document == copy.getDocument()) { return copy; } } return null; }
Example #24
Source File: JsonEditor.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
@Override protected void doSetInput(IEditorInput input) throws CoreException { if (input != null) { super.doSetInput(input); IDocument document = getDocumentProvider().getDocument(getEditorInput()); if (document != null) { document.addDocumentListener(changeListener); // validate content before editor opens runValidate(true); } } }
Example #25
Source File: AppendNextKillHandler.java From e4macs with Eclipse Public License 1.0 | 5 votes |
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event) throws BadLocationException { KillRing.getInstance().setForceAppend(true); // don't override M-x info if called from M-x if (event.getTrigger() != null) { EmacsPlusUtils.showMessage(editor, APPEND_KILL, false); } return NO_OFFSET; }
Example #26
Source File: JsonRpcHelpers.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
/** * Convert line, column to a document offset. * * @param document * @param line * @param column * @return */ public static int toOffset(IDocument document, int line, int column) { if (document != null) { try { return document.getLineOffset(line) + column; } catch (BadLocationException e) { JavaLanguageServerPlugin.logException(e.getMessage(), e); } } return -1; }
Example #27
Source File: IndentGuidePainter.java From IndentGuide with MIT License | 5 votes |
public void paint(int reason) { IDocument document = fTextViewer.getDocument(); if (document == null) { deactivate(false); return; } if (!fIsActive) { fIsActive = true; fTextWidget.addPaintListener(this); redrawAll(); } else if (reason == CONFIGURATION || reason == INTERNAL) { redrawAll(); } else if (reason == TEXT_CHANGE) { // redraw current line only try { IRegion lineRegion = document .getLineInformationOfOffset(getDocumentOffset(fTextWidget .getCaretOffset())); int widgetOffset = getWidgetOffset(lineRegion.getOffset()); int charCount = fTextWidget.getCharCount(); int redrawLength = Math.min(lineRegion.getLength(), charCount - widgetOffset); if (widgetOffset >= 0 && redrawLength > 0) { fTextWidget.redrawRange(widgetOffset, redrawLength, true); } } catch (BadLocationException e) { // ignore } } }
Example #28
Source File: CalcitePane.java From mat-calcite-plugin with Apache License 2.0 | 5 votes |
private IDocument createDocument() { IDocument doc = new Document(); doc.set("-- explain plan for -- or F10\n" + "-- Tables:\n" + "-- java.lang.BigInteger list of all BigIntegers\n" + "-- instanceof.java.lang.BigInteger BigIntegers and all subclasses\n" + "-- instanceof.java.lang.\"HashMap$Entry\" Entry and all subclasses\n" + "-- Virtual columns:\n" + "-- this['@shallow'] -- returns shallow heap size\n" + "-- this['@retained'] -- returns retained heap size\n" + "-- this['fieldName'] -- the same as getField(this, 'fieldName')\n" + "-- this['a.b.c'] -- the same as this['a']['b']['c']\n" + "-- Functions:\n" + "-- toString(any) returns string representation\n" + "-- getAddress(any) returns address of referenced object\n" + "-- getType(any) returns class name of referenced object\n" + "-- shallowSize(any) returns shallow heap size\n" + "-- retainedSize(any) returns retained heap size\n" + "-- length(array) returns length of array reference\n" + "-- getSize(collection or map or array) returns size of collection or array, or number of non-null elements in array\n" + "-- getByKey(map, key) returns element of map for key with given string representation\n" + "-- getField(any, field name) returns value of field for given object\n" + "select u.this, retainedSize(s.this) retained_size\n" + " from \"java.lang.String\" s\n" + " , \"java.net.URL\" u\n" + " where s.this = u.path\n"); return doc; }
Example #29
Source File: SelectionKeeper.java From Pydev with Eclipse Public License 1.0 | 5 votes |
private int getLineDelimiterLen(IDocument doc, int line) { try { String lineDelimiter = doc.getLineDelimiter(line); if (lineDelimiter == null) { return 0; } return lineDelimiter.length(); } catch (BadLocationException e) { return 0; } }
Example #30
Source File: PyCreateClassTest.java From Pydev with Eclipse Public License 1.0 | 5 votes |
public void testPyCreateClassInSameModule3() throws Exception { PyCreateClass pyCreateClass = new PyCreateClass(); String source = "" + "import foo\n" + "\n" + "class Foo(object):\n" + " pass\n" + "\n" + "class Bar(object):\n" + " def m1(self):\n" + " MyClass()\n"; IDocument document = new Document(source); ICoreTextSelection selection = new CoreTextSelection(document, source.length() - 4, 0); RefactoringInfo info = new RefactoringInfo(document, selection, PY_27_ONLY_GRAMMAR_VERSION_PROVIDER); pyCreateClass.execute(info, PyCreateClass.LOCATION_STRATEGY_BEFORE_CURRENT); assertContentsEqual("" + "import foo\n" + "\n" + "class Foo(object):\n" + " pass\n" + "\n" + "\n" + "class MyClass(${object}):\n" + " ${pass}${cursor}\n" + "\n" + "\n" + "class Bar(object):\n" + " def m1(self):\n" + " MyClass()\n", document.get()); }