Debian Codegraph @

book/src/languages.md

raw symbols SCIP
1 ## Languages
2
3 Language-specific settings and settings for language servers are configured
4 in `languages.toml` files.
5
6 ## `languages.toml` files
7
8 There are three possible locations for a `languages.toml` file:
9
10 1. In the Helix source code, which lives in the
11 [Helix repository](https://github.com/helix-editor/helix/blob/master/languages.toml).
12 It provides the default configurations for languages and language servers.
13
14 2. In your [configuration directory](./configuration.md). This overrides values
15 from the built-in language configuration. For example, to disable
16 auto-formatting for Rust:
17
18 ```toml
19 # in <config_dir>/helix/languages.toml
20
21 [language-server.mylang-lsp]
22 command = "mylang-lsp"
23
24 [[language]]
25 name = "rust"
26 auto-format = false
27 ```
28
29 3. In a `.helix` folder in your project. Language configuration may also be
30 overridden local to a project by creating a `languages.toml` file in a
31 `.helix` folder. Its settings will be merged with the language configuration
32 in the configuration directory and the built-in configuration.
33
34 ## Language configuration
35
36 Each language is configured by adding a `[[language]]` section to a
37 `languages.toml` file. For example:
38
39 ```toml
40 [[language]]
41 name = "mylang"
42 scope = "source.mylang"
43 injection-regex = "mylang"
44 file-types = ["mylang", "myl"]
45 comment-tokens = "#"
46 indent = { tab-width = 2, unit = " " }
47 formatter = { command = "mylang-formatter" , args = ["--stdin"] }
48 language-servers = [ "mylang-lsp" ]
49 ```
50
51 These configuration keys are available:
52
53 | Key | Description |
54 | ---- | ----------- |
55 | `name` | The name of the language |
56 | `language-id` | The language-id for language servers, checkout the table at [TextDocumentItem](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem) for the right id |
57 | `scope` | A string like `source.js` that identifies the language. Currently, we strive to match the scope names used by popular TextMate grammars and by the Linguist library. Usually `source.<name>` or `text.<name>` in case of markup languages |
58 | `injection-regex` | regex pattern that will be tested against a language name in order to determine whether this language should be used for a potential [language injection][treesitter-language-injection] site. |
59 | `file-types` | The filetypes of the language, for example `["yml", "yaml"]`. See the file-type detection section below. |
60 | `shebangs` | The interpreters from the shebang line, for example `["sh", "bash"]` |
61 | `roots` | A set of marker files used for LSP working directory selection. Helix starts at the file, walks upward, and remembers the *topmost* i.e. *last* directory that contains a marker file. For example Cargo.lock, yarn.lock |
62 | `auto-format` | Whether to autoformat this language when saving |
63 | `diagnostic-severity` | Minimal severity of diagnostic for it to be displayed. (Allowed values: `error`, `warning`, `info`, `hint`) |
64 | `comment-tokens` | The tokens to use as a comment token, either a single token `"//"` or an array `["//", "///", "//!"]` (the first token will be used for commenting). Also configurable as `comment-token` for backwards compatibility|
65 | `block-comment-tokens`| The start and end tokens for a multiline comment either an array or single table of `{ start = "/*", end = "*/"}`. The first set of tokens will be used for commenting, any pairs in the array can be uncommented |
66 | `indent` | The indent to use. Has sub keys `unit` (the text inserted into the document when indenting; usually set to N spaces or `"\t"` for tabs) and `tab-width` (the number of spaces rendered for a tab) |
67 | `language-servers` | The Language Servers used for this language. See below for more information in the section [Configuring Language Servers for a language](#configuring-language-servers-for-a-language) |
68 | `grammar` | The tree-sitter grammar to use (defaults to the value of `name`) |
69 | `formatter` | The formatter for the language, it will take precedence over the lsp when defined. The formatter must be able to take the original file as input from stdin and write the formatted file to stdout. The filename of the current buffer can be passed as argument by using the `%{buffer_name}` expansion variable. See below for more information in the [Configuring the formatter command](#configuring-the-formatter-command) |
70 | `soft-wrap` | [editor.softwrap](./editor.md#editorsoft-wrap-section)
71 | `text-width` | Maximum line length. Used for the `:reflow` command and soft-wrapping if `soft-wrap.wrap-at-text-width` is set, defaults to `editor.text-width` |
72 | `rulers` | Overrides the `editor.rulers` config key for the language. |
73 | `path-completion` | Overrides the `editor.path-completion` config key for the language. |
74 | `word-completion` | Overrides the [`editor.word-completion`](./editor.md#editorword-completion-section) configuration for the language. |
75 | `workspace-lsp-roots` | Directories (relative to the workspace root) that stop the upward root search early. Meant for project-specific hard overrides in a local `.helix/config.toml`; |
76 | `persistent-diagnostic-sources` | An array of LSP diagnostic sources assumed unchanged when the language server resends the same set of diagnostics. Helix can track the position for these diagnostics internally instead. Useful for diagnostics that are recomputed on save.
77 | `rainbow-brackets` | Overrides the `editor.rainbow-brackets` config key for the language |
78 | `code-actions-on-save` | List of LSP code actions to be run in order on save, for example `["source.organizeImports"]` |
79
80 ## Project and LSP root selection
81
82 This is the model Helix uses:
83
84 - The **workspace root** is found once by walking upward from the current
85 working directory and picking the first directory that contains `.git`, `.svn`,
86 `.jj`, or `.helix`. If none are found, the current working directory is the
87 workspace root.
88 - Root markers (`roots`) are used only for LSP root selection and are found by
89 starting at the **file**, not the folder Helix was opened in.
90 - We use the **topmost** directory that has a root marker (we stop the search at
91 the workspace root).
92 - In most cases, root markers are enough. In some repos there are multiple
93 nested root markers and whether you want the inner or outer one is project
94 specific. For these situations, use `workspace-lsp-roots` to stop the search
95 early in a particular directory.
96 - `workspace-lsp-roots` is meant to be set in the **project-specific** config:
97 `$PROJECT/.helix/config.toml`.
98
99 Interaction with `required-root-patterns` (a language_server configuration key):
100
101 - After the LSP root is selected, Helix checks for `required-root-patterns` in
102 that directory. If none match, the server is not started.
103 - This is validation, not root detection.
104
105 ### File-type detection and the `file-types` key
106
107 Helix determines which language configuration to use based on the `file-types` key
108 from the above section. `file-types` is a list of strings or tables, for
109 example:
110
111 ```toml
112 file-types = ["toml", { glob = "Makefile" }, { glob = ".git/config" }, { glob = ".github/workflows/*.yaml" } ]
113 ```
114
115 When determining a language configuration to use, Helix searches the file-types
116 with the following priorities:
117
118 1. Glob: values in `glob` tables are checked against the full path of the given
119 file. Globs are standard Unix-style path globs (e.g. the kind you use in Shell)
120 and can be used to match paths for a specific prefix, suffix, directory, etc.
121 In the above example, the `{ glob = "Makefile" }` config would match files
122 with the name `Makefile`, the `{ glob = ".git/config" }` config would match
123 `config` files in `.git` directories, and the `{ glob = ".github/workflows/*.yaml" }`
124 config would match any `yaml` files in `.github/workflow` directories. Note
125 that globs should always use the Unix path separator `/` even on Windows systems;
126 the matcher will automatically take the machine-specific separators into account.
127 If the glob isn't an absolute path or doesn't already start with a glob prefix,
128 `*/` will automatically be added to ensure it matches for any subdirectory.
129 2. Extension: if there are no glob matches, any `file-types` string that matches
130 the file extension of a given file wins. In the example above, the `"toml"`
131 config matches files like `Cargo.toml` or `languages.toml`.
132
133 ### Configuring the formatter command
134
135 [Command line expansions](./command-line.md#expansions) are supported in the arguments
136 of the formatter command. In particular, the `%{buffer_name}` variable can be passed as
137 argument to the formatter:
138
139 ```toml
140 formatter = { command = "mylang-formatter" , args = ["--stdin", "--stdin-filename", "%{buffer_name}"] }
141 ```
142
143 ### Configuring code actions on save
144
145 The `code-actions-on-save` key lists LSP code actions to run (in order) when
146 the buffer is saved. The available actions depend on available language servers,
147 below are common examples and may need adjusting for your setup.
148
149 ```toml
150 # Python with ruff
151 [[language]]
152 name = "python"
153 code-actions-on-save = ["source.organizeImports", "source.fixAll"]
154
155 # TS/JS with tsserver
156 [[language]]
157 name = "typescript"
158 code-actions-on-save = ["source.addMissingImports.ts"]
159
160 # TS/JS with eslint
161 [[language]]
162 name = "javascript"
163 code-actions-on-save = ["source.fixAll.eslint", "source.organizeImports"]
164 ```
165
166 ## Language Server configuration
167
168 Language servers are configured separately in the table `language-server` in the same file as the languages `languages.toml`
169
170 For example:
171
172 ```toml
173 [language-server.mylang-lsp]
174 command = "mylang-lsp"
175 args = ["--stdio"]
176 config = { provideFormatter = true }
177 environment = { "ENV1" = "value1", "ENV2" = "value2" }
178
179 [language-server.efm-lsp-prettier]
180 command = "efm-langserver"
181
182 [language-server.efm-lsp-prettier.config]
183 documentFormatting = true
184 languages = { typescript = [ { formatCommand ="prettier --stdin-filepath ${INPUT}", formatStdin = true } ] }
185 ```
186
187 These are the available options for a language server.
188
189 | Key | Description |
190 | ---- | ----------- |
191 | `command` | The name or path of the language server binary to execute. Binaries must be in `$PATH` |
192 | `args` | A list of arguments to pass to the language server binary |
193 | `config` | Language server initialization options |
194 | `timeout` | The maximum time a request to the language server may take, in seconds. Defaults to `20` |
195 | `environment` | Any environment variables that will be used when starting the language server `{ "KEY1" = "Value1", "KEY2" = "Value2" }` |
196 | `required-root-patterns` | A list of `glob` patterns to look for in the working directory of the lsp. The language server is only started if at least one of them is found. |
197
198 A `format` sub-table within `config` can be used to pass extra formatting options to
199 [Document Formatting Requests](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_formatting).
200 For example, with typescript:
201
202 ```toml
203 [language-server.typescript-language-server]
204 # pass format options according to https://github.com/typescript-language-server/typescript-language-server#workspacedidchangeconfiguration omitting the "[language].format." prefix.
205 config = { format = { "semicolons" = "insert", "insertSpaceBeforeFunctionParenthesis" = true } }
206 ```
207
208 ### Configuring Language Servers for a language
209
210 The `language-servers` attribute in a language tells helix which language servers are used for this language.
211
212 They have to be defined in the `[language-server]` table as described in the previous section.
213
214 Different languages can use the same language server instance, e.g. `typescript-language-server` is used for javascript, jsx, tsx and typescript by default.
215
216 The definition order of language servers affects the order in the results list of code action menu.
217
218 In case multiple language servers are specified in the `language-servers` attribute of a `language`,
219 it's often useful to only enable/disable certain language-server features for these language servers.
220
221 As an example, `efm-lsp-prettier` of the previous example is used only with a formatting command `prettier`,
222 so everything else should be handled by the `typescript-language-server` (which is configured by default).
223 The language configuration for typescript could look like this:
224
225 ```toml
226 [[language]]
227 name = "typescript"
228 language-servers = [ { name = "efm-lsp-prettier", only-features = [ "format" ] }, "typescript-language-server" ]
229 ```
230
231 or equivalent:
232
233 ```toml
234 [[language]]
235 name = "typescript"
236 language-servers = [ { name = "typescript-language-server", except-features = [ "format" ] }, "efm-lsp-prettier" ]
237 ```
238
239 Each requested LSP feature is prioritized in the order of the `language-servers` array.
240 For example, the first `goto-definition` supported language server (in this case `typescript-language-server`) will be taken for the relevant LSP request (command `goto_definition`).
241 The features `diagnostics`, `code-action`, `completion`, `document-symbols` and `workspace-symbols` are an exception to that rule, as they are working for all language servers at the same time and are merged together, if enabled for the language.
242 If no `except-features` or `only-features` is given, all features for the language server are enabled.
243 If a language server itself doesn't support a feature, the next language server array entry will be tried (and so on).
244
245 The list of supported features is:
246
247 - `format`
248 - `goto-declaration`
249 - `goto-definition`
250 - `goto-type-definition`
251 - `goto-reference`
252 - `goto-implementation`
253 - `signature-help`
254 - `hover`
255 - `document-highlight`
256 - `completion`
257 - `code-action`
258 - `document-links`
259 - `workspace-command`
260 - `document-symbols`
261 - `workspace-symbols`
262 - `diagnostics`
263 - `pull-diagnostics`
264 - `rename-symbol`
265 - `inlay-hints`
266 - `document-colors`
267 - `call-hierarchy`
268
269 ## Tree-sitter grammar configuration
270
271 The source for a language's tree-sitter grammar is specified in a `[[grammar]]`
272 section in `languages.toml`. For example:
273
274 ```toml
275 [[grammar]]
276 name = "mylang"
277 source = { git = "https://github.com/example/mylang", rev = "a250c4582510ff34767ec3b7dcdd3c24e8c8aa68" }
278 ```
279
280 Grammar configuration takes these keys:
281
282 | Key | Description |
283 | --- | ----------- |
284 | `name` | The name of the tree-sitter grammar |
285 | `source` | The method of fetching the grammar - a table with a schema defined below |
286
287 Where `source` is a table with either these keys when using a grammar from a
288 git repository:
289
290 | Key | Description |
291 | --- | ----------- |
292 | `git` | A git remote URL from which the grammar should be cloned |
293 | `rev` | The revision (commit hash or tag) which should be fetched |
294 | `subpath` | A path within the grammar directory which should be built. Some grammar repositories host multiple grammars (for example `tree-sitter-typescript` and `tree-sitter-ocaml`) in subdirectories. This key is used to point `hx --grammar build` to the correct path for compilation. When omitted, the root of repository is used |
295
296 ### Choosing grammars
297
298 You may use a top-level `use-grammars` key to control which grammars are
299 fetched and built when using `hx --grammar fetch` and `hx --grammar build`.
300
301 ```toml
302 # Note: this key must come **before** the [[language]] and [[grammar]] sections
303 use-grammars = { only = [ "rust", "c", "cpp" ] }
304 # or
305 use-grammars = { except = [ "yaml", "json" ] }
306 ```
307
308 When omitted, all grammars are fetched and built.
309
310 [treesitter-language-injection]: https://tree-sitter.github.io/tree-sitter/3-syntax-highlighting.html#language-injection