下面列出了怎么用org.eclipse.jface.text.TextViewer的API类实例代码及写法,或者点击链接到github查看源代码。
private void createCommitMessageComposite(Composite parent) {
Composite commitMessageComposite = this.toolkit.createComposite(parent);
this.toolkit.paintBordersFor(commitMessageComposite);
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(commitMessageComposite);
GridDataFactory.fillDefaults().grab(true, true).applyTo(commitMessageComposite);
this.commitMessageTextViewer = new TextViewer(commitMessageComposite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
this.commitMessageTextViewer.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
GridDataFactory.fillDefaults().grab(true, true).applyTo(this.commitMessageTextViewer.getTextWidget());
this.commitMessageTextViewer.getTextWidget().setAlwaysShowScrollBars(false);
this.commitMessageTextViewer.getTextWidget().setFont(JFaceResources.getTextFont());
SWTUtil.addTextEditMenu(this.commitMessageTextViewer.getTextWidget());
//draw a line to hint the max commit line length
createMarginPainter(this.commitMessageTextViewer);
this.commitMessageTextViewer.getTextWidget().addModifyListener(e -> validateInputs());
}
public TMEditor(IGrammar grammar, ITokenProvider tokenProvider, String text) {
shell = new Shell();
viewer = new TextViewer(shell, SWT.NONE);
document = new Document();
viewer.setDocument(document);
commands = new ArrayList<>();
collector = new StyleRangesCollector();
setAndExecute(text);
reconciler = new TMPresentationReconciler();
reconciler.addTMPresentationReconcilerListener(collector);
reconciler.setGrammar(grammar);
reconciler.setTheme(tokenProvider);
reconciler.install(viewer);
}
@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 configureTextViewer(final TextViewer textViewer)
{
ThemePlugin.getDefault().getControlThemerFactory().apply(textViewer);
// Force line highlight color. We need to perform this after the line painter is attached, which happens after
// the return of this method. Scheduling async seems to work.
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
CursorLinePainter p = getCursorLinePainterInstalled(textViewer);
if (p != null)
{
p.setHighlightColor(getColorManager().getColor(getCurrentTheme().getLineHighlightAgainstBG()));
}
}
});
}
private CursorLinePainter getCursorLinePainterInstalled(TextViewer viewer)
{
Listener[] listeners = viewer.getTextWidget().getListeners(3001/* StyledText.LineGetBackground */);
for (Listener listener : listeners)
{
if (listener instanceof TypedListener)
{
TypedListener typedListener = (TypedListener) listener;
if (typedListener.getEventListener() instanceof CursorLinePainter)
{
return (CursorLinePainter) typedListener.getEventListener();
}
}
}
return null;
}
@Override
protected void handleDispose()
{
// HACK We force the widget command to be nulled out so it can be garbage collected. Might want to
// report a bug with eclipse to clean this up.
try
{
Field f = TextViewer.class.getDeclaredField("fWidgetCommand"); //$NON-NLS-1$
if (f != null)
{
f.setAccessible(true);
f.set(this, null);
}
}
catch (Throwable t)
{
// ignore
}
finally
{
super.handleDispose();
}
}
@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);
}
@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);
}
}
}
/**
* A semi-hack... This uses stuff that may change at any time in Eclipse.
* In the java editor, the projection annotation model contains the collapsible regions which correspond to methods (and other areas
* such as import groups).
*
* This may work in other editor types as well... TBD
*/
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
ExecutionEvent event) throws BadLocationException {
ITextViewerExtension viewer = MarkUtils.getITextViewer(editor);
if (viewer instanceof ProjectionViewer) {
ProjectionAnnotationModel projection = ((ProjectionViewer)viewer).getProjectionAnnotationModel();
Iterator<Annotation> pit = projection.getAnnotationIterator();
while (pit.hasNext()) {
Position p = projection.getPosition(pit.next());
if (p.includes(currentSelection.getOffset())) {
if (isUniversalPresent()) {
// Do this here to prevent subsequent scrolling once range is revealed
MarkUtils.setSelection(editor, new TextSelection(document, p.offset, 0));
}
// the viewer is pretty much guaranteed to be a TextViewer
if (viewer instanceof TextViewer) {
((TextViewer)viewer).revealRange(p.offset, p.length);
}
break;
}
}
}
return NO_OFFSET;
}
/**
* Initialize foreground, background color, current line highlight from the
* current theme if needed.
*
*/
private void applyThemeEditorIfNeeded() {
if (!initializeViewerColors) {
StyledText styledText = viewer.getTextWidget();
((ITheme) tokenProvider).initializeViewerColors(styledText);
initializeViewerColors = true;
}
if (updateTextDecorations) {
return;
}
try {
// Ugly code to update "current line highlight" :
// - get the PaintManager from the ITextViewer with reflection.
// - get the list of IPainter of PaintManager with reflection
// - loop for IPainter to retrieve CursorLinePainter which manages "current line
// highlight".
PaintManager paintManager = ClassHelper.getFieldValue(viewer, "fPaintManager", TextViewer.class);
if (paintManager == null) {
return;
}
List<IPainter> painters = ClassHelper.getFieldValue(paintManager, "fPainters", PaintManager.class);
if (painters == null) {
return;
}
for (IPainter painter : painters) {
if (painter instanceof CursorLinePainter) {
// Update current line highlight
Color background = tokenProvider.getEditorCurrentLineHighlight();
if (background != null) {
((CursorLinePainter) painter).setHighlightColor(background);
}
updateTextDecorations = true;
}
}
} catch (Exception e) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
}
}
public static TabSpacesInfo getTabSpaces(ITextViewer viewer) {
TabsToSpacesConverter converter = ClassHelper.getFieldValue(viewer, "fTabsToSpacesConverter", TextViewer.class); //$NON-NLS-1$
if (converter != null) {
int tabSize = ClassHelper.getFieldValue(converter, "fTabRatio", TabsToSpacesConverter.class); //$NON-NLS-1$
return new TabSpacesInfo(tabSize, true);
}
return new TabSpacesInfo(-1, false);
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
IDocument document = WorkbenchUtils.getActiveDocument();
IEditorInput input = WorkbenchUtils.getActiveInput();
IEditorPart editor = WorkbenchUtils.getActiveEditor(false);
boolean isTextOperationAllowed = (selection != null) && (document != null)
&& (input != null) && (editor != null)
&& (editor instanceof SourceCodeTextEditor);
if (isTextOperationAllowed) {
final ITextOperationTarget operationTarget = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
String commentPrefix = ((SourceCodeTextEditor)editor).getEOLCommentPrefix();
isTextOperationAllowed = (operationTarget != null)
&& (operationTarget instanceof TextViewer)
&& (validateEditorInputState((ITextEditor)editor))
&& (commentPrefix != null);
if ((isTextOperationAllowed)) {
final int operation = isSelectionCommented(document, selection, commentPrefix)
? ITextOperationTarget.STRIP_PREFIX
: ITextOperationTarget.PREFIX;
if (operationTarget.canDoOperation(operation)) {
BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
public void run() {
// Really processed in TextViewer.doOperation:
operationTarget.doOperation(operation);
}
});
}
}
}
return null;
}
@Override
protected SourceViewerDecorationSupport getSourceViewerDecorationSupport(ISourceViewer viewer) {
//TODO Initialize painter after editor input has been set.
painter = new TLACoveragePainter(this);
((TextViewer) viewer).addTextPresentationListener(painter);
return super.getSourceViewerDecorationSupport(viewer);
}
@Override
protected void configureTextViewer(TextViewer textViewer)
{
super.configureTextViewer(textViewer);
if (textViewer instanceof SourceViewer)
{
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.unconfigure();
IPreferenceStore preferences = SVGEditor.getChainedPreferenceStore();
SVGSourceViewerConfiguration config = new SVGSourceViewerConfiguration(preferences, null);
sourceViewer.configure(config);
}
}
@Override
protected void configureTextViewer(TextViewer textViewer)
{
super.configureTextViewer(textViewer);
if (textViewer instanceof SourceViewer)
{
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.unconfigure();
IPreferenceStore preferences = XMLEditor.getChainedPreferenceStore();
XMLSourceViewerConfiguration config = new XMLSourceViewerConfiguration(preferences, null);
sourceViewer.configure(config);
}
}
@Override
protected void configureTextViewer(TextViewer textViewer)
{
super.configureTextViewer(textViewer);
if (textViewer instanceof SourceViewer)
{
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.unconfigure();
IPreferenceStore preferences = JSSourceEditor.getChainedPreferenceStore();
JSSourceViewerConfiguration config = new JSSourceViewerConfiguration(preferences, null);
sourceViewer.configure(config);
}
}
@Override
protected void configureTextViewer(TextViewer textViewer)
{
super.configureTextViewer(textViewer);
if (textViewer instanceof SourceViewer)
{
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.unconfigure();
IPreferenceStore preferences = DTDEditor.getChainedPreferenceStore();
DTDSourceViewerConfiguration config = new DTDSourceViewerConfiguration(preferences, null);
sourceViewer.configure(config);
}
}
@Override
protected void configureTextViewer(TextViewer textViewer)
{
super.configureTextViewer(textViewer);
if (textViewer instanceof SourceViewer)
{
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.unconfigure();
IPreferenceStore preferences = CSSSourceEditor.getChainedPreferenceStore();
CSSSourceViewerConfiguration config = new CSSSourceViewerConfiguration(preferences, null);
sourceViewer.configure(config);
}
}
protected Composite doCreatePreviewPane(Composite composite, int numColumns)
{
createLabel(numColumns - 1, composite, FormatterMessages.FormatterModifyTabPage_preview_label_text);
fShowInvisibleButton = new Button(composite, SWT.CHECK);
fShowInvisibleButton.setText(FormatterMessages.FormatterModifyTabPage_showInvisible);
fShowInvisibleButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
fShowInvisibleButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
final boolean newValue = fShowInvisibleButton.getSelection();
updateShowInvisible(newValue);
getDialogSettings().put(SHOW_INVISIBLE_PREFERENCE_KEY, newValue);
}
});
previewViewer = dialog.getOwner().createPreview(composite);
final boolean savedValue = getDialogSettings().getBoolean(SHOW_INVISIBLE_PREFERENCE_KEY);
fShowInvisibleButton.setSelection(savedValue);
updateShowInvisible(savedValue);
if (previewViewer instanceof TextViewer)
{
GridData gd = createGridData(numColumns, GridData.FILL_BOTH, 0);
gd.widthHint = 100;
gd.heightHint = 100;
((TextViewer) previewViewer).getControl().setLayoutData(gd);
}
return composite;
}
@Override
protected void configureTextViewer(TextViewer textViewer)
{
super.configureTextViewer(textViewer);
if (textViewer instanceof SourceViewer)
{
SourceViewer sourceViewer = (SourceViewer) textViewer;
sourceViewer.unconfigure();
IPreferenceStore preferences = HTMLEditor.getChainedPreferenceStore();
HTMLSourceViewerConfiguration config = new HTMLSourceViewerConfiguration(preferences, null);
sourceViewer.configure(config);
}
}
/**
* Creates the action.
*
* @param textViewer the text viewer
*/
public SelectAllAction(TextViewer textViewer) {
super("selectAll"); //$NON-NLS-1$
Assert.isNotNull(textViewer);
fTextViewer= textViewer;
setText(InfoViewMessages.SelectAllAction_label);
setToolTipText(InfoViewMessages.SelectAllAction_tooltip);
setDescription(InfoViewMessages.SelectAllAction_description);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION);
}
private void beginChange() {
ITextViewer viewer= fViewer;
if (viewer instanceof TextViewer) {
TextViewer v= (TextViewer) viewer;
v.getRewriteTarget().beginCompoundChange();
}
}
private void endChange() {
ITextViewer viewer= fViewer;
if (viewer instanceof TextViewer) {
TextViewer v= (TextViewer) viewer;
v.getRewriteTarget().endCompoundChange();
}
}
/**
*
* @param id
* @param viewer
* @param name
* @param operation
* @return
*/
private final SQLEditorAction getAction( String id, TextViewer viewer,
String name, int operation )
{
SQLEditorAction action = (SQLEditorAction) htActions.get( id );
if ( action == null )
{
action = new SQLEditorAction( viewer, name, operation );
htActions.put( id, action );
}
return action;
}
public SQLEditorAction( TextViewer viewer, String text,
int operationCode )
{
super( text );
this.operationCode = operationCode;
this.viewer = viewer;
}
/**
* @param editor
* @param start
* - in model coords
* @param length
* - in model coords
*/
public static ITextSelection setSelection(ITextEditor editor, int start, int length) {
TextViewer tv = findTextViewer(editor);
ITextSelection selection = new TextSelection(null, start, length);
if (tv != null) {
tv.setSelection(selection, false);
} else {
setSelection(editor, selection);
}
return selection;
}
@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 void createMarginPainter(TextViewer commitMessageTextViewer) {
MarginPainter marginPainter = new MarginPainter(commitMessageTextViewer);
marginPainter.setMarginRulerColumn(MAX_COMMIT_MESSAGE_LINE_LENGTH); //maximum recommended commit message line length is 72
marginPainter.setMarginRulerColor(PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_GRAY));
commitMessageTextViewer.addPainter(marginPainter);
}
public TextViewerInvalidateTextPresentationCommand(int offset, int length, TextViewer viewer) {
super(getName(offset, length));
this.offset = offset;
this.length = length;
this.viewer = viewer;
}
@Override
protected void configureTextViewer(TextViewer textViewer) {
if (textViewer instanceof SourceViewer) {
configureSourceViewer(((SourceViewer) textViewer));
}
}