Java 类org.eclipse.jface.text.ITextViewer 实例源码

项目:eclipse-batch-editor    文件:BatchEditorSimpleWordContentAssistProcessor.java   
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    IDocument document = viewer.getDocument();
    if (document == null) {
        return null;
    }
    String source = document.get();

    Set<String> words = simpleWordCompletion.calculate(source, offset);

    ICompletionProposal[] result = new ICompletionProposal[words.size()];
    int i = 0;
    for (String word : words) {
        result[i++] = new SimpleWordProposal(document, offset, word);
    }

    return result;
}
项目:eclipse-bash-editor    文件:BashEditorSimpleWordContentAssistProcessor.java   
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    IDocument document = viewer.getDocument();
    if (document == null) {
        return null;
    }
    String source = document.get();

    Set<String> words = simpleWordCompletion.calculate(source, offset);

    ICompletionProposal[] result = new ICompletionProposal[words.size()];
    int i = 0;
    for (String word : words) {
        result[i++] = new SimpleWordProposal(document, offset, word);
    }

    return result;
}
项目:codelens-eclipse    文件:ClassReferencesCodeLensProvider.java   
@Override
public ICodeLens[] provideSyncCodeLenses(ICodeLensContext context, IProgressMonitor monitor) {
    ITextViewer textViewer = context.getViewer();
    IDocument document = textViewer.getDocument();
    List<ICodeLens> lenses = new ArrayList<>();
    int lineCount = document.getNumberOfLines();
    for (int i = 0; i < lineCount; i++) {
        String line = getLineText(document, i, false);
        int index = line.indexOf("class ");
        if (index != -1) {
            String className = line.substring(index + "class ".length(), line.length());
            index = className.indexOf(" ");
            if (index != -1) {
                className = className.substring(0, index);
            }
            if (className.length() > 0) {
                lenses.add(new ClassCodeLens(className, i + 1));
            }
        }
    }
    return lenses.toArray(new ICodeLens[0]);
}
项目:codelens-eclipse    文件:EditorTracker.java   
private void editorOpened(IEditorPart part) {
    if (part instanceof ITextEditor) {
        ITextViewer textViewer = (ITextViewer) part.getAdapter(ITextOperationTarget.class);
        if (textViewer != null) {
            ICodeLensController controller = codeLensControllers.get(part);
            if (controller == null) {
                ITextEditor textEditor = (ITextEditor) part;
                controller = CodeLensControllerRegistry.getInstance().create(textEditor);
                if (controller != null) {
                    controller.setProgressMonitor(new NullProgressMonitor());
                    codeLensControllers.put(textEditor, controller);
                    //controller.install();
                }
            }
        }
    }
}
项目:pgcodekeeper    文件:SQLEditorTemplateAssistProcessor.java   
@Override
protected String extractPrefix(ITextViewer viewer, int offset) {
    int i = offset;
    IDocument document = viewer.getDocument();
    if (i > document.getLength()) {
        return ""; //$NON-NLS-1$
    }
    try {
        while (i > 0) {
            char ch = document.getChar(i - 1);
            if (!PgDiffUtils.isValidIdChar(ch)) {
                break;
            }
            i--;
        }
        if (i > 0) {
            int j = i;
            if (document.getChar(j - 1) == '<') {
                i--;
            }
        }
        return document.get(i, offset - i);
    } catch (BadLocationException e) {
        return ""; //$NON-NLS-1$
    }
}
项目:pgcodekeeper    文件:SQLEditorHyperLinkDetector.java   
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    SQLEditor editor = getAdapter(SQLEditor.class);
    PgDbParser parser = editor.getParser();

    int offset = region.getOffset();
    List<PgObjLocation> refs = parser.getObjsForEditor(editor.getEditorInput());
    for (PgObjLocation obj : refs) {
        if (offset > obj.getOffset()
                && offset < (obj.getOffset() + obj.getObjLength())) {
            IHyperlink[] links =  parser.getDefinitionsForObj(obj)
                    .map(def -> new SQLEditorHyperLink(
                            new Region(def.getOffset(), def.getObjLength()),
                            new Region(obj.getOffset(), obj.getObjLength()),
                            obj.getObjName(), def.getFilePath(), def.getLineNumber()))
                    .toArray(IHyperlink[]::new);
            if (links.length != 0) {
                return links;
            }
        }
    }
    return null;
}
项目:pgcodekeeper    文件:SQLEditorTextHover.java   
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
    PgDbParser parser = editor.getParser();
    List<PgObjLocation> refs = parser.getObjsForEditor(editor.getEditorInput());
    for (PgObjLocation obj : refs) {
        if (offset > obj.getOffset()
                && offset < (obj.getOffset() + obj.getObjLength())) {
            Optional<PgObjLocation> loc = parser.getDefinitionsForObj(obj).findAny();
            if (loc.isPresent()) {
                SQLEditorMyRegion region = new SQLEditorMyRegion(obj.getOffset(), obj.getObjLength());
                region.setComment(loc.get().getComment());
                return region;
            }
        }
    }
    return new Region(offset, 0);
}
项目:Hydrograph    文件:HydrographJavaCompletionProcessor.java   
@Override
   protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset) 
{
            ICompilationUnit compilationUnit = ((SourceViewer) viewer).getCompilatioUnit();
           if (compilationUnit != null) {

               CompletionProposalCollector completionProposalCollector = new CompletionProposalCollector(compilationUnit);
               JavaContentAssistInvocationContext invocContext = new JavaContentAssistInvocationContext(viewer, offset,
                    new NullEditorPart());

               completionProposalCollector.setInvocationContext(invocContext);
               return invocContext;
           } else {
               return null;
           }

   }
项目:vertigo-chroma-kspplugin    文件:KspTextHover.java   
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {

    IDocument document = textViewer.getDocument();

    /* Vérifie qu'on est dans une String de KSP */
    boolean isSqlString = DocumentUtils.isContentType(document, offset, KspRegionType.STRING);
    if (!isSqlString) {
        return null;
    }

    /* Extrait le mot courant. */
    ITextSelection selection = new TextSelection(document, offset, 0);
    ITextSelection currentWordSelection = DocumentUtils.findCurrentWord(document, selection, WordSelectionType.SNAKE_CASE);
    if (currentWordSelection == null) {
        return null;
    }
    String currentWord = currentWordSelection.getText();
    if (currentWord == null) {
        return null;
    }

    /* Renvoie la région du mot. */
    return new Region(currentWordSelection.getOffset(), currentWordSelection.getLength());
}
项目:vertigo-chroma-kspplugin    文件:KspTextHover.java   
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {

    /* Extrait le mot de la région. */
    String currentWord = getSelectedWord(textViewer, hoverRegion);

    /* Extrait un nom de DTO : Calcul le nom en PascalCase */
    String javaName = StringUtils.toPascalCase(currentWord);

    /* Cherche le fichier Java du DTO. */
    DtoFile dtoFile = DtoManager.getInstance().findDtoFile(javaName);
    if (dtoFile == null) {
        return null;
    }

    /* Renvoie le nom Java. Le texte complet sera généré par KspInformationPresenter. */
    return javaName;
}
项目:ec4e    文件:CompositeReconcilingStrategy.java   
@Override
public void install(ITextViewer textViewer) {
    if (fStrategies == null)
        return;

    for (int i = 0; i < fStrategies.length; i++) {
        if (fStrategies[i] instanceof IReconciler) {
            IReconciler extension = (IReconciler) fStrategies[i];
            try {
                extension.install(textViewer);
            } catch (Exception e) {

            }

        }
    }
}
项目:ec4e    文件:EditorConfigCompletionProposal.java   
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    initIfNeeded();
    IDocument document = viewer.getDocument();
    if (fTextViewer == null) {
        fTextViewer = viewer;
    }
    // don't eat if not in preferences, XOR with modifier key 1 (Ctrl)
    // but: if there is a selection, replace it!
    Point selection = viewer.getSelectedRange();
    fToggleEating = (stateMask & SWT.MOD1) != 0;
    int newLength = selection.x + selection.y - getReplacementOffset();
    if ((insertCompletion() ^ fToggleEating) && newLength >= 0) {
        setReplacementLength(newLength);
    }
    apply(document, trigger, offset);
    fToggleEating = false;
}
项目:ec4e    文件:EditorConfigTextHover.java   
/***
 * Returns true if it exists a marker annotation in the given offset and false
 * otherwise.
 *
 * @param textViewer
 * @param offset
 * @return true if it exists a marker annotation in the given offset and false
 *         otherwise.
 */
private static boolean hasProblem(ITextViewer textViewer, int offset) {
    if (!(textViewer instanceof ISourceViewer)) {
        return false;
    }

    IAnnotationModel annotationModel = ((ISourceViewer) textViewer).getAnnotationModel();
    Iterator<Annotation> iter = (annotationModel instanceof IAnnotationModelExtension2)
            ? ((IAnnotationModelExtension2) annotationModel).getAnnotationIterator(offset, 1, true, true)
            : annotationModel.getAnnotationIterator();
    while (iter.hasNext()) {
        Annotation ann = iter.next();
        if (ann instanceof MarkerAnnotation) {
            return true;
        }
    }
    return false;
}
项目:tm4e    文件:TMPresentationReconciler.java   
/**
 * Returns the {@link TMPresentationReconciler} of the given text viewer and
 * null otherwise.
 * 
 * @param textViewer
 * @return the {@link TMPresentationReconciler} of the given text viewer and
 *         null otherwise.
 */
public static TMPresentationReconciler getTMPresentationReconciler(ITextViewer textViewer) {
    try {
        Field field = SourceViewer.class.getDeclaredField("fPresentationReconciler");
        if (field != null) {
            field.setAccessible(true);
            IPresentationReconciler presentationReconciler = (IPresentationReconciler) field.get(textViewer);
            return presentationReconciler instanceof TMPresentationReconciler
                    ? (TMPresentationReconciler) presentationReconciler
                    : null;
        }
    } catch (Exception e) {

    }
    return null;
}
项目:egradle    文件:GradleTextHover.java   
/**
 * Get language at given offset
 * 
 * @param offset
 * @param textViewer
 * @return language element or <code>null</code>
 */
protected HoverDataRegion getLanguageElementAt(int offset, ITextViewer textViewer) {
    IContentAssistant assist = gradleSourceViewerConfiguration.getContentAssistant(sourceViewer);
    if (assist == null) {
        return null;
    }
    IContentAssistProcessor processor = assist.getContentAssistProcessor(contentType);
    if (!(processor instanceof GradleContentAssistProcessor)) {
        return null;
    }
    GradleContentAssistProcessor gprocessor = (GradleContentAssistProcessor) processor;
    String allText = textViewer.getDocument().get();
    RelevantCodeCutter codeCutter = this.codeCutter;
    Model model = gprocessor.getModel();
    GradleFileType fileType = gradleSourceViewerConfiguration.getFileType();
    GradleLanguageElementEstimater estimator = gprocessor.getEstimator();

    HoverData data = hoverSupport.caclulateHoverData(allText, offset, codeCutter, model, fileType, estimator);
    if (data == null) {
        return null;
    }
    return new HoverDataRegion(data);
}
项目:eclipse-asciidoctools    文件:AsciidocContentAssistProcessor.java   
@Override
public ComparableCompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    List<ComparableCompletionProposal> results = new ArrayList<ComparableCompletionProposal>();
    IDocument document = viewer.getDocument();

    if (viewer.getSelectedRange().y == 0) {
        try {
            int position = getCurrentWordStart(document, offset);
            String start = document.get(position, offset - position);
            results.addAll(AsciidocVariablesProposals.getValidCompletionProposals(document, offset, start));
            if (isCurrentLineStart(document, offset)) {
                results.addAll(AsciidocBlocksAndHeadersProposals.getValidCompletionProposals(document, offset));
            }
            results.addAll(AsciidocAnchorsProposals.getValidCompletionProposals(document, offset, start));
            results.addAll(AsciidocMacrosCompletionProposals.getValidCompletionProposals(document, offset, start));
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    } else {

    }
    Collections.sort(results);
    return results.toArray(new ComparableCompletionProposal[0]);
}
项目:LibertyEiffel-Eclipse-Plugin    文件:EiffelContentAssistantProcessor.java   
@Override
    public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {

        try {
            List<ICompletionProposal> completionProposals = new ArrayList<ICompletionProposal>();
            IDocument document = viewer.getDocument();
            String prefix = lastWord(document, offset);
            String indent = lastIndent(document, offset);
//          EiffelModel model = EiffelModel.getModel(document, null);
//          model.getContentProposals(prefix, indent, offset, completionProposals);

            return completionProposals.toArray(new ICompletionProposal[completionProposals.size()]);

        } catch (Exception e) {
            return NO_COMPLETIONS;
        }
    }
项目:ftc    文件:FtcCompletionProcessor.java   
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {

    currentCompletions = getCompletions(viewer.getDocument().get(), documentOffset);

    ICompletionProposal[] templates = super.computeCompletionProposals(viewer, documentOffset);
    ICompletionProposal[] completions = getModelElementProposals(currentCompletions.modelElements, documentOffset, sourceViewer.getSelectedRange().y);

    ICompletionProposal[] result = new ICompletionProposal[templates.length + completions.length];

    int idx = 0;
    for (int i = 0; i < templates.length; i++) {
        result[idx] = templates[i];
        idx++;
    }
    for (int i = 0; i < completions.length; i++) {
        result[idx] = completions[i];
        idx++;
    }

    return result;
}
项目:texlipse    文件:TexTemplateCompletion.java   
/**
 * Adds all available TeX templates to the given list, available meaning here that
 * the templates match the found prefix.
 * 
 * @param viewer The viewer associated with this editor
 * @param documentOffset The offset in the document where the completions hould take place
 * @param prefix The prefix of the completion string
 * @return An <code>ArrayList</code> containing the <code>ICompletionProposals</code>
 */
public ArrayList addTemplateProposals(ITextViewer viewer, int documentOffset, String prefix) {
    ArrayList propList = new ArrayList();
    ICompletionProposal[] templateProposals = 
            computeCompletionProposals(viewer, documentOffset);

    // compute doesn't give the right proposal list for some reason,
    // so we need to filter here
    for (int j = 0; j < templateProposals.length; j++) {
        ICompletionProposal proposal = templateProposals[j];
        if (proposal.getDisplayString().startsWith(prefix)) {
            propList.add(templateProposals[j]);
        }
    }
    Collections.sort(propList, new CompletionProposalComparator());
    return propList;
}
项目:texlipse    文件:BibTexTemplateCompletion.java   
/**
 * This method overrides the default one (which is suited for Java
 * (i.e. result in NOT replacing anything before '.', which causes
 * inconvenience, when templates are named like "list.itemize"
 * 
 * @param viewer
 * @param offset Document offset
 * @return prefix (all character counting back from current cursont
 *     position, until a space(' '), linefeed('\n'), carriage return('\r'),
 *     a tab('\t') or the beginning of the file is encountered
 */
protected String extractPrefix(ITextViewer viewer, int offset) {
    int i = offset - 1;
    if (i == -1) {
        return "";
    }

    StringBuffer sb = new StringBuffer("");
    char c;
    try {
        c = viewer.getDocument().getChar(i);
        while (!Character.isWhitespace(c)) {
            sb.append(c);
            i--;
            if (i < 0) {
                break;
            } else {
                c = viewer.getDocument().getChar(i);
            }
        }
    } catch (BadLocationException e) {
        TexlipsePlugin.log("BibTemplateCompletion, extractPrefix.", e);
    }
    return sb.reverse().toString();
}
项目:http4e    文件:MyTextHover.java   
public String getHoverInfo( ITextViewer textViewer, IRegion hoverRegion){
   int offset = hoverRegion.getOffset();
   if (hoverRegion != null) {
      try {
         if (hoverRegion.getLength() > -1) {
            IDocument doc = textViewer.getDocument();
            // String key = textViewer.getDocument().get(offset, hoverRegion.getLength());
            // ITypedRegion region = doc.getPartition(offset);
            ITypedRegion partitionType = textViewer.getDocument().getPartition(offset);

            IRegion reg2 = doc.getLineInformationOfOffset(offset);
            String lineText = doc.get(reg2.getOffset(), reg2.getLength());
            // if(BaseUtils.isEmpty(key)){
            // key = BaseUtils.getKeyFromLine(lineText);
            // return HAssistInfoMap.getInfo(key);
            // }
            String key = DocumentUtils.getKeyFromLine(lineText);
            return LazyObjects.getInfoMap("Headers").getInfo(key);
         }
      } catch (BadLocationException x) {
      }
   }

   return "JavaEditorMessages.getString(MyTextHover.emptySelection)";
}
项目:n4js    文件:JSDocContentAssistProcessor.java   
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    if (viewer instanceof XtextSourceViewer) {
        IXtextDocument document = (IXtextDocument) viewer.getDocument();
        return document.priorityReadOnly(createCompletionProposalComputer(viewer, offset));
    }

    return new ICompletionProposal[0];
}
项目:n4js    文件:JSDocCompletionProposalComputer.java   
/**
 * Creates this computer.
 */
public JSDocCompletionProposalComputer(JSDocContentAssistProcessor jsDocContentAssistProcessor, ITextViewer viewer,
        int offset) {
    this.processor = jsDocContentAssistProcessor;
    this.viewer = viewer;
    this.offset = offset;
}
项目:n4js    文件:N4JSHyperlinkDetector.java   
/**
 * 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 {
            if (resource == null) {
                return null;
            }
            if (helper instanceof ISourceViewerAware && textViewer instanceof ISourceViewer) {
                ((ISourceViewerAware) helper).setSourceViewer((ISourceViewer) textViewer);
            }
            return helper.createHyperlinksByOffset(resource, region.getOffset(), canShowMultipleHyperlinks);
        }
    }, null);
}
项目:n4js    文件:FQNImporter.java   
FQNImporter(
        Resource context,
        IScope scope,
        IValueConverter<String> valueConverter,
        Predicate<IEObjectDescription> filter,
        ITextViewer viewer) {
    this.context = context;
    this.scope = scope;
    this.valueConverter = valueConverter;
    this.filter = filter;
    this.viewer = viewer;
}
项目:eclipse-bash-editor    文件:BashTextHover.java   
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    BashEditorPreferences preferences = BashEditorPreferences.getInstance();
    boolean tooltipsEnabled = preferences.getBooleanPreference(P_TOOLTIPS_ENABLED);
    if (!tooltipsEnabled){
        return null;
    }
    IDocument document = textViewer.getDocument();
    if (document == null) {
        return "";
    }
    String text = document.get();
    if (text == null) {
        return "";
    }
    int offset = hoverRegion.getOffset();
    String word = SimpleStringUtils.nextWordUntilWhitespace(text, offset);
    if (word.isEmpty()) {
        return "";
    }

    for (DocumentKeyWord keyword : DocumentKeyWords.getAll()) {
        if (word.equals(keyword.getText())) {
            return buildHoverInfo(keyword);
        }
    }

    return "";
}
项目:codelens-eclipse    文件:CodeLensStrategy.java   
public CodeLensStrategy(ICodeLensContext context, boolean invalidateTextPresentation) {
    this.context = context;
    this.invalidateTextPresentation = invalidateTextPresentation;
    this.targets = new ArrayList<>();
    // Initialize the view change accessor in the UI Thread because the
    // constructor update the StyledTextRenderer which is accessible only in
    // an UI Thread.
    ITextViewer textViewer = context.getViewer();
    textViewer.getTextWidget().getDisplay().syncExec(() -> {
        CodeLensStrategy.this.accessor = new ViewZoneChangeAccessor(textViewer);
    });
    this._lenses = new ArrayList<>();
}
项目:codelens-eclipse    文件:ClassReferencesCodeLensProvider.java   
@Override
public ICodeLens resolveSyncCodeLens(ICodeLensContext context, ICodeLens codeLens, IProgressMonitor monitor) {
    ITextViewer textViewer = context.getViewer();
    IDocument document = textViewer.getDocument();
    String className = ((ClassCodeLens) codeLens).getClassName();
    int refCount = 0;
    int lineCount = document.getNumberOfLines();
    for (int i = 0; i < lineCount; i++) {
        String line = getLineText(document, i, false);
        refCount += line.contains("new " + className) ? 1 : 0;
    }
    ((ClassCodeLens) codeLens).setCommand(new Command(refCount + " references", ""));
    return codeLens;
}
项目:codelens-eclipse    文件:ViewZoneDemo.java   
public static void main(String[] args) throws Exception {
    // create the widget's shell
    Shell shell = new Shell();
    shell.setLayout(new FillLayout());
    shell.setSize(500, 500);
    Display display = shell.getDisplay();

    Composite parent = new Composite(shell, SWT.NONE);
    parent.setLayout(new GridLayout(2, false));

    ITextViewer textViewer = new TextViewer(parent, SWT.V_SCROLL | SWT.BORDER);
    textViewer.setDocument(new Document(""));
    StyledText styledText = textViewer.getTextWidget();
    styledText.setLayoutData(new GridData(GridData.FILL_BOTH));

    ViewZoneChangeAccessor viewZones = new ViewZoneChangeAccessor(textViewer);

    Button add = new Button(parent, SWT.NONE);
    add.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 0, 0));
    add.setText("Add Zone");
    add.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            InputDialog dlg = new InputDialog(Display.getCurrent().getActiveShell(), "", "Enter view zone content",
                    "Zone " + viewZones.getSize(), null);
            if (dlg.open() == Window.OK) {
                int line = styledText.getLineAtOffset(styledText.getCaretOffset());
                IViewZone zone = new DefaultViewZone(line, 20, dlg.getValue());
                viewZones.addZone(zone);
                viewZones.layoutZone(zone);
            }
        }
    });

    shell.open();
    while (!shell.isDisposed())
        if (!display.readAndDispatch())
            display.sleep();
}
项目:codelens-eclipse    文件:ClassImplementationsCodeLensProvider.java   
@Override
public ICodeLens[] provideSyncCodeLenses(ICodeLensContext context, IProgressMonitor monitor) {
    ITextViewer textViewer = context.getViewer();
    IDocument document = textViewer.getDocument();
    List<ICodeLens> lenses = new ArrayList<>();
    int lineCount = document.getNumberOfLines();
    for (int i = 0; i < lineCount; i++) {
        updateCodeLens(i, document, "class ", lenses);
        updateCodeLens(i, document, "interface ", lenses);
    }
    return lenses.toArray(new ICodeLens[0]);
}
项目:codelens-eclipse    文件:ClassImplementationsCodeLensProvider.java   
@Override
public ICodeLens resolveSyncCodeLens(ICodeLensContext context, ICodeLens codeLens, IProgressMonitor monitor) {
    ITextViewer textViewer = context.getViewer();
    IDocument document = textViewer.getDocument();
    String className = ((ClassCodeLens) codeLens).getClassName();
    int refCount = 0;
    int lineCount = document.getNumberOfLines();
    for (int i = 0; i < lineCount; i++) {
        String line = getLineText(document, i, false);
        refCount += line.contains("implements " + className) ? 1 : 0;
    }
    ((ClassCodeLens) codeLens).setCommand(new Command(refCount + " implementation", ""));
    return codeLens;
}
项目:codelens-eclipse    文件:CodeLensDemo.java   
public static void main(String[] args) throws Exception {
    // create the widget's shell
    Shell shell = new Shell();
    shell.setLayout(new FillLayout());
    shell.setSize(500, 500);
    Display display = shell.getDisplay();

    Composite parent = new Composite(shell, SWT.NONE);
    parent.setLayout(new GridLayout(2, false));

    ITextViewer textViewer = new TextViewer(parent, SWT.V_SCROLL | SWT.BORDER);
    String delim = textViewer.getTextWidget().getLineDelimiter();
    textViewer.setDocument(new Document(delim + " class A" + delim + "new A" + delim + "new A" + delim + "class B"
            + delim + "new B" + delim + "interface I" + delim + "class C implements I"));
    StyledText styledText = textViewer.getTextWidget();
    styledText.setLayoutData(new GridData(GridData.FILL_BOTH));

    CodeLensProviderRegistry registry = CodeLensProviderRegistry.getInstance();
    registry.register(CONTENT_TYPE_ID, new ClassReferencesCodeLensProvider());
    registry.register(CONTENT_TYPE_ID, new ClassImplementationsCodeLensProvider());

    CodeLensStrategy codelens = new CodeLensStrategy(new DefaultCodeLensContext(textViewer), false);
    codelens.addTarget(CONTENT_TYPE_ID).reconcile(null);

    styledText.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent event) {
            codelens.reconcile(null);
        }
    });

    shell.open();
    while (!shell.isDisposed())
        if (!display.readAndDispatch())
            display.sleep();
}
项目:codelens-eclipse    文件:EditorTracker.java   
@Override
public void partActivated(IWorkbenchPart part) {
    if (part instanceof ITextEditor) {
        ITextViewer textViewer = (ITextViewer) part.getAdapter(ITextOperationTarget.class);
        if (textViewer != null) {
            ICodeLensController controller = codeLensControllers.get(part);
            if (controller != null) {
                controller.refresh();
            }
        }
    }
}
项目:codelens-eclipse    文件:DefaultCodeLensController.java   
@Override
public void refresh() {
    if (textViewer == null) {
        this.textViewer = (ITextViewer) getTextEditor().getAdapter(ITextOperationTarget.class);
        reconciler.install(textViewer);
    }
    getStrategy().initialReconcile();
}
项目:pgcodekeeper    文件:SQLEditorTemplateAssistProcessor.java   
@Override
protected TemplateContextType getContextType(ITextViewer viewer,
        IRegion region) {
    SQLEditorTemplateManager manager = SQLEditorTemplateManager
            .getInstance();
    return manager.getContextTypeRegistry().getContextType(
            SQLEditorTemplateContextType.CONTEXT_TYPE);
}
项目:pgcodekeeper    文件:SQLEditorTemplateAssistProcessor.java   
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
        int offset) {
    ITextSelection selection = (ITextSelection) viewer
            .getSelectionProvider().getSelection();
    // adjust offset to end of normalized selection
    if (selection.getOffset() == offset) {
        offset = selection.getOffset() + selection.getLength();
    }
    String prefix = extractPrefix(viewer, offset);
    Region region = new Region(offset - prefix.length(), prefix.length());
    TemplateContext context = createContext(viewer, region);
    if (context == null) {
        return new ICompletionProposal[0];
    }
    context.setVariable("selection", selection.getText()); // name of the selection variables {line, word_selection //$NON-NLS-1$
    Template[] templates = getTemplates(context.getContextType().getId());
    List<ICompletionProposal> matches = new ArrayList<>();
    for (Template template : templates) {
        try {
            context.getContextType().validate(template.getPattern());
        } catch (TemplateException e) {
            continue;
        }
        if (!prefix.equals("") && prefix.charAt(0) == '<') { //$NON-NLS-1$
            prefix = prefix.substring(1);
        }
        if (!prefix.equals("") //$NON-NLS-1$
                && (template.getName().startsWith(prefix) && template
                        .matches(prefix, context.getContextType().getId()))) {
            matches.add(createProposal(template, context, (IRegion) region,
                    getRelevance(template, prefix)));
        }
    }
    return matches.toArray(new ICompletionProposal[matches.size()]);
}
项目:pgcodekeeper    文件:SQLEditorTemplateAssistProcessor.java   
public List<ICompletionProposal> getAllTemplates(ITextViewer viewer,
        int offset) {
    List<ICompletionProposal> result = new ArrayList<>();
    String prefix = extractPrefix(viewer, offset);
    Region region = new Region(offset - prefix.length(), prefix.length());
    TemplateContext context = createContext(viewer, region);
    Template[] templates = getTemplates(context.getContextType().getId());
    for (Template template : templates) {
        result.add(createProposal(template, context, (IRegion) region,
                getRelevance(template, prefix)));
    }
    return result;
}
项目:pgcodekeeper    文件:SQLEditorTextHover.java   
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    @SuppressWarnings("deprecation")
    String msg = super.getHoverInfo(textViewer, hoverRegion);
    if (msg != null) {
        return msg;
    }
    if (hoverRegion instanceof SQLEditorMyRegion) {
        return ((SQLEditorMyRegion) hoverRegion).getComment();
    }
    return "";  //$NON-NLS-1$
}
项目:Hydrograph    文件:HydrographCompletionProposalComputer.java   
public List<ICompletionProposal> computeCompletionProposals(ITextViewer textViewer, String prefix, int offset,
            IProgressMonitor monitor) {
        List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
        try {
            int replacementLength = textViewer.getSelectedRange().y;
            if (replacementLength == 0) {
                replacementLength = prefix.length();
            }
            String displayLabel;
            String replacementString;
            List<ClassDetails> classList = ClassRepo.INSTANCE.getClassList();
            Image image=ImagePathConstant.INTELLISENCE_IMAGE.getImageFromRegistry();

            for (ClassDetails classDetails : classList) {
//              if (!classDetails.isUserDefined()) {
                    List<MethodDetails> methodlist = classDetails.getMethodList();
                    for (MethodDetails methodDetails : methodlist) {
                        displayLabel = classDetails.getcName() + Constants.DOT + methodDetails.getSignature();
                        replacementString = methodDetails.getPlaceHolder();

                        HydrographCompletionProposal customProposal=new HydrographCompletionProposal(replacementString,offset-prefix.length(),replacementLength,replacementString.length(),
                                image,displayLabel,null,null);
                        customProposal.setType(CUSTOM_TYPE);
                        proposals.add(customProposal);
                    }
//              }
            }
            addAvailableFieldsProposals(textViewer,image,proposals,prefix,offset,replacementLength);
        } catch (RuntimeException exception) {
            LOGGER.error("Error occurred while building custom proposals", exception);
        }
        filterProposalsOnPrefix(prefix, proposals);
        System.gc();
        return proposals;
    }
项目:Hydrograph    文件:HydrographCompletionProposalComputer.java   
@SuppressWarnings("unchecked")
private void addAvailableFieldsProposals(ITextViewer textViewer,Image image, List<ICompletionProposal> proposals,String prefix, int offset,int replacementLength) {
    Map<String,Class<?>> fieldMap=(Map<String, Class<?>>)textViewer.getTextWidget().getData(ExpressionEditorDialog.FIELD_DATA_TYPE_MAP); 

    for(Entry<String, Class<?>> entry:fieldMap.entrySet()){
        String display = entry.getKey()+SWT.SPACE+Constants.DASH+entry.getValue().getSimpleName();
        String replacementString=SWT.SPACE+entry.getKey()+SWT.SPACE;
        HydrographCompletionProposal customProposal=new HydrographCompletionProposal(replacementString,offset-prefix.length(),replacementLength,replacementString.length(),
                image,display,null,null);
        customProposal.setType(CUSTOM_TYPE);

        proposals.add(customProposal);
    }
}