Java Code Examples for org.eclipse.jface.text.IDocument

The following examples show how to use org.eclipse.jface.text.IDocument. These examples are extracted from open source projects. 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 Project: http4e   Source File: DocumentUtils.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: typescript.java   Source File: TypeScriptCompletionProposal.java    License: MIT License 6 votes vote down vote up
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 3
/**
 * @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 Project: http4e   Source File: XMLConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: birt   Source File: ScriptEditor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 6
Source Project: tlaplus   Source File: TLAPartitionScanner.java    License: MIT License 6 votes vote down vote up
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 7
Source Project: n4js   Source File: N4JSHyperlinkDetector.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 8
Source Project: Pydev   Source File: ModulesManagerWithBuild.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 9
Source Project: texlipse   Source File: SpellChecker.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 10
@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 11
/**
 * 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 12
Source Project: Pydev   Source File: TextEditCreation.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 13
Source Project: tlaplus   Source File: ToggleCommentAction.java    License: MIT License 6 votes vote down vote up
/**
 * 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 14
@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
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 16
Source Project: scava   Source File: PartEventListener.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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 17
/**
 * @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 18
Source Project: KaiZen-OpenAPI-Editor   Source File: JsonEditor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@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 19
@SuppressWarnings("try")
public static String formatEclipseStyle(final Properties prop, final String content) {
  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("JavaFormatter.formatEclipseStyle")) {
    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("size", content.length()).build("args"));

    final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(prop);
    final IDocument document = new Document(content);
    final TextEdit textEdit =
        codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
            content,
            0,
            content.length(),
            0,
            null);
    if (nonNull(textEdit)) {
      textEdit.apply(document);
      return ensureCorrectNewLines(document.get());
    } else {
      return content;
    }
  } catch (Throwable e) {
    return content;
  }
}
 
Example 20
Source Project: textuml   Source File: SourceEditor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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 21
Source Project: xtext-eclipse   Source File: InterpreterAutoEdit.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private BigDecimal computeResult(IDocument document, DocumentCommand command) {
	return xtextDocumentUtil.getXtextDocument(document).tryReadOnly((XtextResource resource) -> {
		Evaluation stmt = findEvaluation(command, resource);
		if (stmt == null) {
			return null;
		}
		return evaluate(stmt);
	});
}
 
Example 22
Source Project: xtext-eclipse   Source File: TokenScanner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void setRange(IDocument document, final int offset, final int length) {
	this.regionOffset = offset;
	overlapFilter = Regions.overlaps(offset, length);
	Iterable<ILexerTokenRegion> newIterable = getTokens(document);
	if (delegateIterable != null) {
		if (!delegateIterable.equals(newIterable)) {
			current = null;
		}
	}
	if (current == null) {
		delegate = newIterable.iterator();
		delegateIterable = newIterable;
		computedHasNext = false;
		hasNext = false;
	} else {
		if (current.getOffset() <= offset && current.getOffset() + current.getLength() > offset) {
			// offset is inside of current - return current as next
			computedHasNext = true;
			hasNext = true;
		} else {
			// restart - use a new delegate
			computedHasNext = false;
			hasNext = false;
			delegate = newIterable.iterator();
			delegateIterable = newIterable;
		}
	}
}
 
Example 23
@Override
protected List<String> getAdditionalComments(IDocument d, DocumentCommand c)
{
	List<String> params = ParseUtil.getFunctionParameters(d, c.offset);
	return CollectionsUtil.map(params, new IMap<String, String>()
	{
		public String map(String item)
		{
			return "@param {Object} " + item; //$NON-NLS-1$
		}
	});
}
 
Example 24
/**
 * Returns <code>true</code> if the document command is applied on a multi
 * line selection, <code>false</code> otherwise.
 *
 * @param document the document
 * @param command the command
 * @return <code>true</code> if <code>command</code> is a multiline command
 */
private boolean isMultilineSelection(IDocument document, DocumentCommand command) {
	try {
		return document.getNumberOfLines(command.offset, command.length) > 1;
	} catch (BadLocationException e) {
		// ignore
		return false;
	}
}
 
Example 25
@Override
public void connect(Object element) throws CoreException {
	super.connect(element);

	IDocument document = this.getDocument(element);
	if (document != null) {
		IPartitioningConfiguration configuration = this.getPartitioningConfiguration();
		IDocumentPartitioner partitioner = new ExtendedFastPartitioner(this.createPartitionScanner(), configuration.getContentTypes());

		partitioner.connect(document);
		document.setDocumentPartitioner(partitioner);

		CommonEditorPlugin.getDefault().getDocumentScopeManager().registerConfiguration(document, configuration);
	}
}
 
Example 26
Source Project: gwt-eclipse-plugin   Source File: SseUtilities.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Resolves the file that is associated with the given document.
 * 
 * @return an IFile pointing to the file in the workspace, or null if one
 *         could not be resolved.
 */
public static IFile resolveFile(IDocument document) {
  IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(
      document);
  try {
    return resolveFile(model);
  } finally {
    model.releaseFromRead();
  }
}
 
Example 27
Source Project: Pydev   Source File: ImportArranger.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public ImportArranger(IDocument doc, boolean removeUnusedImports, String endLineDelim, String indentStr,
        boolean automatic, IPyFormatStdProvider edit) {
    this.doc = doc;
    this.endLineDelim = endLineDelim;
    this.indentStr = indentStr;
    this.removeUnusedImports = removeUnusedImports;
    this.automatic = automatic;
    this.edit = edit;
    multilineImports = ImportsPreferencesPage.getMultilineImports(edit);
    sortNamesGrouped = ImportsPreferencesPage.getSortNamesGrouped(edit);
    breakWithParenthesis = getBreakImportsWithParenthesis(edit);
    maxCols = getMaxCols(multilineImports);
}
 
Example 28
Source Project: typescript.java   Source File: JSDocAutoIndentStrategy.java    License: MIT License 5 votes vote down vote up
/**
 * Returns <code>true</code> if the comment being inserted at
 * <code>command.offset</code> is the first comment (the first javadoc
 * comment if <code>ignoreJavadoc</code> is <code>true</code>) of the given
 * member.
 * <p>
 * see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=55325 (don't add
 * parameters if the member already has a comment)
 * </p>
 */
private boolean isFirstComment(IDocument document, DocumentCommand command, IMember member,
		boolean ignoreNonJavadoc) throws BadLocationException, JavaScriptModelException {
	IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	ISourceRange sourceRange = member.getSourceRange();
	if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
		return false;
	int srcOffset = sourceRange.getOffset();
	int srcLength = sourceRange.getLength();
	int nameRelativeOffset = member.getNameRange().getOffset() - srcOffset;
	int partitionRelativeOffset = partition.getOffset() - srcOffset;
	String token = ignoreNonJavadoc ? "/**" : "/*"; //$NON-NLS-1$ //$NON-NLS-2$
	return document.get(srcOffset, srcLength).lastIndexOf(token, nameRelativeOffset) == partitionRelativeOffset;
}
 
Example 29
@Override
protected IDocument createDocument(Object element) throws CoreException {
	IDocument document = null;
	if (element instanceof IStreamContentAccessor) {
		document = createEmptyDocument();
		setupDocument(element, document);
	}
	return document;
}
 
Example 30
Source Project: tm4e   Source File: ToggleLineCommentHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void addBlockComment(IDocument document, ITextSelection selection, CharacterPair blockComment,
		ITextEditor editor) throws BadLocationException {
	document.replace(selection.getOffset(), 0, blockComment.getKey());
	document.replace(selection.getOffset() + selection.getLength() + blockComment.getKey().length(), 0,
			blockComment.getValue());
	ITextSelection newSelection = new TextSelection(selection.getOffset() + blockComment.getKey().length(),
			selection.getLength());
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}