下面列出了怎么用org.eclipse.jface.text.source.SourceViewer的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testLSFindsDiagnosticsCSProj() throws Exception {
IProject project = getProject("csprojWithError");
IFile csharpSourceFile = project.getFile("Program.cs");
IEditorPart editor = IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), csharpSourceFile);
SourceViewer viewer = (SourceViewer)getTextViewer(editor);
workaroundOmniSharpIssue1088(viewer.getDocument());
new DisplayHelper() {
@Override
protected boolean condition() {
try {
return csharpSourceFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO).length > 0;
} catch (Exception e) {
return false;
}
}
}.waitForCondition(Display.getDefault(), 5000);
DisplayHelper.sleep(500); // time to fill marker details
IMarker marker = csharpSourceFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)[0];
assertTrue(marker.getType().contains("lsp4e"));
assertEquals(12, marker.getAttribute(IMarker.LINE_NUMBER, -1));
}
/**
* 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) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
}
return null;
}
private StyledText buildEditorText( Composite parent){
final SourceViewer sourceViewer = new SourceViewer(parent, null, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
final HConfiguration sourceConf = new HConfiguration(HContentAssistProcessor.PARAM_PROCESSOR);
sourceViewer.configure(sourceConf);
sourceViewer.setDocument(DocumentUtils.createDocument1());
sourceViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed( KeyEvent e){
// if ((e.character == ' ') && ((e.stateMask & SWT.CTRL) != 0)) {
if (Utils.isAutoAssistInvoked(e)) {
IContentAssistant ca = sourceConf.getContentAssistant(sourceViewer);
ca.showPossibleCompletions();
}
}
});
return sourceViewer.getTextWidget();
}
@Override
protected SourceViewer createViewer(Composite parent) {
LangSourceViewer viewer = new LangSourceViewer(parent, null, null, false,
SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
final IContentAssistProcessor templateProcessor = getTemplateProcessor();
IDocument document = new Document();
LangDocumentPartitionerSetup.getInstance().setup(document);
IPreferenceStore store = LangUIPlugin.getDefault().getCombinedPreferenceStore();
SourceViewerConfiguration configuration = EditorSettings_Actual
.createTemplateEditorSourceViewerConfiguration(store, templateProcessor);
viewer.configure(configuration);
viewer.setEditable(true);
viewer.setDocument(document);
return viewer;
}
/**
* Saves input code to model
*/
private void saveModel( )
{
if ( isCodeModified( ) && editObject instanceof DesignElementHandle )
{
saveEditorContentsDE( (DesignElementHandle) editObject,
isSaveScript );
}
setIsModified( false );
( (IFormPage) getParentEditor( ) ).getEditor( )
.editorDirtyStateChanged( );
firePropertyChange( PROP_DIRTY );
SourceViewer viewer = getViewer( );
IUndoManager undoManager = viewer == null ? null
: viewer.getUndoManager( );
if ( undoManager != null )
{
undoManager.endCompoundChange( );
}
cleanPoint = getUndoLevel( );
}
protected void configureSourceViewer(SourceViewer sourceViewer) {
IEditorInput editorInput = getEditorInput(sourceViewer);
SourceViewerConfiguration sourceViewerConfiguration = createSourceViewerConfiguration(sourceViewer, editorInput);
sourceViewer.unconfigure();
sourceViewer.configure(sourceViewerConfiguration);
IXtextDocument xtextDocument = xtextDocumentUtil.getXtextDocument(sourceViewer);
if (xtextDocument != null) {
if (!xtextDocument.readOnly(TEST_EXISTING_XTEXT_RESOURCE)) {
String[] configuredContentTypes = sourceViewerConfiguration.getConfiguredContentTypes(sourceViewer);
for (String contentType : configuredContentTypes) {
sourceViewer.removeTextHovers(contentType);
}
sourceViewer.setHyperlinkDetectors(null, sourceViewerConfiguration.getHyperlinkStateMask(sourceViewer));
}
}
}
protected SourceViewerConfiguration createSourceViewerConfiguration(SourceViewer sourceViewer,
IEditorInput editorInput) {
SourceViewerConfiguration sourceViewerConfiguration = null;
if (editorInput != null && getEditor(sourceViewer) != null) {
DefaultMergeEditor mergeEditor = getEditor(sourceViewer);
sourceViewerConfiguration = mergeEditor.getXtextSourceViewerConfiguration();
try {
mergeEditor.init((IEditorSite) mergeEditor.getSite(), editorInput);
mergeEditor.createActions();
} catch (PartInitException partInitException) {
throw new WrappedException(partInitException);
}
} else {
sourceViewerConfiguration = sourceViewerConfigurationProvider.get();
}
return sourceViewerConfiguration;
}
@Override
protected void setActionsActivated(SourceViewer sourceViewer, boolean state) {
DefaultMergeEditor mergeEditor = getEditor(sourceViewer);
if (mergeEditor != null) {
mergeEditor.setActionsActivated(state);
IAction saveAction = mergeEditor.getAction(ITextEditorActionConstants.SAVE);
if (saveAction instanceof IPageListener) {
PartEventAction partEventAction = (PartEventAction) saveAction;
IWorkbenchPart compareEditorPart = getCompareConfiguration().getContainer().getWorkbenchPart();
if (state) {
partEventAction.partActivated(compareEditorPart);
} else {
partEventAction.partDeactivated(compareEditorPart);
}
}
}
}
/**
* Important: update only asynchronously...
*/
public void invalidateTextPresentation() {
if (viewer != null) {
RunInUiThread.async(new Runnable() {
@Override
public void run() {
ITextViewer v = viewer;
if (v != null && v instanceof SourceViewer) {
SourceViewer sourceViewer = (SourceViewer) v;
StyledText textWidget = sourceViewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
sourceViewer.invalidateTextPresentation();
}
}
}
});
}
}
@Override
protected void configureTextViewer(TextViewer viewer) {
if (viewer instanceof SourceViewer) {
SourceViewer sourceViewer = (SourceViewer) viewer;
if (fSourceViewer == null)
fSourceViewer = new ArrayList<>();
if (!fSourceViewer.contains(sourceViewer))
fSourceViewer.add(sourceViewer);
TypeScriptTextTools tools = JSDTTypeScriptUIPlugin.getDefault().getJavaTextTools();
if (tools != null) {
IEditorInput editorInput = getEditorInput(sourceViewer);
sourceViewer.unconfigure();
if (editorInput == null) {
sourceViewer.configure(getSourceViewerConfiguration(sourceViewer, null));
return;
}
getSourceViewerConfiguration(sourceViewer, editorInput);
}
}
}
@Override
protected void setActionsActivated(SourceViewer sourceViewer, boolean state) {
if (fEditor != null) {
Object editor = fEditor.get(sourceViewer);
if (editor instanceof TypeScriptEditorAdapter) {
TypeScriptEditorAdapter cuea = (TypeScriptEditorAdapter) editor;
cuea.setActionsActivated(state);
IAction saveAction = cuea.getAction(ITextEditorActionConstants.SAVE);
if (saveAction instanceof IPageListener) {
PartEventAction partEventAction = (PartEventAction) saveAction;
IWorkbenchPart compareEditorPart = getCompareConfiguration().getContainer().getWorkbenchPart();
if (state)
partEventAction.partActivated(compareEditorPart);
else
partEventAction.partDeactivated(compareEditorPart);
}
}
}
}
public LogFileViewer(Composite parent, int style) {
store = LogViewerPlugin.getDefault().getPreferenceStore();
if (store.getBoolean(ILogViewerConstants.PREF_WORD_WRAP))
style |= SWT.WRAP;
showWhenUpdated = store.getBoolean(ILogViewerConstants.PREF_SHOW_WHEN_UPDATED);
showTopOfFile = store.getBoolean(ILogViewerConstants.PREF_SHOW_TOP_OF_FILE);
txtViewer = new SourceViewer(parent,null,style);
FontData[] fontData = PreferenceConverter.getFontDataArray(store,ILogViewerConstants.PREF_EDITOR_FONT_STYLE);
if(fontData == null) {
fontData = JFaceResources.getDefaultFont().getFontData();
}
txtViewer.getTextWidget().setFont(new Font(Display.getCurrent(),fontData));
propertyChangeListener = new PropertyChangeListener();
store.addPropertyChangeListener(propertyChangeListener);
createCursorLinePainter();
createAndInstallPresentationReconciler();
}
protected void createScriptPreviewComposite(final Composite mainComposite) {
final Composite previewComposite = new Composite(mainComposite, SWT.NONE);
previewComposite.setLayout(new FillLayout(SWT.VERTICAL));
previewComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).span(2, 0).create());
final GroovyViewer groovyViewer = sourceViewerFactory.createSourceViewer(previewComposite, true);
groovyViewer.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, 300).create());
final SourceViewer sourceViewer = groovyViewer.getSourceViewer();
sourceViewer.setEditable(false);
sourceViewer.setEventConsumer(new IEventConsumer() {
@Override
public void processEvent(final VerifyEvent event) {
event.doit = false;
}
});
document = groovyViewer.getDocument();
document.set(generatedExpression.getContent());
}
protected SourceViewer createViewer(final Composite parent) {
final Builder editorBuilder = configuration.getEmbeddedEditorFactory().newEditor(resourceProvider);
editorBuilder.processIssuesBy((issues, monitor) -> {
IStatus result = Status.OK_STATUS;
final StringBuilder messages = new StringBuilder();
for (final Issue issue : issues) {
if (issue.getSeverity() == Severity.ERROR) {
if (messages.length() != 0) {
messages.append('\n');
}
messages.append(issue.getMessage());
}
}
if (messages.length() != 0) {
result = createErrorStatus(messages.toString(), null);
}
final IStatus toBeUpdated = result;
getShell().getDisplay().asyncExec(() -> updateStatus(toBeUpdated));
});
final EmbeddedEditor handle = editorBuilder.withParent(parent);
partialModelEditor = handle.createPartialEditor(getPrefix(), data.getTemplate().getPattern(), "", true);
return handle.getViewer();
}
public AbstractFormatterSelectionBlock(IStatusChangeListener context, IProject project,
IWorkbenchPreferenceContainer container)
{
super(context, project, ProfileManager.collectPreferenceKeys(TEMP_LIST, true), container);
Collections.sort(TEMP_LIST, new Comparator<IScriptFormatterFactory>()
{
public int compare(IScriptFormatterFactory s1, IScriptFormatterFactory s2)
{
return s1.getName().compareToIgnoreCase(s2.getName());
}
});
factories = TEMP_LIST.toArray(new IScriptFormatterFactory[TEMP_LIST.size()]);
TEMP_LIST = new ArrayList<IScriptFormatterFactory>();
sourcePreviewViewers = new ArrayList<SourceViewer>();
// Override the super preferences lookup order.
// All the changes to the formatter settings should go to the instance scope (no project scope here). Only the
// selected profile will be picked from the project scope and then the instance scope when requested.
fLookupOrder = new IScopeContext[] { EclipseUtil.instanceScope(), EclipseUtil.defaultScope() };
}
@Override
protected SourceViewer createPatternViewer(Composite parent) {
IDocument document= new Document();
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
JavaSourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL, store);
SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING, false);
viewer.configure(configuration);
viewer.setEditable(false);
viewer.setDocument(document);
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
new JavaSourcePreviewerUpdater(viewer, configuration, store);
Control control= viewer.getControl();
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
control.setLayoutData(data);
viewer.setEditable(false);
return viewer;
}
private Control createPreviewer(Composite parent) {
IPreferenceStore store = new ChainedPreferenceStore(new IPreferenceStore[] { fOverlayStore,
EditorConfigUIPlugin.getDefault().getCombinedPreferenceStore() });
fPreviewViewer = new SourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
fColorManager = new EditorConfigColorManager(false);
EditorConfigSourceViewerConfiguration configuration = new EditorConfigSourceViewerConfiguration(fColorManager,
store, null, IEditorConfigPartitions.EDITOR_CONFIG_PARTITIONING);
fPreviewViewer.configure(configuration);
Font font = JFaceResources.getFont(PreferenceConstants.EDITOR_CONFIG_EDITOR_TEXT_FONT);
fPreviewViewer.getTextWidget().setFont(font);
new SourcePreviewerUpdater(fPreviewViewer, configuration, store);
fPreviewViewer.setEditable(false);
String content = loadPreviewContentFromFile("EditorConfigEditorColorSettingPreviewCode.txt"); //$NON-NLS-1$
IDocument document = new Document(content);
EditorConfigDocumentSetupParticipant.setupDocument(document);
fPreviewViewer.setDocument(document);
return fPreviewViewer.getControl();
}
@Override
protected void configureTextViewer(TextViewer textViewer) {
if (!(textViewer instanceof SourceViewer))
return;
if (fPreferenceStore == null) {
fSourceViewerConfigurations= new ArrayList<SourceViewerConfiguration>(3);
fPreferenceStore= JavaPlugin.getDefault().getCombinedPreferenceStore();
fPreferenceChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
Iterator<SourceViewerConfiguration> iter= fSourceViewerConfigurations.iterator();
while (iter.hasNext())
((PropertiesFileSourceViewerConfiguration)iter.next()).handlePropertyChangeEvent(event);
invalidateTextPresentation();
}
};
fPreferenceStore.addPropertyChangeListener(fPreferenceChangeListener);
}
SourceViewerConfiguration sourceViewerConfiguration= new PropertiesFileSourceViewerConfiguration(JavaPlugin.getDefault().getJavaTextTools().getColorManager(), fPreferenceStore, null,
getDocumentPartitioning());
fSourceViewerConfigurations.add(sourceViewerConfiguration);
((SourceViewer)textViewer).configure(sourceViewerConfiguration);
}
JavaTextViewer(Composite parent) {
fSourceViewer= new SourceViewer(parent, null, SWT.LEFT_TO_RIGHT | SWT.H_SCROLL | SWT.V_SCROLL);
JavaTextTools tools= JavaCompareUtilities.getJavaTextTools();
if (tools != null) {
IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
fSourceViewer.configure(new JavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING));
}
fSourceViewer.setEditable(false);
String symbolicFontName= JavaMergeViewer.class.getName();
Font font= JFaceResources.getFont(symbolicFontName);
if (font != null)
fSourceViewer.getTextWidget().setFont(font);
}
@Override
protected void configureTextViewer(TextViewer viewer) {
if (viewer instanceof SourceViewer) {
SourceViewer sourceViewer= (SourceViewer)viewer;
if (fSourceViewer == null)
fSourceViewer= new ArrayList<SourceViewer>();
if (!fSourceViewer.contains(sourceViewer))
fSourceViewer.add(sourceViewer);
JavaTextTools tools= JavaCompareUtilities.getJavaTextTools();
if (tools != null) {
IEditorInput editorInput= getEditorInput(sourceViewer);
sourceViewer.unconfigure();
if (editorInput == null) {
sourceViewer.configure(getSourceViewerConfiguration(sourceViewer, null));
return;
}
getSourceViewerConfiguration(sourceViewer, editorInput);
}
}
}
private void configureSourceViewer(SourceViewer viewer) {
viewer.setEditable(false);
viewer.addTextListener(new ITextListener() {
@Override
public void textChanged(TextEvent event) {
updateHighlighting();
sourceViewer.getTextWidget().setFont(editorFont);
}
});
}
private StyledText buildJsonEditorText( Composite parent){
final SourceViewer sourceViewer = new SourceViewer(parent, null, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
StyledText st = sourceViewer.getTextWidget();
JSONLineStyler jsonStyler = new JSONLineStyler();
st.addLineStyleListener(jsonStyler);
return st;
}
private static StyledText buildEditorText( Composite parent){
final SourceViewer sourceViewer = new SourceViewer(parent, null, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
final XMLConfiguration sourceConf = new XMLConfiguration(new ColorManagerAdaptor(ResourceUtils.getResourceCache()));
sourceViewer.configure(sourceConf);
sourceViewer.setDocument(DocumentUtils.createDocument2());
return sourceViewer.getTextWidget();
}
private StyledText buildEditorText( Composite parent){
final SourceViewer sourceViewer = new SourceViewer(parent, null, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
final XMLConfiguration sourceConf = new XMLConfiguration(new ColorManagerAdaptor(ResourceUtils.getResourceCache()));
sourceViewer.configure(sourceConf);
sourceViewer.setDocument(DocumentUtils.createDocument2());
return sourceViewer.getTextWidget();
}
private StyledText buildJsonEditorText( Composite parent){
final SourceViewer sourceViewer = new SourceViewer(parent, null, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
StyledText st = sourceViewer.getTextWidget();
JSONLineStyler jsonStyler = new JSONLineStyler();
st.addLineStyleListener(jsonStyler);
return st;
}
@Override
protected void configureTextViewer(TextViewer textViewer) {
if(textViewer instanceof SourceViewer) {
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.configure(getSourceViewerConfiguration(sourceViewer));
} else {
super.configureTextViewer(textViewer);
}
sourceViewerNumber = (sourceViewerNumber + 1) % 3;
}
private StyledText getTextWidget() {
SourceViewer viewer = getSourceViewer();
if (viewer != null) {
return viewer.getTextWidget();
}
return null;
}
@Override
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
LangSourceViewer viewer = doCreateSourceViewer(parent, ruler, styles);
assertInstance(viewer, SourceViewer.class);
assertInstance(viewer, ISourceViewerExt.class);
return viewer;
}
@Override
public void createPartControl(Composite composite) {
SourceViewer sourceViewer = (SourceViewer) createSourceViewer(composite, createVerticalRuler(), SWT.H_SCROLL
| SWT.V_SCROLL | textOrientation);
setSourceViewer(this, sourceViewer);
getSourceViewer().configure(getXtextSourceViewerConfiguration());
getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
getSelectionProvider().addSelectionChangedListener(getSelectionChangedListener());
}
private void setSourceViewer(ITextEditor editor, SourceViewer viewer) {
Field field = null;
try {
field = AbstractTextEditor.class.getDeclaredField("fSourceViewer"); //$NON-NLS-1$
field.setAccessible(true);
field.set(editor, viewer);
} catch (Exception exception) {
throw new WrappedException(exception);
}
}