All posts by Christoph Cullmann

Dr.-Ing. Christoph Cullmann is a Senior Software Engineer at AbsInt Angewandte Informatik GmbH. His work is focused on static analysis of both binary and source programs and the WCET analysis of embedded systems. In his spare time, he works on the KDE project and maintains the Kate editor application and component.

Kate Modelines

Kate Part’s modelines – also called Kate document variables – are Kate Part’s implementation of document variables, similar to Emacs and vim modelines.

Document variables can be used to set Kate settings local to a file. This is for example for using another indenter than the one defined in the GUI settings. Or assume you work on two projects, the first indents with spaces and the second with tabs, then you can simply add a modeline that contains the specific document variables that set the specific indentation properties.

The following contents is mainly from the Kate Handbook.

Modeline Format

A modeline in the Kate Part has the following format:

kate: VARIABLENAME VALUE; [ VARIABLENAME VALUE; ... ] 

The lines can be in a comment, in C++ for example in /*...*/ sections. Multiple modelines are supported, i.e. modelines can be split over several lines for better visibility. Variable names are single words (no whitespace), and anything up to the next semicolon is the value. The trailing semicolon (;) is required.

Here is an example of how a modeline could look like, forcing indentation settings for a C++, Java or JavaScript file:

// kate: space-indent on; indent-width 4; mixedindent off; indent-mode cstyle; 

NOTE: Only the first and last 10 lines in a file are searched for modelines.

There are variables to support almost all options in Kate Part, and additionally plugins can use variables, in which case it should be documented in the plugin’s documentation.

How Kate Part uses Variables

When reading settings, Kate Part looks in the following places in the order

  1. the global configuration, i.e. settings made in the user interface
  2. the Modes & Filetypes configuration
  3. the .kateconfig file
  4. the modelines in the document itself

This means Kate Part’s modelines have actually the highest precedence. Whenever a document is saved, the document variables are reread, and will overwrite changes made using menu items or the command line.
Any variable not listed below is stored in the document and can be queried by other objects such as plugins, which can use them for their own purpose.

Available Modelines

The variables listed here documents Kate version 2.4. More variables may be added in the future. There are defied 3 types of values for variables, with the following valid expressions:

  • BOOL – on|off|true|false|1|0
  • INTEGER – any integer number
  • STRING – anything else

Available modelines are, in detail:

  • auto-brackets [BOOL]
    Set auto insertion of brackets on or off.
  • auto-center-lines [INT]
    Set the number of autocenter lines.
  • auto-insert-doxygen [BOOL]
    Turn insertion of the leading asterisk in doxygen comments on or off. This has no effect unless you use the cstyle auto-indenter.
  • background-color [STRING]
    Sets the document background color. The value must be something that can be evaluated to a valid color, for example #ff0000.
  • backspace-indents [BOOL]Turn backspace indenting on or off.
  • block-selection [BOOL]
    Turn block selection on or off.
  • bom | byte-order-marker [BOOL] (new in Kate 3.4/KDE 4.4)
    Enable/disable the byte order marker when saving files in unicode format (utf-8/utf-16/utf-32).
  • bracket-highlight-color [STRING]
    Sets the color for the bracket highlight. The value must be something that can be evaluated to a valid color, for example #ff0000.
  • current-line-color [STRING]
    Sets the color for the current line. The value must be something that can be evaluated to a valid color, for example #ff0000.
  • default-dictionary [STRING] (new in Kate 3.4/KDE 4.4)Sets the default dictionary used for spell checking.
  • dynamic-word-wrap [BOOL]
    Turns dynamic word wrap on or off.
  • eol | end-of-line [STRING]
    Sets the end of line mode. Valid settings are unix, mac and dos
  • folding-markers [BOOL]
    Set the display of folding markers on or off.
  • font-size [INT]Sets the point size of the document font.
  • font [STRING]
    Sets the font of the document. The value should be a valid font name, for example courier.
  • hl | syntax [STRING]Set the syntax highlighting. Valid strings are all the names you can find in the menus. For instance, for C++ you write C++.
  • icon-bar-color [STRING]
    Sets the icon bar color. The value must be something that can be evaluated to a valid color, for example #ff0000.
  • icon-border [BOOL]
    Set the display of the icon border on or off.
  • indent-mode [STRING]
    Set the auto-indentation mode. The options none, normal, cstyle, haskell, python, lilypond, lisp are recognized. See the section Using Automatic Indenting for details.
  • indent-width [INT]
    Sets the indentation width.
  • keep-extra-spaces [BOOL]
    Set weather to keep extra spaces when calculating indentation width.
  • keep-indent-profile [BOOL] (Removed in Kate 3, i.e. since KDE4)
    If enabled, prevents unindenting a block if at least one line has no indentation.
  • line-numbers [BOOL]
    Set the display of line numbers on or off.
  • mixed-indent [BOOL]
    Set mixed indentation ala Emacs on or off.
    DEPRECATED for Kate 3.0 From version 3.0 this variable is ignored, set replace-tabs on; instead for that version.
  • overwrite-mode [BOOL]
    Set overwrite mode on or off.
  • persistent-selection [BOOL]
    Set persistent selection on or off.
  • remove-trailing-space [BOOL]
    Set dynamic end of line cleanup on or off.
  • replace-tabs-save [BOOL]
    Set tab->space conversion on save on or off.
  • replace-tabs [BOOL]
    Set dynamic tab->space conversion on or off.
  • replace-trailing-space-save [BOOL]
    Set end of line cleanup on save on or off.
  • scheme [STRING]
    Set the color scheme. The string must be the name of a color scheme that exists in your configuration to have any effect.
  • selection-color [STRING]
    Set the selection color. The value must be something that can be evaluated to a valid color, for example #ff0000.
  • show-tabs [BOOL]Set the visual TAB character on or off.
  • smart-home [BOOL]
    Set smart home navigation on or off.
  • space-indent [BOOL]
    Set indentation with spaces on or off.
    DEPRECATED for Kate 3.0 — From Kate 3.0 mixed-indent is the default behavior, set replace-tabs on; to achieve space-only indentation.
  • tab-indents [BOOL]
    Set the TAB key indentation on or off.
  • tab-width [INT]
    Set the tab display width.
  • undo-steps [INT]
    Set the number of undo steps to remember.
  • word-wrap-column [INT]
    Set the hard word wrap width.
  • word-wrap-marker-color [STRING]
    Set the work wrap marker color. The value must be something that can be evaluated to a valid color, for example #ff0000.
  • word-wrap [BOOL]
    Set hard word wrapping on or off.
  • wrap-cursor [BOOL]
    Set cursor wrapping on or off.

Writing a Syntax Highlighting File

Note: Please refer to the Kate Handbook for the most recent version of how to write syntax highlighting files.

Hint: If you want to write a syntax highlighting file, the XML Completion plugin might be of great help.

This section is an overview of the Highlight Definition XML format in KDE4. Based on a small example it will describe the main components and their meaning and usage. The next section will go into detail with the highlight detection rules.

Main sections of Kate Highlight Definition files

The formal definition, aka the DTD is stored in the file language.dtd which should be installed on your system in the folder $KDEDIR/share/apps/katepart/syntax. If $KDEDIR is unset look up the folder by using kde4-config --prefix.

An Example

A highlighting file contains a header that sets the XML version and the doctype:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE language SYSTEM "language.dtd"> 

The root of the definition file is the element language. Available attributes are:

Required attributes:

  • name sets the name of the language. It appears in the menus and dialogs.
  • section specifies the category.
  • extensions defines file extensions, like “.cpp;.h”

Optional attributes:

  • mimetype associates files Mime Type based.
  • version specifies the current version of the definition file.
  • kateversion specifies the latest supported version of Kate.
  • casesensitive defines, whether the keywords are case sensitive or not. NOTE: not implemented yet.
  • priority is necessary if another highlight definition file uses the same extensions. The higher priority will win.
  • author contains the name of the author and his email-address.
  • license contains the license, usually LGPL, Artistic, GPL and others. It’s important to specify a license, as the kate team needs some legal backing for the distribution of the files.
  • hidden defines, whether the name should appear in Kate’s menus.

So the next line may look like this:

<language name="C++" version="1.00" kateversion="2.4" section="Sources" extensions="*.cpp;*.h" > 

Next comes the highlighting element, which contains the optional element list and the required elements contexts and itemDatas.

list elements contain a list of keywords. In this case the keywords are class and const. You can add as many lists as you need. The contexts element contains all contexts. The first context is by default the start of the highlighting. There are two rules in the context Normal Text, which match the list of keywords with the name somename and a rule that detects a quote and switches the context to string. To learn more about rules read the next chapter.
The third part is the itemDatas element. It contains all color and font styles needed by the contexts and rules.
In this example, the itemData Normal Text, String and Keyword are used.

 <highlighting> <list name="somename"> <item> class </item> <item> const </item> </list> <contexts> <context attribute="Normal Text" lineEndContext="#pop" name="Normal Text" > <keyword attribute="Keyword" context="#stay" String="somename" /> <DetectChar attribute="String" context="string" char="&quot;" /> </context> <context attribute="String" lineEndContext="#stay" name="string" > <DetectChar attribute="String" context="#pop" char="&quot;" /> </context> </contexts> <itemDatas> <itemData name="Normal Text" defStyleNum="dsNormal" /> <itemData name="Keyword" defStyleNum="dsKeyword" /> <itemData name="String" defStyleNum="dsString" /> </itemDatas> </highlighting> 

The last part of a highlight definition is the optional general section. It may contain information about keywords, code folding, comments and indentation.

The comment section defines with what string a single line comment is introduced. You also can define a multiline comments using multiLine with the additional attribute end. This is used if the user presses the corresponding shortcut for comment/uncomment.
The keywords section defines whether keyword lists are case sensitive or not. Other attributes will be explained later.

 <general> <comments> <comment name="singleLine" start="#"/> </comments> <keywords casesensitive="1"/> </general> </language> 

The Sections in Detail

This part will describe all available attributes for contexts,
itemDatas, keywords, comments, code folding and indentation.

The element context belongs into the group contexts. A context itself defines context specific rules like what should happen if the highlight system reaches the end of a line. Available attributes are:

  • name the context name/identifier. Rules will use this name to specify the context to switch to if the rule matches.
  • attribute the default item data that is used if no rules match in the current context.
  • lineEndContext defines the context the highlight system switches to if it reaches the end of a line. This may either be a name of another context, #stay to not switch the context (i.e. do nothing) or #pop which will cause to leave this context. It is possible to use for example #pop#pop#pop to pop three times.
  • lineBeginContext defines the context if a begin of a line is encountered. Default: #stay.
  • fallthrough defines if the highlight system switches to the context specified in fallthroughContext if no rule matches. Default: false.
  • fallthroughContext specifies the next context if no rule matches.
  • dynamic if true, the context remembers strings/placeholders saved by dynamic rules. This is needed for HERE documents for example. Default: false.

The element itemData is in the group itemDatas. It defines the font style and colors. So it is possible to define your own styles and colors, however we recommend to stick to the default styles if possible so that the user will always see the same colors used in different languages. Though, sometimes there is no other way and it is necessary to change color and font attributes. The attributes name and defStyleNum are required, the other optional. Available attributes are:

  • name sets the name of the itemData. Contexts and rules will use this name in their attribute.
  • attribute to reference an itemData.
  • defStyleNum defines which default style to use. Available default styles are explained in detail later.
  • color defines a color. Valid formats are ‘#rrggbb’ or ‘#rgb’.
  • selColor defines the selection color.
  • italic if true, the text will be italic.
  • bold if true, the text will be bold.
  • underline if true, the text will be underlined.
  • strikeout if true, the text will be stroked out.
  • spellChecking if true, the text will be spell checked, otherwise it will be ignored during spell check.

The element keywords in the group general defines keyword properties. Available attributes are:

  • casesensitive may be true or false. If true, all keywords are matched case sensitive. Default: true.
  • weakDeliminator is a list of characters that do not act as word delimiters. For example the dot (.) is a word delimiter. Assume a keyword in a list contains a dot, it will only match if you specify the dot as a weak delimiter.
  • additionalDeliminator defines additional delimiters.
  • wordWrapDeliminator defines characters after which a line wrap may occur. Default delimiters and word wrap delimiters are the characters .():!+,-<=>%&/;?[]^{|}~\*, space (‘ ‘) and tabulator (\t).

The element comment in the group comments defines comment properties which are used
for Tools > Comment and Tools > Uncomment.
Available attributes are:

  • name is either singleLine or multiLine.
  • If you choose singleLine the optinal attribute position is available. Default for this attribute is to insert the single line comment string in column 0. If you want it to appear after the whitespaces you have to set it to afterwhitespace, like: position="afterwhitespace".
  • If you choose multiLine the attributes end and region are required.
  • start defines the string used to start a comment. In C++ this is /*.
  • end defines the string used to close a comment. In C++ this is */.
  • region should be the name of the the foldable multiline comment. Assume you have beginRegion=”Comment”endRegion=”Comment” in your rules, you should use region=”Comment”. This way uncomment works even if you do not select all the text of the multiline comment. The cursor only must be in the multiline comment.

The element folding in the group general defines code folding properties. Available attributes are:

  • indentationsensitive if true, the code folding markers will be added indentation based, like in the scripting language Python. Usually you do not need to set it, as it defaults to false.

The element indentation in the group general defines which indenter will be used, however we strongly recommend to omit this element, as the indenter usually will be set by either defining a File Type or by adding a mode line to the text file. If you specify an indenter though, you will force a specific indentation on the user, which he might not like at all.
Available attributes are:

  • mode is the name of the indenter. Available indenters right now are: none, normal, cstyle, haskell, lilypond, lisp, python, ruby and xml.

Available Default Styles

Default styles are predefined font and color styles. For convenience Kate provides several default styles, in detail:

  • dsNormal, used for normal text.
  • dsKeyword, used for keywords.
  • dsDataType, used for data types.
  • dsDecVal, used for decimal values.
  • dsBaseN, used for values with a base other than 10.
  • dsFloat, used for float values.
  • dsChar, used for a character.
  • dsString, used for strings.
  • dsComment, used for comments.
  • dsOthers, used for ‘other’ things.
  • dsAlert, used for warning messages.
  • dsFunction, used for function calls.
  • dsRegionMarker, used for region markers.
  • dsError, used for error highlighting and wrong syntax.

Highlight Detection Rules

This section describes the syntax detection rules.

Each rule can match zero or more characters at the beginning of the string they are tested against. If the rule matches, the matching characters are assigned the style or attribute defined by the rule, and a rule may ask that the current context is switched.

A rule looks like this:

The attribute identifies the style to use for matched characters by name, and the context identifies the context to use from here.

The context can be identified by:

  • An identifier, which is the name/identifier of another context.
  • An order telling the engine to stay in the current context (#stay), or to pop back to a previous context used in the string (#pop). To go back more steps, the #pop keyword can be repeated: #pop#pop#pop

Some rules can have child rules which are then evaluated only if the parent rule matched. The entire matched string will be given the attribute defined by the parent rule. A rule with child rules looks like this:

<RuleName (attributes)> <ChildRuleName (attributes) /> ... </RuleName> 

Rule specific attributes vary and are described in the following sections.

Common attributes

All rules have the following attributes in common and are available whenever a (common attributes) appears. All following attributes are optional.

  • attribute maps to a defined itemData. Default: the attribute from the destination context
  • context specifies the context to which the highlighting system switches if the rule matches. Default: #stay
  • beginRegion starts a code folding block. Default: unset.
  • endRegion closes a code folding block. Default: unset.
  • lookAhead, if true, the highlighting system will not process the matches length. Default: false.
  • firstNonSpace, if true, the rule only matches, if the string is the first non-whitespace in the line. Default: false.
  • column defines the column. The rule only matches, if the current column matches the given one. Default: unset.

Dynamic rules

Some rules allow the optional attribute dynamic of type boolean that defaults to false. If dynamic is true, a rule can use placeholders representing the text matched by a regular expression rule that switched to the current context in its string or char attributes. In a string, the placeholder %N (where N is a number) will be replaced with the corresponding capture N from the calling regular expression. In a char the placeholer must be a number N and it will be replaced with the first character of the corresponding capture N from the calling regular expression. Whenever a rule allows this attribute it will contain a (dynamic).

  • dynamic may be either true or false. Default: false.

The Rules in Detail

DetectChar

Detect a single specific character. Commonly used for example to find the ends of quoted strings.

<DetectChar char="(character)" (common attributes) (dynamic) /> 

The char attribute defines the character to match.

Detect2Chars

Detect two specific characters in a defined order.

<Detect2Chars char="(character)" char1="(character)" (common attributes) (dynamic) /> 

The char attribute defines the first character to match, char1 the second.

AnyChar

Detect one character of a set of specified characters.

<AnyChar String="(string)" (common attributes) /> 

The String attribute defines the set of characters.

StringDetect

Detect an exact string.

<StringDetect String="(string)" [insensitive="true|false"] (common attributes) (dynamic) /> 

The String attribute defines the string to match. The insensitive attribute defaults to false and is passed to the string comparison function. If the value is true insensitive comparing is used.

WordDetect (KDE >= 4.5, Kate >= 3.5)

Detect an exact string but additionally require word boundaries like a dot (.) or a whitespace on the beginning and the end of the word. You can think of \b\b in terms of a regular expression.

<WordDetect String="(string)" [insensitive="true|false"] (common attributes) (dynamic) /> 

The String attribute defines the string to match. The insensitive attribute defaults to false and is passed to the string comparison function. If the value is true insensitive comparing is used.

RegExpr

Matches against a regular expression.

<RegExpr String="(string)" [insensitive="true|false"] [minimal="true|false"] (common attributes) (dynamic) /> 
  • The String attribute defines the regular expression.
  • insensitive defaults to false and is passed to the regular expression engine.
  • minimal defaults to false and is passed to the regular expression engine.

Because the rules are always matched against the beginning of the current string, a regular expression starting with a caret (^) indicates that the rule should only be matched against the start of a line.

keyword

Detect a keyword from a specified list.

<keyword String="(list name)" (common attributes) /> 

The String attribute identifies the keyword list by name. A list with that name must exist.

Int

Detect an integer number.

<Int (common attributes) (dynamic) /> 

This rule has no specific attributes. Child rules are typically used to detect combinations of L and U after the number, indicating the integer type in program code. Actually all rules are allowed as child rules, though, the DTD only allowes the child rule StringDetect.
The following example matches integer numbers follows by the character ‘L’.

<Int attribute="Decimal" context="#stay" > <StringDetect attribute="Decimal" context="#stay" String="L" insensitive="true"/> </Int> 

Float

Detect a floating point number.

<Float (common attributes) /> 

This rule has no specific attributes. AnyChar is allowed as a child rules and typically used to detect combinations, see rule Int for reference.

HlCOct

Detect an octal point number representation.

<HlCOct (common attributes) /> 

This rule has no specific attributes.

HlCHex

Detect a hexadecimal number representation.

<HlCHex (common attributes) /> 

This rule has no specific attributes.

HlCStringChar

Detect an escaped character.

<HlCStringChar (common attributes) /> 

This rule has no specific attributes.

It matches literal representations of characters commonly used in program code, for example \n (newline) or \t (tabulator).

The following characters will match if they follow a backslash (\): abefnrtv”’?\. Additionally, escaped hexadecimal numbers like for example \xff and escaped octal numbers, for example \033 will match.

HlCChar

Detect an C character.

<HlCChar (common attributes) /> 

This rule has no specific attributes.

It matches C characters enclosed in a tick (Example: ‘c’). So in the ticks may be a simple character or an escaped character. See HlCStringChar for matched escaped character sequences.

RangeDetect

Detect a string with defined start and end characters.

<RangeDetect char="(character)" char1="(character)" (common attributes) /> 

char defines the character starting the range, char1 the character ending the range. Usefull to detect for example small quoted strings and the like, but note that since the highlighting engine works on one line at a time, this will not find strings spanning over a line break.

LineContinue

Matches a backslash (‘\’) at the end of a line.

<LineContinue (common attributes) /> 

This rule has no specific attributes.
This rule is useful for switching context at end of line, if the last character is a backslash (‘\’). This is needed for example in C/C++ to continue macros or strings.

IncludeRules

Include rules from another context or language/file.

<IncludeRules context="contextlink" [includeAttrib="true|false"] /> 

The context attribute defines which context to include.
If it a simple string it includes all defined rules into the current context, example:

<IncludeRules context="anotherContext" /> 

If the string begins with ## the highlight system will look for another language definition with the given name, example:

<IncludeRules context="##C++" /> 

If includeAttrib attribute is true, change the destination attribute to the one of the source. This is required to make for example commenting work, if text matched by the included context is a different highlight than the host context.

DetectSpaces

Detect whitespaces.

<DetectSpaces (common attributes) /> 

This rule has no specific attributes.
Use this rule if you know that there can several whitespaces ahead, for example in the beginning of indented lines. This rule will skip all whitespace at once, instead of testing multiple rules and skipping one at the time due to no match.

DetectIdentifier

Detect identifier strings (as a regular expression: [a-zA-Z][a-zA-Z0-9]*).

<DetectIdentifier (common attributes) /> 

This rule has no specific attributes.
Use this rule to skip a string of word characters at once, rather than testing with multiple rules and skipping one at the time due to no match.

Tips & Tricks

Once you have understood how the context switching works it will be easy to write highlight definitions. Though you should carefully check what rule you choose in what situation. Regular expressions are very mighty, but they are slow compared to the other rules. So you may consider the following tips.

  • If you only match two characters use Detect2Chars instead of StringDetect. The same applies to DetectChar.
  • Regular expressions are easy to use but often there is another much faster way to achieve the same result. Consider you only want to match the character #if it is the first character in the line. A regular expression based solution would look like this:
    <RegExpr attribute="Macro" context="macro" String="^\s*#" /> 

    You can achieve the same much faster in using:

    <DetectChar attribute="Macro" context="macro" char="#" firstNonSpace="true" /> 

    If you want to match the regular expression ‘^#’ you can still use DetectChar with the attribute column=”0″. The attribute column counts character based, so a tabulator still is only one character.

  • You can switch contexts without processing characters. Assume that you want to switch context when you meet the string /*, but need to process that string in the next context. The below rule will match, and the lookAheadattribute will cause the highlighter to keep the matched string for the next context.
    <Detect2Chars attribute="Comment" context="#pop" char="*" char1="/" lookAhead="true" /> 
  • Use DetectSpaces if you know that many whitespaces occur.
  • Use DetectIdentifier instead of the regular expression ‘[a-zA-Z_]\w*’.
  • Use default styles whenever you can. This way the user will find a familiar environment.
  • Look into other XML-files to see how other people implement tricky rules.
  • You can validate every XML file by using the command xmllint --dtdvalid language.dtd mySyntax.xml.
  • If you repeat complex regular expression very often you can use ENTITIES. Example:
    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE language SYSTEM "language.dtd" [ <!ENTITY myref "[A-Za-z_:][\w.:_-]*"> ]> 

    Now you can use &myref; instead of the regular expression.

Writing a Kate Plugin

Introduction

First at all, why writing plugins for an editor ? Good question, and I hope I have a good answer: Because we want Kate to be small and all extended features not all users need should go into plugins (like CVS suppport, project managment, coffee cooking ;) Therefore Kate provides a quite full-featured plugin interface and interfaces to all important stuff in the Kate application (the documents, views, windows, sidebar …).

This tutorial is for people knowing the Qt/KDE libraries and will not describe how to compile, make … a kde/qt application/library in detail.

The “helloworld” plugin which is here described can be found in the “kdesdk” package of kde (located in kdesdk/kate/plugins/helloworld). A detailed description of the Kate API is available here..

Coding example: The Konsole plugin

This is one of standard plugins shipped with Kate which embeds the awesome KonsolePart into it to have a nice terminal emulator around.

Needed files for a plugin

Each plugin consists of at least three files which are needed:

  • a desktop file with some information about the plugin (correct syntax described later – named like kate”pluginname”.desktop
  • a XmlGui rc file named ui.rc
  • a library containing the plugin (named like kate”pluginname”plugin)

About the desktop file

The desktop file needs the syntax shown here and must be located in kde services directory with the name kate”yourpluginname”.desktop,

Example: katekonsoleplugin.desktop

[Desktop Entry]
Type=Service
ServiceTypes=Kate/Plugin
X-KDE-Library=katekonsoleplugin
X-Kate-Version=2.8
Name=Terminal tool view
Comment=Toolview embedding a terminal widget
X-Kate-MajorProfiles=Kate
X-Kate-MinorProfiles=*

The “X-Kate-Version=2.8″ line is important! Kate for KDE 4 and up won’t load your plugin unless the property is similar to the version with which you want to use the plugin!

To install this desktop file to KDE’s services directory, we’ll later add the following line to the CMakeLists.txt file:

install( FILES katekonsoleplugin.desktop  DESTINATION  ${SERVICES_INSTALL_DIR} )

About the xmlGUI rc file

The xmlgui resource file describes how the menu and toolbar actions appear in the Kate application. For more detailed examples look into other plugins. The ui.rc file for the katekonsoleplugin looks like this:

<!DOCTYPE kpartgui>
<gui name="katekonsole" library="katekonsoleplugin" version="3">
<MenuBar>
 <Menu name="tools"><text>&amp;Tools</text>
 <Action name="katekonsole_tools_pipe_to_terminal" group="tools_operations"/>
 <Action name="katekonsole_tools_sync" group="tools_operations"/>
 <Action name="katekonsole_tools_toggle_focus" group="tools_operations"/>
 </Menu>
</MenuBar>
</gui>

To automatically install the ui.rc file into the right directory later we add the following line to CMakeLists.txt:

install( FILES ui.rc  DESTINATION  ${DATA_INSTALL_DIR}/kate/plugins/katekonsole )

About plugin lib

Each Kate plugin is a library which Kate will dynamically load on demand via KLibLoader. The name of the library is kate”yourpluginname”plugin.so and should be installed into KDE’s plugin directory.

The complete result for the file CMakeLists.txt looks like this:

########### compile and link and install plugin library ###############
set(katekonsoleplugin_PART_SRCS kateconsole.cpp )
kde4_add_plugin(katekonsoleplugin ${katekonsoleplugin_PART_SRCS})
target_link_libraries(katekonsoleplugin  ${KDE4_KDEUI_LIBS} ${KDE4_KPARTS_LIBS} kateinterfaces )
install(TARGETS katekonsoleplugin  DESTINATION ${PLUGIN_INSTALL_DIR} )

########### install support files ###############
install( FILES ui.rc  DESTINATION  ${DATA_INSTALL_DIR}/kate/plugins/katekonsole )
install( FILES katekonsoleplugin.desktop  DESTINATION  ${SERVICES_INSTALL_DIR} )

Start the real coding ;)

Now we can start with the real coding, The Konsole plugin consists of 2 files, kateconsole.cpp and .h.

The plugin header file – kateconsole.h

#ifndef __KATE_CONSOLE_H__
#define __KATE_CONSOLE_H__

#include <kate/plugin.h>
#include <kate/mainwindow.h>
#include <kate/pluginconfigpageinterface.h>
#include <kurl.h>
#include <kxmlguiclient.h>

#include <kvbox.h>
#include <QList>

class QShowEvent;

namespace KParts
{
 class ReadOnlyPart;
}

namespace KateMDI
{
 }

class KateConsole;
class KateKonsolePluginView;

class KateKonsolePlugin: public Kate::Plugin, public Kate::PluginConfigPageInterface
{
 Q_OBJECT
 Q_INTERFACES(Kate::PluginConfigPageInterface)
 
 friend class KateKonsolePluginView;
 
 public:
 explicit KateKonsolePlugin( QObject* parent = 0, const QList<QVariant>& = QList<QVariant>() );
 virtual ~KateKonsolePlugin();

 Kate::PluginView *createView (Kate::MainWindow *mainWindow);

 // PluginConfigPageInterface
 uint configPages() const { return 1; };
 Kate::PluginConfigPage *configPage (uint number = 0, QWidget *parent = 0, const char *name = 0);
 QString configPageName (uint number = 0) const;
 QString configPageFullName (uint number = 0) const;
 KIcon configPageIcon (uint number = 0) const;

 void readConfig();

 QByteArray previousEditorEnv() {return m_previousEditorEnv;}
 
 private:
 QList<KateKonsolePluginView*> mViews;
 QByteArray m_previousEditorEnv;
};

class KateKonsolePluginView : public Kate::PluginView
{
 Q_OBJECT

 public:
 /**
 * Constructor.
 */
 KateKonsolePluginView (KateKonsolePlugin* plugin, Kate::MainWindow *mainWindow);

 /**
 * Virtual destructor.
 */
 ~KateKonsolePluginView ();

 void readConfig();

 private:
 KateKonsolePlugin *m_plugin;
 KateConsole *m_console;
};

/**
 * KateConsole
 * This class is used for the internal terminal emulator
 * It uses internally the konsole part, thx to konsole devs :)
 */
class KateConsole : public KVBox, public Kate::XMLGUIClient
{
 Q_OBJECT

 public:
 /**
 * construct us
 * @param mw main window
 * @param parent toolview
 */
 KateConsole (KateKonsolePlugin* plugin, Kate::MainWindow *mw, QWidget* parent);

 /**
 * destruct us
 */
 ~KateConsole ();

 void readConfig();

 /**
 * cd to dir
 * @param url given dir
 */
 void cd (const KUrl &url);

 /**
 * send given text to console
 * @param text commands for console
 */
 void sendInput( const QString& text );

 Kate::MainWindow *mainWindow()
 {
 return m_mw;
 }

 public Q_SLOTS:
 /**
 * pipe current document to console
 */
 void slotPipeToConsole ();

 /**
 * synchronize the konsole with the current document (cd to the directory)
 */
 void slotSync();
 /**
 * When syncing is done by the user, also show the terminal if it is hidden
 */
 void slotManualSync();

 private Q_SLOTS:
 /**
 * the konsole exited ;)
 * handle that, hide the dock
 */
 void slotDestroyed ();

 /**
 * construct console if needed
 */
 void loadConsoleIfNeeded();

 /**
 * set or clear focus as appropriate.
 */
 void slotToggleFocus();

 protected:
 /**
 * the konsole get shown
 * @param ev show event
 */
 void showEvent(QShowEvent *ev);

 private:
 /**
 * console part
 */
 KParts::ReadOnlyPart *m_part;

 /**
 * main window of this console
 */
 Kate::MainWindow *m_mw;

 /**
 * toolview for this console
 */
 QWidget *m_toolView;

 KateKonsolePlugin *m_plugin;
};

class KateKonsoleConfigPage : public Kate::PluginConfigPage {
 Q_OBJECT
 public:
 explicit KateKonsoleConfigPage( QWidget* parent = 0, KateKonsolePlugin *plugin = 0 );
 virtual ~KateKonsoleConfigPage()
 {}

 virtual void apply();
 virtual void reset();
 virtual void defaults()
 {}
 private:
 class QCheckBox *cbAutoSyncronize;
 class QCheckBox *cbSetEditor;
 KateKonsolePlugin *mPlugin;
};
#endif

// kate: space-indent on; indent-width 2; replace-tabs on;

The plugin source file – kateconsole.cpp

#include "kateconsole.h"
#include "kateconsole.moc"

#include <kicon.h>
#include <kiconloader.h>
#include <ktexteditor/document.h>
#include <ktexteditor/view.h>

#include <kde_terminal_interface.h>
#include <kshell.h>
#include <kparts/part.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <KDialog>

#include <kurl.h>
#include <klibloader.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>
//Added by qt3to4:
#include <QShowEvent>
#include <QLabel>

#include <QCheckBox>
#include <QVBoxLayout>

#include <kpluginloader.h>
#include <kaboutdata.h>
#include <kpluginfactory.h>
#include <kauthorized.h>

K_PLUGIN_FACTORY(KateKonsoleFactory, registerPlugin<KateKonsolePlugin>();)
K_EXPORT_PLUGIN(KateKonsoleFactory(KAboutData("katekonsole","katekonsoleplugin",ki18n("Konsole"), "0.1", ki18n("Embedded Konsole"), KAboutData::License_LGPL_V2)) )

KateKonsolePlugin::KateKonsolePlugin( QObject* parent, const QList<QVariant>& ):
 Kate::Plugin ( (Kate::Application*)parent )
{
 m_previousEditorEnv=qgetenv("EDITOR");
 if (!KAuthorized::authorizeKAction("shell_access"))
 {
 KMessageBox::sorry(0, i18n ("You do not have enough karma to access a shell or terminal emulation"));
 }
}

KateKonsolePlugin::~KateKonsolePlugin()
{
 ::setenv( "EDITOR", m_previousEditorEnv.data(), 1 );
}

Kate::PluginView *KateKonsolePlugin::createView (Kate::MainWindow *mainWindow)
{
 KateKonsolePluginView *view = new KateKonsolePluginView (this, mainWindow);
 return view;
}

Kate::PluginConfigPage *KateKonsolePlugin::configPage (uint number, QWidget *parent, const char *name)
{
 Q_UNUSED(name)
 if (number != 0)
 return 0;
 return new KateKonsoleConfigPage(parent, this);
}

QString KateKonsolePlugin::configPageName (uint number) const
{
 if (number != 0) return QString();
 return i18n("Terminal");
}

QString KateKonsolePlugin::configPageFullName (uint number) const
{
 if (number != 0) return QString();
 return i18n("Terminal Settings");
}

KIcon KateKonsolePlugin::configPageIcon (uint number) const
{
 if (number != 0) return KIcon();
 return KIcon("utilities-terminal");
}

void KateKonsolePlugin::readConfig()
{
 foreach ( KateKonsolePluginView *view, mViews )
 view->readConfig();
}

KateKonsolePluginView::KateKonsolePluginView (KateKonsolePlugin* plugin, Kate::MainWindow *mainWindow)
 : Kate::PluginView (mainWindow),m_plugin(plugin)
{
 // init console
 QWidget *toolview = mainWindow->createToolView ("kate_private_plugin_katekonsoleplugin", Kate::MainWindow::Bottom, SmallIcon("utilities-terminal"), i18n("Terminal"));
 m_console = new KateConsole(m_plugin, mainWindow, toolview);
 
 // register this view
 m_plugin->mViews.append ( this );
}

KateKonsolePluginView::~KateKonsolePluginView ()
{
 // unregister this view
 m_plugin->mViews.removeAll (this);
 
 // cleanup, kill toolview + console
 QWidget *toolview = m_console->parentWidget();
 delete m_console;
 delete toolview;
}

void KateKonsolePluginView::readConfig()
{
 m_console->readConfig();
}

KateConsole::KateConsole (KateKonsolePlugin* plugin, Kate::MainWindow *mw, QWidget *parent)
 : KVBox (parent), Kate::XMLGUIClient(KateKonsoleFactory::componentData())
 , m_part (0)
 , m_mw (mw)
 , m_toolView (parent)
 , m_plugin(plugin)
{
 QAction* a = actionCollection()->addAction("katekonsole_tools_pipe_to_terminal");
 a->setIcon(KIcon("utilities-terminal"));
 a->setText(i18nc("@action", "&Pipe to Terminal"));
 connect(a, SIGNAL(triggered()), this, SLOT(slotPipeToConsole()));

 a = actionCollection()->addAction("katekonsole_tools_sync");
 a->setText(i18nc("@action", "S&ynchronize Terminal with Current Document"));
 connect(a, SIGNAL(triggered()), this, SLOT(slotManualSync()));

 a = actionCollection()->addAction("katekonsole_tools_toggle_focus");
 a->setIcon(KIcon("utilities-terminal"));
 a->setText(i18nc("@action", "&Focus Terminal"));
 connect(a, SIGNAL(triggered()), this, SLOT(slotToggleFocus()));

 m_mw->guiFactory()->addClient (this);

 readConfig();
}

KateConsole::~KateConsole ()
{ 
 m_mw->guiFactory()->removeClient (this);
 if (m_part)
 disconnect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) );
}

void KateConsole::loadConsoleIfNeeded()
{
 if (m_part) return;

 if (!window() || !parentWidget()) return;
 if (!window() || !isVisibleTo(window())) return;

 KPluginFactory *factory = KPluginLoader("libkonsolepart").factory();

 if (!factory) return;

 m_part = static_cast<KParts::ReadOnlyPart *>(factory->create<QObject>(this, this));

 if (!m_part) return;

 // start the terminal
 qobject_cast<TerminalInterface*>(m_part)->showShellInDir( QString() );

 KGlobal::locale()->insertCatalog("konsole");

 setFocusProxy(m_part->widget());
 m_part->widget()->show();

 connect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) );

 slotSync();
}

void KateConsole::slotDestroyed ()
{
 m_part = 0;

 // hide the dockwidget
 if (parentWidget())
 {
 m_mw->hideToolView (m_toolView);
 m_mw->centralWidget()->setFocus ();
 }
}

void KateConsole::showEvent(QShowEvent *)
{
 if (m_part) return;

 loadConsoleIfNeeded();
}

void KateConsole::cd (const KUrl &url)
{
 sendInput("cd " + KShell::quoteArg(url.path()) + '\n');
}

void KateConsole::sendInput( const QString& text )
{
 loadConsoleIfNeeded();

 if (!m_part) return;

 TerminalInterface *t = qobject_cast<TerminalInterface *>(m_part);

 if (!t) return;

 t->sendInput (text);
}

void KateConsole::slotPipeToConsole ()
{
 if (KMessageBox::warningContinueCancel
 (m_mw->window()
 , i18n ("Do you really want to pipe the text to the console? This will execute any contained commands with your user rights.")
 , i18n ("Pipe to Terminal?")
 , KGuiItem(i18n("Pipe to Terminal")), KStandardGuiItem::cancel(), "Pipe To Terminal Warning") != KMessageBox::Continue)
 return;

 KTextEditor::View *v = m_mw->activeView();

 if (!v)
 return;

 if (v->selection())
 sendInput (v->selectionText());
 else
 sendInput (v->document()->text());
}

void KateConsole::slotSync()
{
 if (m_mw->activeView() ) {
 if ( m_mw->activeView()->document()->url().isValid()
 && m_mw->activeView()->document()->url().isLocalFile() ) {
 cd(KUrl( m_mw->activeView()->document()->url().directory() ));
 } else if ( !m_mw->activeView()->document()->url().isEmpty() ) {
 sendInput( "### " + i18n("Sorry, can not cd into '%1'", m_mw->activeView()->document()->url().directory() ) + '\n' );
 }
 }
}

void KateConsole::slotManualSync()
{
 slotSync();
 if ( ! m_part || ! m_part->widget()->isVisible() )
 m_mw->showToolView( parentWidget() );
}
void KateConsole::slotToggleFocus()
{
 QAction *action = actionCollection()->action("katekonsole_tools_toggle_focus");
 if ( ! m_part ) {
 m_mw->showToolView( parentWidget() );
 action->setText( i18n("Defocus Terminal") );
 return; // this shows and focuses the konsole
 }

 if ( ! m_part ) return;

 if (m_part->widget()->hasFocus()) {
 if (m_mw->activeView())
 m_mw->activeView()->setFocus();
 action->setText( i18n("Focus Terminal") );
 } else {
 // show the view if it is hidden
 if (parentWidget()->isHidden())
 m_mw->showToolView( parentWidget() );
 else // should focus the widget too!
 m_part->widget()->setFocus( Qt::OtherFocusReason );
 action->setText( i18n("Defocus Terminal") );
 }
}

void KateConsole::readConfig()
{
 disconnect( m_mw, SIGNAL(viewChanged()), this, SLOT(slotSync()) );
 if ( KConfigGroup(KGlobal::config(), "Konsole").readEntry("AutoSyncronize", false) )
 connect( m_mw, SIGNAL(viewChanged()), SLOT(slotSync()) );
 
 
 if ( KConfigGroup(KGlobal::config(), "Konsole").readEntry("SetEditor", false) )
 ::setenv( "EDITOR", "kate -b",1);
 else
 ::setenv( "EDITOR", m_plugin->previousEditorEnv().data(), 1 );
}

KateKonsoleConfigPage::KateKonsoleConfigPage( QWidget* parent, KateKonsolePlugin *plugin )
 : Kate::PluginConfigPage( parent )
 , mPlugin( plugin )
{
 QVBoxLayout *lo = new QVBoxLayout( this );
 lo->setSpacing( KDialog::spacingHint() );

 cbAutoSyncronize = new QCheckBox( i18n("&Automatically synchronize the terminal with the current document when possible"), this );
 lo->addWidget( cbAutoSyncronize );
 cbSetEditor = new QCheckBox( i18n("Set &EDITOR environment variable to 'kate -b'"), this );
 lo->addWidget( cbSetEditor );
 QLabel *tmp = new QLabel(this);
 tmp->setText(i18n("Important: The document has to be closed to make the console application continue"));
 lo->addWidget(tmp);
 reset();
 lo->addStretch();
 connect( cbAutoSyncronize, SIGNAL(stateChanged(int)), SIGNAL(changed()) );
 connect( cbSetEditor, SIGNAL(stateChanged(int)), SIGNAL(changed()) );
}

void KateKonsoleConfigPage::apply()
{
 KConfigGroup config(KGlobal::config(), "Konsole");
 config.writeEntry("AutoSyncronize", cbAutoSyncronize->isChecked());
 config.writeEntry("SetEditor", cbSetEditor->isChecked());
 config.sync();
 mPlugin->readConfig();
}

void KateKonsoleConfigPage::reset()
{
 KConfigGroup config(KGlobal::config(), "Konsole");
 cbAutoSyncronize->setChecked(config.readEntry("AutoSyncronize", false));
 cbSetEditor->setChecked(config.readEntry("SetEditor", false));
}

// kate: space-indent on; indent-width 2; replace-tabs on;

How does the Plugin look & work after install ?

You first have to go to the Settings -> Configure Kate -> Kate -> Plugins in Kate and activate the Konsole  plugin.

More information ? Advanced plugin stuff ?

To get more information about the plugin interface and its advanced functions please look at the Kate API documentation and the KTextEditor API documentation or contact us on our mailing list!