1---
2title: Language Extensions
3description: "Overview of programming language support in Zed, including built-in and extension-based languages."
4---
5
6# Language Extensions
7
8Language support in Zed has several components:
9
10- Language metadata and configuration
11- Grammar
12- Queries
13- Language servers
14
15## Language Metadata
16
17Each language supported by Zed must be defined in a subdirectory inside the `languages` directory of your extension.
18
19This subdirectory must contain a file called `config.toml` file with the following structure:
20
21```toml
22name = "My Language"
23grammar = "my-language"
24path_suffixes = ["myl"]
25line_comments = ["# "]
26```
27
28- `name` (required) is the human readable name that will show up in the Select Language dropdown.
29- `grammar` (required) is the name of a grammar. Grammars are registered separately, described below.
30- `path_suffixes` is an array of file suffixes that should be associated with this language. Unlike `file_types` in settings, this does not support glob patterns.
31- `line_comments` is an array of strings that are used to identify line comments in the language. This is used for the `editor::ToggleComments` keybind: {#kb editor::ToggleComments} for toggling lines of code.
32- `tab_size` defines the indentation/tab size used for this language (default is `4`).
33- `hard_tabs` whether to indent with tabs (`true`) or spaces (`false`, the default).
34- `first_line_pattern` is a regular expression that can be used alongside `path_suffixes` (above) or `file_types` in settings to match files that should use this language. For example, Zed uses this to identify Shell Scripts by matching [shebang lines](https://github.com/zed-industries/zed/blob/main/crates/languages/src/bash/config.toml) in the first line of a script.
35- `debuggers` is an array of strings that are used to identify debuggers in the language. When launching a debugger's `New Process Modal`, Zed will order available debuggers by the order of entries in this array.
36
37<!--
38TBD: Document `language_name/config.toml` keys
39
40- autoclose_before
41- brackets (start, end, close, newline, not_in: ["comment", "string"])
42- word_characters
43- prettier_parser_name
44- opt_into_language_servers
45- code_fence_block_name
46- scope_opt_in_language_servers
47- increase_indent_pattern, decrease_indent_pattern
48- collapsed_placeholder
49- auto_indent_on_paste, auto_indent_using_last_non_empty_line
50- overrides: `[overrides.element]`, `[overrides.string]`
51-->
52
53## Grammar
54
55Zed uses the [Tree-sitter](https://tree-sitter.github.io) parsing library to provide built-in language-specific features. There are grammars available for many languages, and you can also [develop your own grammar](https://tree-sitter.github.io/tree-sitter/creating-parsers#writing-the-grammar). A growing list of Zed features are built using pattern matching over syntax trees with Tree-sitter queries. As mentioned above, every language that is defined in an extension must specify the name of a Tree-sitter grammar that is used for parsing. These grammars are then registered separately in extensions' `extension.toml` file, like this:
56
57```toml
58[grammars.gleam]
59repository = "https://github.com/gleam-lang/tree-sitter-gleam"
60rev = "58b7cac8fc14c92b0677c542610d8738c373fa81"
61```
62
63The `repository` field must specify a repository where the Tree-sitter grammar should be loaded from, and the `rev` field must contain a Git revision to use, such as the SHA of a Git commit. If you're developing an extension locally and want to load a grammar from the local filesystem, you can use a `file://` URL for `repository`. An extension can provide multiple grammars by referencing multiple tree-sitter repositories.
64
65## Tree-sitter Queries
66
67Zed uses the syntax tree produced by the [Tree-sitter](https://tree-sitter.github.io) query language to implement
68several features:
69
70- Syntax highlighting
71- Bracket matching
72- Code outline/structure
73- Auto-indentation
74- Code injections
75- Syntax overrides
76- Text redactions
77- Runnable code detection
78- Selecting classes, functions, etc.
79
80The following sections elaborate on how [Tree-sitter queries](https://tree-sitter.github.io/tree-sitter/using-parsers/queries/index.html) enable these
81features in Zed, using [JSON syntax](https://www.json.org/json-en.html) as a guiding example.
82
83### Syntax highlighting
84
85In Tree-sitter, the `highlights.scm` file defines syntax highlighting rules for a particular syntax.
86
87Here's an example from a `highlights.scm` for JSON:
88
89```scheme
90(string) @string
91
92(pair
93 key: (string) @property.json_key)
94
95(number) @number
96```
97
98This query marks strings, object keys, and numbers for highlighting. The following is the full list of captures supported by themes:
99
100| Capture | Description |
101| ------------------------ | -------------------------------------- |
102| @attribute | Captures attributes |
103| @boolean | Captures boolean values |
104| @comment | Captures comments |
105| @comment.doc | Captures documentation comments |
106| @constant | Captures constants |
107| @constant.builtin | Captures built-in constants |
108| @constructor | Captures constructors |
109| @embedded | Captures embedded content |
110| @emphasis | Captures emphasized text |
111| @emphasis.strong | Captures strongly emphasized text |
112| @enum | Captures enumerations |
113| @function | Captures functions |
114| @hint | Captures hints |
115| @keyword | Captures keywords |
116| @label | Captures labels |
117| @link_text | Captures link text |
118| @link_uri | Captures link URIs |
119| @number | Captures numeric values |
120| @operator | Captures operators |
121| @predictive | Captures predictive text |
122| @preproc | Captures preprocessor directives |
123| @primary | Captures primary elements |
124| @property | Captures properties |
125| @punctuation | Captures punctuation |
126| @punctuation.bracket | Captures brackets |
127| @punctuation.delimiter | Captures delimiters |
128| @punctuation.list_marker | Captures list markers |
129| @punctuation.special | Captures special punctuation |
130| @string | Captures string literals |
131| @string.escape | Captures escaped characters in strings |
132| @string.regex | Captures regular expressions |
133| @string.special | Captures special strings |
134| @string.special.symbol | Captures special symbols |
135| @tag | Captures tags |
136| @tag.doctype | Captures doctypes (e.g., in HTML) |
137| @text.literal | Captures literal text |
138| @title | Captures titles |
139| @type | Captures types |
140| @type.builtin | Captures built-in types |
141| @variable | Captures variables |
142| @variable.special | Captures special variables |
143| @variable.parameter | Captures function/method parameters |
144| @variant | Captures variants |
145
146### Bracket matching
147
148The `brackets.scm` file defines matching brackets.
149
150Here's an example from a `brackets.scm` file for JSON:
151
152```scheme
153("[" @open "]" @close)
154("{" @open "}" @close)
155("\"" @open "\"" @close)
156```
157
158This query identifies opening and closing brackets, braces, and quotation marks.
159
160| Capture | Description |
161| ------- | --------------------------------------------- |
162| @open | Captures opening brackets, braces, and quotes |
163| @close | Captures closing brackets, braces, and quotes |
164
165Zed uses these to highlight matching brackets: painting each bracket pair with a different color ("rainbow brackets") and highlighting the brackets if the cursor is inside the bracket pair.
166
167To opt out of rainbow brackets colorization, add the following to the corresponding `brackets.scm` entry:
168
169```scheme
170(("\"" @open "\"" @close) (#set! rainbow.exclude))
171```
172
173### Code outline/structure
174
175The `outline.scm` file defines the structure for the code outline.
176
177Here's an example from an `outline.scm` file for JSON:
178
179```scheme
180(pair
181 key: (string (string_content) @name)) @item
182```
183
184This query captures object keys for the outline structure.
185
186| Capture | Description |
187| -------------- | ------------------------------------------------------------------------------------ |
188| @name | Captures the content of object keys |
189| @item | Captures the entire key-value pair |
190| @context | Captures elements that provide context for the outline item |
191| @context.extra | Captures additional contextual information for the outline item |
192| @annotation | Captures nodes that annotate outline item (doc comments, attributes, decorators)[^1] |
193
194[^1]: These annotations are used by Assistant when generating code modification steps.
195
196### Auto-indentation
197
198The `indents.scm` file defines indentation rules.
199
200Here's an example from an `indents.scm` file for JSON:
201
202```scheme
203(array "]" @end) @indent
204(object "}" @end) @indent
205```
206
207This query marks the end of arrays and objects for indentation purposes.
208
209| Capture | Description |
210| ------- | -------------------------------------------------- |
211| @end | Captures closing brackets and braces |
212| @indent | Captures entire arrays and objects for indentation |
213
214### Code injections
215
216The `injections.scm` file defines rules for embedding one language within another, such as code blocks in Markdown or SQL queries in Python strings.
217
218Here's an example from an `injections.scm` file for Markdown:
219
220```scheme
221(fenced_code_block
222 (info_string
223 (language) @injection.language)
224 (code_fence_content) @injection.content)
225
226((inline) @content
227 (#set! injection.language "markdown-inline"))
228```
229
230This query identifies fenced code blocks, capturing the language specified in the info string and the content within the block. It also captures inline content and sets its language to "markdown-inline".
231
232| Capture | Description |
233| ------------------- | ---------------------------------------------------------- |
234| @injection.language | Captures the language identifier for a code block |
235| @injection.content | Captures the content to be treated as a different language |
236
237Note that we couldn't use JSON as an example here because it doesn't support language injections.
238
239### Syntax overrides
240
241The `overrides.scm` file defines syntactic _scopes_ that can be used to override certain editor settings within specific language constructs.
242
243For example, there is a language-specific setting called `word_characters` that controls which non-alphabetic characters are considered part of a word, for example when you double click to select a variable. In JavaScript, "$" and "#" are considered word characters.
244
245There is also a language-specific setting called `completion_query_characters` that controls which characters trigger autocomplete suggestions. In JavaScript, when your cursor is within a _string_, `-` should be considered a completion query character. To achieve this, the JavaScript `overrides.scm` file contains the following pattern:
246
247```scheme
248[
249 (string)
250 (template_string)
251] @string
252```
253
254And the JavaScript `config.toml` contains this setting:
255
256```toml
257word_characters = ["#", "$"]
258
259[overrides.string]
260completion_query_characters = ["-"]
261```
262
263You can also disable certain auto-closing brackets in a specific scope. For example, to prevent auto-closing `'` within strings, you could put the following in the JavaScript `config.toml`:
264
265```toml
266brackets = [
267 { start = "'", end = "'", close = true, newline = false, not_in = ["string"] },
268 # other pairs...
269]
270```
271
272#### Range inclusivity
273
274By default, the ranges defined in `overrides.scm` are _exclusive_. So in the case above, if your cursor was _outside_ the quotation marks delimiting the string, the `string` scope would not take effect. Sometimes, you may want to make the range _inclusive_. You can do this by adding the `.inclusive` suffix to the capture name in the query.
275
276For example, in JavaScript, we also disable auto-closing of single quotes within comments. And the comment scope must extend all the way to the newline after a line comment. To achieve this, the JavaScript `overrides.scm` contains the following pattern:
277
278```scheme
279(comment) @comment.inclusive
280```
281
282### Text objects
283
284The `textobjects.scm` file defines rules for navigating by text objects. This was added in Zed v0.165 and is currently used only in Vim mode.
285
286Vim provides two levels of granularity for navigating around files. Section-by-section with `[]` etc., and method-by-method with `]m` etc. Even languages that don't support functions and classes can work well by defining similar concepts. For example CSS defines a rule-set as a method, and a media-query as a class.
287
288For languages with closures, these typically should not count as functions in Zed. This is best-effort, however, because languages like JavaScript do not syntactically differentiate between closures and top-level function declarations.
289
290For languages with declarations like C, provide queries that match `@class.around` or `@function.around`. The `if` and `ic` text objects will default to these if there is no inside.
291
292If you are not sure what to put in textobjects.scm, both [nvim-treesitter-textobjects](https://github.com/nvim-treesitter/nvim-treesitter-textobjects), and the [Helix editor](https://github.com/helix-editor/helix) have queries for many languages. You can refer to the Zed [built-in languages](https://github.com/zed-industries/zed/tree/main/crates/languages/src) to see how to adapt these.
293
294| Capture | Description | Vim mode |
295| ---------------- | ----------------------------------------------------------------------- | ------------------------------------------------ |
296| @function.around | An entire function definition or equivalent small section of a file. | `[m`, `]m`, `[M`,`]M` motions. `af` text object |
297| @function.inside | The function body (the stuff within the braces). | `if` text object |
298| @class.around | An entire class definition or equivalent large section of a file. | `[[`, `]]`, `[]`, `][` motions. `ac` text object |
299| @class.inside | The contents of a class definition. | `ic` text object |
300| @comment.around | An entire comment (e.g. all adjacent line comments, or a block comment) | `gc` text object |
301| @comment.inside | The contents of a comment | `igc` text object (rarely supported) |
302
303For example:
304
305```scheme
306; include only the content of the method in the function
307(method_definition
308 body: (_
309 "{"
310 (_)* @function.inside
311 "}")) @function.around
312
313; match function.around for declarations with no body
314(function_signature_item) @function.around
315
316; join all adjacent comments into one
317(comment)+ @comment.around
318```
319
320### Text redactions
321
322The `redactions.scm` file defines text redaction rules. When collaborating and sharing your screen, it makes sure that certain syntax nodes are rendered in a redacted mode to avoid them from leaking.
323
324Here's an example from a `redactions.scm` file for JSON:
325
326```scheme
327(pair value: (number) @redact)
328(pair value: (string) @redact)
329(array (number) @redact)
330(array (string) @redact)
331```
332
333This query marks number and string values in key-value pairs and arrays for redaction.
334
335| Capture | Description |
336| ------- | ------------------------------ |
337| @redact | Captures values to be redacted |
338
339### Runnable code detection
340
341The `runnables.scm` file defines rules for detecting runnable code.
342
343Here's an example from a `runnables.scm` file for JSON:
344
345```scheme
346(
347 (document
348 (object
349 (pair
350 key: (string
351 (string_content) @_name
352 (#eq? @_name "scripts")
353 )
354 value: (object
355 (pair
356 key: (string (string_content) @run @script)
357 )
358 )
359 )
360 )
361 )
362 (#set! tag package-script)
363 (#set! tag composer-script)
364)
365```
366
367This query detects runnable scripts in package.json and composer.json files.
368
369The `@run` capture specifies where the run button should appear in the editor. Other captures, except those prefixed with an underscore, are exposed as environment variables with a prefix of `ZED_CUSTOM_$(capture_name)` when running the code.
370
371| Capture | Description |
372| ------- | ------------------------------------------------------ |
373| @\_name | Captures the "scripts" key |
374| @run | Captures the script name |
375| @script | Also captures the script name (for different purposes) |
376
377<!--
378TBD: `#set! tag`
379-->
380
381## Language Servers
382
383Zed uses the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) to provide advanced language support.
384
385An extension may provide any number of language servers. To provide a language server from your extension, add an entry to your `extension.toml` with the name of your language server and the language(s) it applies to. The entry in the list of `languages` has to match the `name` field from the `config.toml` file for that language:
386
387```toml
388[language_servers.my-language-server]
389name = "My Language LSP"
390languages = ["My Language"]
391```
392
393Then, in the Rust code for your extension, implement the `language_server_command` method on your extension:
394
395```rust
396impl zed::Extension for MyExtension {
397 fn language_server_command(
398 &mut self,
399 language_server_id: &LanguageServerId,
400 worktree: &zed::Worktree,
401 ) -> Result<zed::Command> {
402 Ok(zed::Command {
403 command: get_path_to_language_server_executable()?,
404 args: get_args_for_language_server()?,
405 env: get_env_for_language_server()?,
406 })
407 }
408}
409```
410
411You can customize the handling of the language server using several optional methods in the `Extension` trait. For example, you can control how completions are styled using the `label_for_completion` method. For a complete list of methods, see the [API docs for the Zed extension API](https://docs.rs/zed_extension_api).
412
413### Syntax Highlighting with Semantic Tokens
414
415Zed supports syntax highlighting using semantic tokens from the attached language servers. This is currently disabled by default, but can be enabled in your settings file:
416
417```json [settings]
418{
419 // Enable semantic tokens globally, backed by tree-sitter highlights for each language:
420 "semantic_tokens": "combined",
421 // Or, specify per-language:
422 "languages": {
423 "Rust": {
424 // No tree-sitter, only LSP semantic tokens:
425 "semantic_tokens": "full"
426 }
427 }
428}
429```
430
431The `semantic_tokens` setting accepts the following values:
432
433- `"off"` (default): Do not request semantic tokens from language servers.
434- `"combined"`: Use LSP semantic tokens together with tree-sitter highlighting.
435- `"full"`: Use LSP semantic tokens exclusively, replacing tree-sitter highlighting.
436
437#### Customizing Semantic Token Styles
438
439Zed supports customizing the styles used for semantic tokens. You can define rules in your settings file, which customize how semantic tokens get mapped to styles in your theme.
440
441```json [settings]
442{
443 "global_lsp_settings": {
444 "semantic_token_rules": [
445 {
446 // Highlight macros as keywords.
447 "token_type": "macro",
448 "style": ["syntax.keyword"]
449 },
450 {
451 // Highlight unresolved references in bold red.
452 "token_type": "unresolvedReference",
453 "foreground_color": "#c93f3f",
454 "font_weight": "bold"
455 },
456 {
457 // Underline all mutable variables/references/etc.
458 "token_modifiers": ["mutable"],
459 "underline": true
460 }
461 ]
462 }
463}
464```
465
466All rules that match a given `token_type` and `token_modifiers` are applied. Earlier rules take precedence. If no rules match, the token is not highlighted. User-defined rules take priority over the default rules.
467
468Each rule in the `semantic_token_rules` array is defined as follows:
469
470- `token_type`: The semantic token type as defined by the [LSP specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens). If omitted, the rule matches all token types.
471- `token_modifiers`: A list of semantic token modifiers to match. All modifiers must be present to match.
472- `style`: A list of styles from the current syntax theme to use. The first style found is used. Any settings below override that style.
473- `foreground_color`: The foreground color to use for the token type, in hex format (e.g., `"#ff0000"`).
474- `background_color`: The background color to use for the token type, in hex format (e.g., `"#ff0000"`).
475- `underline`: A boolean or color to underline with, in hex format. If `true`, then the token will be underlined with the text color.
476- `strikethrough`: A boolean or color to strikethrough with, in hex format. If `true`, then the token have a strikethrough with the text color.
477- `font_weight`: One of `"normal"`, `"bold"`.
478- `font_style`: One of `"normal"`, `"italic"`.
479
480### Multi-Language Support
481
482If your language server supports additional languages, you can use `language_ids` to map Zed `languages` to the desired [LSP-specific `languageId`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem) identifiers:
483
484```toml
485
486[language-servers.my-language-server]
487name = "Whatever LSP"
488languages = ["JavaScript", "HTML", "CSS"]
489
490[language-servers.my-language-server.language_ids]
491"JavaScript" = "javascript"
492"TSX" = "typescriptreact"
493"HTML" = "html"
494"CSS" = "css"
495```