Click here to Skip to main content
15,065,328 members
Articles / Desktop Programming / Windows Forms
Posted 12 Nov 2008


193 bookmarked

Using ICSharpCode.TextEditor

Rate me:
Please Sign up or sign in to vote.
4.79/5 (57 votes)
12 Nov 2008MIT8 min read
Use TextEditorControl to put a syntax-highlighting editor in your application.
  • Download source code - 396 KB
  • Note: ICSharpCode.TextEditor and the sample application require a C# 3.0 compiler, but they are configured to target .NET Framework 2.0. Normally, we get ICSharpCode.TextEditor bundled with the SharpDevelop source code, but the sample project includes the latest version ( all by itself.



SharpDevelop has a feature-rich, if not documentation-rich, text editor control. The demo attached to this article shows how to use it to load and save files, find and replace strings in a document, do clipboard actions, use TextMarkers to highlight strings, use a FoldingStrategy to let the user collapse areas of the document, use bookmarks, and change some display settings.

Hopefully, the remainder of this article will provide enough information to point you in the right direction for any customization you might want to make to the text editor's behavior.

The design of ICSharpCode.TextEditor

A text editor actually contains three nested controls that are closely coupled to one another:

  • At the top level is TextEditorControl, which contains either one or two TextAreaControls. It has two TextEditorControls when "split", as demonstrated in the screenshot.
  • TextAreaControl encapsulates the horizontal and vertical scroll bars, and a TextArea.
  • TextArea is the control that actually gets the focus. It paints the text and handles keyboard input.

If there's one thing more important than the control classes, it's the IDocument interface. The IDocument interface, implemented in the DefaultDocument class, is the hub that provides access to most of the features of SharpDevelop's text editor: undo/redo, markers, bookmarks, code folding, auto-indenting, syntax highlighting, settings, and last but not least, management of the text buffer.

Here is a diagram of these basic classes:


Note: On Visual Studio class diagrams, I can't show a derivation arrow from a class to the interface it implements, so instead, I point DefaultDocument's "interface lollipop" toward its interface.


Below is a more complete diagram that includes other classes and interfaces you can reach via the properties of TextArea and IDocument. The features of the text editor such as code folding and syntax highlighting are neatly divided into separate classes or interfaces, most of which can be replaced with a custom or derived version, if that's what you need.

The TextEditor (and SharpDevelop, in general) often uses the "Strategy" pattern, so you'll see that word a lot. In the Strategy pattern, an interface defines the functionality required, but not how to implement it. If you need a different implementation, you can write your own and call the appropriate setter in IDocument to change the strategy. In theory, anyway. For some reason, MarkerStrategy is a sealed class with no corresponding interface, and therefore cannot be replaced.

Image 3

Let's talk about the features branching out from IDocument.

  • The document provides unlimited undo/redo automatically. You need not do anything special to ensure that programmatic changes can be undone; just be sure to modify the document using methods in IDocument, not in ITextBufferStrategy (the latter bypasses the undo stack). You can group multiple actions together so that one "undo" command undoes them all by surrounding the group with matching calls to IDocument.UndoStack.StartUndoGroup() and IDocument.UndoStack.EndUndoGroup().
  • Markers (instances of the TextMarker class) are ranges of text (with a start and end position). After registering a marker with a document's MarkerStrategy, the marker's start and endpoints move automatically as the document is modified. Markers can be visible or invisible; if visible, a marker can either underline text (with a spellchecker-style squiggle), or override the syntax highlighting of the region it covers. The sample application uses markers to implement its "Highlight all" command.
  • Curiously, there is another class which serves a similar purpose: TextAnchor anchors to a single point, and automatically moves as the document is changed, but you can't use this class because its constructor is internal.

  • Bookmarks are rectangular markers shown in the "icon bar" margin, which the user can jump to by pressing F2. The sample project shows how to toggle bookmarks and move between them.
  • Code folding allows blocks of text to be collapsed. There are no (working) code folding strategies built into ISharpCode.TextEditor, so if you want to make an editor with code folding, consider snooping around the source code of SharpDevelop for an implementation. In the demo, I implemented a simple folding strategy that supports only #region/#endregion blocks. The DefaultDocument and TextEditorControl do not try to update code folding markers automatically, so in the demo, folding is only computed when a file is first loaded.
  • In the presence of code folding, there are two kinds of line numbers.

    • "logical" line numbers which are the 'real' line numbers displayed in the margin.
    • "visible" line numbers which are the line numbers after folding is applied. The term "line number" by itself normally refers to a logical line number.
  • Auto-indenting, and related features that format the document in reaction to the user's typing, are intended to be provided in an implementation of IFormattingStrategy. The DefaultFormattingStrategy simply matches the indentation of the previous line when Enter is pressed. Again, fancier strategies can be found in SharpDevelop's source code.
  • IFormattingStrategy also contains methods to search backward or forward in the document for matching brackets so they can be highlighted, but this is just part of the mechanism for highlighting matching brackets, a mechanism whose implementation spans several classes including TextUtilities, BracketHighlightingSheme, BracketHighlight, and TextArea. Anyway, it appears that TextArea is hard-coded to provide brace matching for (), [], and {} only.

  • Syntax highlighting is normally provided by an instance of DefaultHighlightingStrategy, which highlights files based on XML files with an "xshd" extension. More than a dozen such files are built into the text editor DLL as resources, and TextEditorControl automatically chooses a highlighter when loading a file, according to the file's extension. It does not change the highlighter when the file name changes; so the demo's DoSaveAs method uses HighlightingStrategyFactory to obtain the appropriate strategy. There are articles out there about adding more XSHD-based highlighters, such as this one and this one.
  • The text buffer strategy manages the text buffer. The algorithm behind the default GapTextBufferStrategy is described on Wikipedia and on CodeProject.
  • ITextEditorProperties encapsulates miscellaneous options such as whether to show line numbers and how wide tabs should be.
  • ITextEditorProperties has no way to inform any other object that its properties have been changed. If you change one of these properties directly, and it affects the appearance of the control, the control doesn't repaint automatically. For that reason, TextEditorControlBase has a wrapper for every property in ITextEditorProperties that it needs to monitor. For instance, TextEditorControlBase.TabIndent is a wrapper around ITextEditorProperties.TabIndent. By the way, you can share a ITextEditorProperties object among many text editors, and I have done so in the demo.

In addition to all this, the the ICSharpCode.TextEditor project contains some code related to what is commonly known as "intellisense": an "insight window" (a tooltip-like window typically used to show method signatures) and a "code completion" list.

ICSharpCode.TextEditor itself does not actually perform intellisense, but it contains some code for the GUI of these features. However, this code is not used directly by the text editor, and my demo does not demonstrate it (in fact, I don't know how to use it).

The text editor library is very large; there are a number of other miscellaneous classes that couldn't fit on the diagram, which I don't have time to describe in this article. Notable ones include TextWord, the atomic unit of syntax highlighting; LineManager, which DefaultDocument uses to convert "offsets" to "positions"; and TextUtilities, a collection of static methods.

Here are some more tips:

  • A location in a document can be represented in two ways. First, a location can be represented as a line-column pair, which one bundles together in a TextLocation structure. More fundamentally, you can think of a document as an array of characters whose length is IDocument.TextLength. An index into this array is called an "offset" (type: int). The offset representation seems to be more common, but some code (e.g., the SelectionManager) requires locations to be supplied in the form of TextLocations. You can use IDocument.OffsetToPosition and IDocument.PositionToOffset to convert between the two representations.
  • The "Caret" is the flashing cursor. You can move the cursor by changing the Caret's Line, Column, or Position properties.
  • All text editor actions that can be invoked with a key combination in SharpDevelop are encapsulated in implementations of ICSharpCode.TextEditor.Actions.IEditAction. A few of these actions are demonstrated in the example application's Edit menu handlers.
  • The left side of the TextArea shows up to three margins, represented by three classes that are not on the diagram above. They are not separate controls, but TextArea passes mouse and paint commands to them.
    • FoldMargin shows the little + and - icons for collapsing or expanding regions. If you don't use code folding, I'm afraid there is no way to hide the margin (well, you could change the source code).
    • IconBarMargin shows icons such as bookmarks (or breakpoints in SharpDevelop). Visibility is controlled by ITextEditorProperties.IsIconBarVisible.
    • GutterMargin shows line numbers. Visibility is controlled by ITextEditorProperties.ShowLineNumbers.
  • The document has no reference to the controls that use it, so I assume we could use the same document in multiple controls, manage a document that has no control, or write a new control implementation. Editor controls are informed of changes to the document by subscribing to its events.
  • The most heavyweight part of ICSharpCode.TextEditor is its syntax highlighting, which can use ten times as much memory as the size of the text file being edited. Code to draw this text uses a lot of CPU power and allocates copious amounts of temporary objects.
  • I'm not really an expert; I only learned enough about ICSharpCode.TextEditor to write this article! Have fun!


  • Nov. 13, 2008 - First release.
  • Note: although my sample is provided under the MIT license, ICSharpCode.TextEditor itself is provided under the terms of the GNU LGPL.


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Software Developer None
Canada Canada
Since I started programming when I was 11, I wrote the SNES emulator "SNEqr", the FastNav mapping component, the Enhanced C# programming language (in progress), the parser generator LLLPG, and LES, a syntax to help you start building programming languages, DSLs or build systems.

My overall focus is on the Language of your choice (Loyc) initiative, which is about investigating ways to improve interoperability between programming languages and putting more power in the hands of developers. I'm also seeking employment.

Comments and Discussions

QuestionAttempting to run Pin
ilia.broudno12-Apr-21 12:55
Memberilia.broudno12-Apr-21 12:55 
AnswerRe: Attempting to run Pin
baiello21-Aug-21 12:07
Memberbaiello21-Aug-21 12:07 
QuestionHow can I change BackColor and ForeColor Pin
ighack16-Dec-18 15:06
Memberighack16-Dec-18 15:06 
QuestionLangueges supported Pin
Cool Smith26-Oct-16 1:25
MemberCool Smith26-Oct-16 1:25 
AnswerRe: Langueges supported Pin
Qwertie28-Oct-16 14:50
MemberQwertie28-Oct-16 14:50 
GeneralRe: Langueges supported Pin
Cool Smith21-Nov-16 0:19
MemberCool Smith21-Nov-16 0:19 
GeneralRe: Langueges supported Pin
Qwertie21-Nov-16 14:51
MemberQwertie21-Nov-16 14:51 
QuestionHow could I display current Carret Pos in StatusBar? Pin
Dmitry_Bond26-Feb-15 21:43
MemberDmitry_Bond26-Feb-15 21:43 
AnswerRe: How could I display current Carret Pos in StatusBar? Pin
Qwertie27-Feb-15 10:39
MemberQwertie27-Feb-15 10:39 
GeneralRe: How could I display current Carret Pos in StatusBar? Pin
Dmitry_Bond27-Feb-15 18:41
MemberDmitry_Bond27-Feb-15 18:41 
NewsCreated a ICSharpCode.TextEditorEx project based on ICSharpCode.TextEditor and the code from this project Pin
Stef Heyenrath6-Aug-14 10:56
MemberStef Heyenrath6-Aug-14 10:56 
QuestionMove Caret Pin
lxnitu10-Mar-14 4:17
Memberlxnitu10-Mar-14 4:17 
AnswerRe: Move Caret Pin
Qwertie10-Mar-14 20:49
MemberQwertie10-Mar-14 20:49 
GeneralRe: Move Caret Pin
lxnitu11-Mar-14 1:36
Memberlxnitu11-Mar-14 1:36 
GeneralRe: Move Caret Pin
Qwertie11-Mar-14 9:29
MemberQwertie11-Mar-14 9:29 
GeneralRe: Move Caret Pin
lxnitu11-Mar-14 10:25
Memberlxnitu11-Mar-14 10:25 
BugBuggy control version causes crashes Pin
nadav7419-Feb-14 13:39
Membernadav7419-Feb-14 13:39 
QuestionBackColor and ForeColor Pin
Skeletro 3M17-Oct-13 21:51
MemberSkeletro 3M17-Oct-13 21:51 
QuestionDesign Editor/Viewer for HTML/ASP.NET pages Pin
Chirag B9-Sep-13 3:56
MemberChirag B9-Sep-13 3:56 
AnswerRe: Design Editor/Viewer for HTML/ASP.NET pages Pin
Qwertie9-Sep-13 6:50
MemberQwertie9-Sep-13 6:50 
GeneralRe: Design Editor/Viewer for HTML/ASP.NET pages Pin
Chirag B9-Sep-13 7:29
MemberChirag B9-Sep-13 7:29 
QuestionCan you add Undo/Redo code? Pin
Chirag B6-Sep-13 19:00
MemberChirag B6-Sep-13 19:00 
AnswerRe: Can you add Undo/Redo code? Pin
Qwertie7-Sep-13 6:34
MemberQwertie7-Sep-13 6:34 
GeneralRe: Can you add Undo/Redo code? Pin
Chirag B9-Sep-13 3:53
MemberChirag B9-Sep-13 3:53 
QuestionMessage Closed Pin
25-Aug-13 23:34
MemberMember 1023224425-Aug-13 23:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.