Tip: Spellchecking in Eclipse
Ever wanted to add spelling checking to a dialog, form or some editor in your Eclipse-based application?
Well, I needed to do this recently for a project and thought I would share with people how it can be done (also, I had people emailing me to write more tips ;p). The spell checking infrastructure in Eclipse is handled by the text editor framework. Specifically, there’s an extension point where you can add your own spellchecking engines if you so desire:
The Java Development Tools (JDT) provides an engine by default that gets activated for things like java source files, properties files and ’text’ files. To take advantage of this functionality, we need to hook into the text editing framework inside of Eclipse. I’ve provided a simple example to show you how you can do it, but here are the basics:
...
final SourceViewer sourceViewer = new SourceViewer(
composite, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
// grab the text widget from the source viewer
StyledText fTextField = sourceViewer.getTextWidget();
// this is where the magic happens for spellchecking
// see TextSourceViewerConfiguration#getReconciler
Document document = new Document(text);
SourceViewerConfiguration config =
new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore());
sourceViewer.configure(config);
sourceViewer.setDocument(document, annotationModel);
...
If you ever have written an editor within Eclipse, this code should look familiar to you. If not, well, welcome to text editing framework within Eclipse. You’ll notice that by default, everything is spellchecked. This is because of how the TextSourceViewerConfiguration sets up reconciliation by default (see getReconciler):
...
SpellingService spellingService= EditorsUI.getSpellingService();
IReconcilingStrategy strategy= new SpellingReconcileStrategy(sourceViewer, spellingService);
MonoReconciler reconciler= new MonoReconciler(strategy, false);
...
If you need to only spellcheck certain areas of a document, like say comment headers, you need to provide your own reconciler and partitions. Then you need to setup your partitions that you want to have a spellchecking strategy (SpellingReconcileStrategy) associated with.