Introducing the Formatting plugin
So this is not quite an introduction since the plugin has been around for almost a year now, having been released in the 23.04 release but since I never got around to writing a blog about it, here I am.
In simple words, the formatting plugin allows one to format code easily and quickly. Well the "quickness" depends on the underlying code formatter but we try to be as quick as possible. So far if you wanted to do code formatting from within Kate, the only way to do that was to configure a tool in the External Tools plugin and then invoke it whenever you wanted to format the code. While this works it wasn't great for a few reasons. Firstly, you would loose undo history. Secondly, the buffer would jump and you would most likely loose your current position in the document. Thirdly, for every language you get a different tool and you need to remember the right tool to invoke on the right document type.
To simplify this, I decided to write a plugin that would expose a minimal UI but still provide a lot of features.
There are basically two ways to use this plugin:
- Manually using the "Format Document" action.
- Automatically on save
The correct formatter is invoked based on the document type in all cases. Additionally the plugin will preserve the document's undo history and user's cursor position when formatting the code so that the formatting of code doesn't disrupt user's workflow. This is especially important for automatic formatting on save.
Supported languages:
The current list of supported languages and formatters are as follows:
- C/C++/ObjectiveC/ObjectiveC++/Protobuf
- clang-format
- Javascript/Typescript/JSX/TSX
- Prettier
- Json
- clang-format
- Prettier
- jq
- Dart
- dartfmt
- Rust
- rustfmt
- XML
- xmllint
- Go
- gofmt
- Zig
- zigfmt
- CMake
- cmake-format
- Pythong
- autopep8
- ruff
Configuring
The plugin can be configured in two ways:
- Globally, from the Configure dialog
- On a per project basis using the
.kateproject
file
When reading the config, the plugin will first try to read the config from .kateproject
file and then read the global config.
Example:
{
"formatOnSave": true,
"formatterForJson": "jq",
"cmake-format": {
"formatOnSave": false
},
"autopep8": {
"formatOnSave": false
}
}
The above
- enables "format on save" globally
- specifies "jq" as the formatter for JSON
- disables "format on save" for cmake-format and autopep8
To configure formatting for a project, first create a .kateproject
file and then add a "formatting"
object to it. In the "formatting"
object you can specify your settings as shown in the previous example. Example:
{
"name": "My Cool Project",
"files": [
{
"git": 1
}
],
"formatting": {
"formatterForJson": "clang-format",
"autopep8": {
"formatOnSave": false
}
}
}