languages.md

  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- `modeline_aliases` is an array of additional Emacs modes or Vim filetypes to map modeline settings to Zed language.
 36- `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.
 37
 38<!--
 39TBD: Document `language_name/config.toml` keys
 40
 41- autoclose_before
 42- brackets (start, end, close, newline, not_in: ["comment", "string"])
 43- word_characters
 44- prettier_parser_name
 45- opt_into_language_servers
 46- code_fence_block_name
 47- scope_opt_in_language_servers
 48- increase_indent_pattern, decrease_indent_pattern
 49- collapsed_placeholder
 50- auto_indent_on_paste, auto_indent_using_last_non_empty_line
 51- overrides: `[overrides.element]`, `[overrides.string]`
 52-->
 53
 54## Grammar
 55
 56Zed 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/3-writing-the-grammar.html). 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:
 57
 58```toml
 59[grammars.gleam]
 60repository = "https://github.com/gleam-lang/tree-sitter-gleam"
 61rev = "58b7cac8fc14c92b0677c542610d8738c373fa81"
 62```
 63
 64The `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.
 65
 66## Tree-sitter Queries
 67
 68Zed uses the syntax tree produced by the [Tree-sitter](https://tree-sitter.github.io) query language to implement
 69several features:
 70
 71- Syntax highlighting
 72- Bracket matching
 73- Code outline/structure
 74- Auto-indentation
 75- Code injections
 76- Syntax overrides
 77- Text redactions
 78- Runnable code detection
 79- Selecting classes, functions, etc.
 80
 81The following sections elaborate on how [Tree-sitter queries](https://tree-sitter.github.io/tree-sitter/using-parsers/queries/index.html) enable these
 82features in Zed, using [JSON syntax](https://www.json.org/json-en.html) as a guiding example.
 83
 84### Syntax highlighting
 85
 86In Tree-sitter, the `highlights.scm` file defines syntax highlighting rules for a particular syntax.
 87
 88Here's an example from a `highlights.scm` for JSON:
 89
 90```scheme
 91(string) @string
 92
 93(pair
 94  key: (string) @property.json_key)
 95
 96(number) @number
 97```
 98
 99This query marks strings, object keys, and numbers for highlighting. The following is the full list of captures supported by themes:
100
101| Capture                  | Description                            |
102| ------------------------ | -------------------------------------- |
103| @attribute               | Captures attributes                    |
104| @boolean                 | Captures boolean values                |
105| @comment                 | Captures comments                      |
106| @comment.doc             | Captures documentation comments        |
107| @constant                | Captures constants                     |
108| @constant.builtin        | Captures built-in constants            |
109| @constructor             | Captures constructors                  |
110| @embedded                | Captures embedded content              |
111| @emphasis                | Captures emphasized text               |
112| @emphasis.strong         | Captures strongly emphasized text      |
113| @enum                    | Captures enumerations                  |
114| @function                | Captures functions                     |
115| @hint                    | Captures hints                         |
116| @keyword                 | Captures keywords                      |
117| @label                   | Captures labels                        |
118| @link_text               | Captures link text                     |
119| @link_uri                | Captures link URIs                     |
120| @number                  | Captures numeric values                |
121| @operator                | Captures operators                     |
122| @predictive              | Captures predictive text               |
123| @preproc                 | Captures preprocessor directives       |
124| @primary                 | Captures primary elements              |
125| @property                | Captures properties                    |
126| @punctuation             | Captures punctuation                   |
127| @punctuation.bracket     | Captures brackets                      |
128| @punctuation.delimiter   | Captures delimiters                    |
129| @punctuation.list_marker | Captures list markers                  |
130| @punctuation.special     | Captures special punctuation           |
131| @string                  | Captures string literals               |
132| @string.escape           | Captures escaped characters in strings |
133| @string.regex            | Captures regular expressions           |
134| @string.special          | Captures special strings               |
135| @string.special.symbol   | Captures special symbols               |
136| @tag                     | Captures tags                          |
137| @tag.doctype             | Captures doctypes (e.g., in HTML)      |
138| @text.literal            | Captures literal text                  |
139| @title                   | Captures titles                        |
140| @type                    | Captures types                         |
141| @type.builtin            | Captures built-in types                |
142| @variable                | Captures variables                     |
143| @variable.special        | Captures special variables             |
144| @variable.parameter      | Captures function/method parameters    |
145| @variant                 | Captures variants                      |
146
147### Bracket matching
148
149The `brackets.scm` file defines matching brackets.
150
151Here's an example from a `brackets.scm` file for JSON:
152
153```scheme
154("[" @open "]" @close)
155("{" @open "}" @close)
156("\"" @open "\"" @close)
157```
158
159This query identifies opening and closing brackets, braces, and quotation marks.
160
161| Capture | Description                                   |
162| ------- | --------------------------------------------- |
163| @open   | Captures opening brackets, braces, and quotes |
164| @close  | Captures closing brackets, braces, and quotes |
165
166Zed 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.
167
168To opt out of rainbow brackets colorization, add the following to the corresponding `brackets.scm` entry:
169
170```scheme
171(("\"" @open "\"" @close) (#set! rainbow.exclude))
172```
173
174### Code outline/structure
175
176The `outline.scm` file defines the structure for the code outline.
177
178Here's an example from an `outline.scm` file for JSON:
179
180```scheme
181(pair
182  key: (string (string_content) @name)) @item
183```
184
185This query captures object keys for the outline structure.
186
187| Capture        | Description                                                                          |
188| -------------- | ------------------------------------------------------------------------------------ |
189| @name          | Captures the content of object keys                                                  |
190| @item          | Captures the entire key-value pair                                                   |
191| @context       | Captures elements that provide context for the outline item                          |
192| @context.extra | Captures additional contextual information for the outline item                      |
193| @annotation    | Captures nodes that annotate outline item (doc comments, attributes, decorators)[^1] |
194
195[^1]: These annotations are used by Assistant when generating code modification steps.
196
197### Auto-indentation
198
199The `indents.scm` file defines indentation rules.
200
201Here's an example from an `indents.scm` file for JSON:
202
203```scheme
204(array "]" @end) @indent
205(object "}" @end) @indent
206```
207
208This query marks the end of arrays and objects for indentation purposes.
209
210| Capture | Description                                        |
211| ------- | -------------------------------------------------- |
212| @end    | Captures closing brackets and braces               |
213| @indent | Captures entire arrays and objects for indentation |
214
215### Code injections
216
217The `injections.scm` file defines rules for embedding one language within another, such as code blocks in Markdown or SQL queries in Python strings.
218
219Here's an example from an `injections.scm` file for Markdown:
220
221```scheme
222(fenced_code_block
223  (info_string
224    (language) @injection.language)
225  (code_fence_content) @injection.content)
226
227((inline) @content
228 (#set! injection.language "markdown-inline"))
229```
230
231This 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".
232
233| Capture             | Description                                                |
234| ------------------- | ---------------------------------------------------------- |
235| @injection.language | Captures the language identifier for a code block          |
236| @injection.content  | Captures the content to be treated as a different language |
237
238Note that we couldn't use JSON as an example here because it doesn't support language injections.
239
240### Syntax overrides
241
242The `overrides.scm` file defines syntactic _scopes_ that can be used to override certain editor settings within specific language constructs.
243
244For 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.
245
246There 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:
247
248```scheme
249[
250  (string)
251  (template_string)
252] @string
253```
254
255And the JavaScript `config.toml` contains this setting:
256
257```toml
258word_characters = ["#", "$"]
259
260[overrides.string]
261completion_query_characters = ["-"]
262```
263
264You 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`:
265
266```toml
267brackets = [
268  { start = "'", end = "'", close = true, newline = false, not_in = ["string"] },
269  # other pairs...
270]
271```
272
273#### Range inclusivity
274
275By 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.
276
277For 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:
278
279```scheme
280(comment) @comment.inclusive
281```
282
283### Text objects
284
285The `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.
286
287Vim 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.
288
289For 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.
290
291For 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.
292
293If 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.
294
295| Capture          | Description                                                             | Vim mode                                         |
296| ---------------- | ----------------------------------------------------------------------- | ------------------------------------------------ |
297| @function.around | An entire function definition or equivalent small section of a file.    | `[m`, `]m`, `[M`,`]M` motions. `af` text object  |
298| @function.inside | The function body (the stuff within the braces).                        | `if` text object                                 |
299| @class.around    | An entire class definition or equivalent large section of a file.       | `[[`, `]]`, `[]`, `][` motions. `ac` text object |
300| @class.inside    | The contents of a class definition.                                     | `ic` text object                                 |
301| @comment.around  | An entire comment (e.g. all adjacent line comments, or a block comment) | `gc` text object                                 |
302| @comment.inside  | The contents of a comment                                               | `igc` text object (rarely supported)             |
303
304For example:
305
306```scheme
307; include only the content of the method in the function
308(method_definition
309    body: (_
310        "{"
311        (_)* @function.inside
312        "}")) @function.around
313
314; match function.around for declarations with no body
315(function_signature_item) @function.around
316
317; join all adjacent comments into one
318(comment)+ @comment.around
319```
320
321### Text redactions
322
323The `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.
324
325Here's an example from a `redactions.scm` file for JSON:
326
327```scheme
328(pair value: (number) @redact)
329(pair value: (string) @redact)
330(array (number) @redact)
331(array (string) @redact)
332```
333
334This query marks number and string values in key-value pairs and arrays for redaction.
335
336| Capture | Description                    |
337| ------- | ------------------------------ |
338| @redact | Captures values to be redacted |
339
340### Runnable code detection
341
342The `runnables.scm` file defines rules for detecting runnable code.
343
344Here's an example from a `runnables.scm` file for JSON:
345
346```scheme
347(
348    (document
349        (object
350            (pair
351                key: (string
352                    (string_content) @_name
353                    (#eq? @_name "scripts")
354                )
355                value: (object
356                    (pair
357                        key: (string (string_content) @run @script)
358                    )
359                )
360            )
361        )
362    )
363    (#set! tag package-script)
364    (#set! tag composer-script)
365)
366```
367
368This query detects runnable scripts in package.json and composer.json files.
369
370The `@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.
371
372| Capture | Description                                            |
373| ------- | ------------------------------------------------------ |
374| @\_name | Captures the "scripts" key                             |
375| @run    | Captures the script name                               |
376| @script | Also captures the script name (for different purposes) |
377
378<!--
379TBD: `#set! tag`
380-->
381
382## Language Servers
383
384Zed uses the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) to provide advanced language support.
385
386An 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:
387
388```toml
389[language_servers.my-language-server]
390name = "My Language LSP"
391languages = ["My Language"]
392```
393
394Then, in the Rust code for your extension, implement the `language_server_command` method on your extension:
395
396```rust
397impl zed::Extension for MyExtension {
398    fn language_server_command(
399        &mut self,
400        language_server_id: &LanguageServerId,
401        worktree: &zed::Worktree,
402    ) -> Result<zed::Command> {
403        Ok(zed::Command {
404            command: get_path_to_language_server_executable()?,
405            args: get_args_for_language_server()?,
406            env: get_env_for_language_server()?,
407        })
408    }
409}
410```
411
412You 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).
413
414### Syntax Highlighting with Semantic Tokens
415
416Zed 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:
417
418```json [settings]
419{
420  // Enable semantic tokens globally, backed by tree-sitter highlights for each language:
421  "semantic_tokens": "combined",
422  // Or, specify per-language:
423  "languages": {
424    "Rust": {
425      // No tree-sitter, only LSP semantic tokens:
426      "semantic_tokens": "full"
427    }
428  }
429}
430```
431
432The `semantic_tokens` setting accepts the following values:
433
434- `"off"` (default): Do not request semantic tokens from language servers.
435- `"combined"`: Use LSP semantic tokens together with tree-sitter highlighting.
436- `"full"`: Use LSP semantic tokens exclusively, replacing tree-sitter highlighting.
437
438#### Extension-Provided Semantic Token Rules
439
440Language extensions can ship default semantic token rules for their language server's custom token types. To do this, place a `semantic_token_rules.json` file in the language directory alongside `config.toml`:
441
442```
443my-extension/
444  languages/
445    my-language/
446      config.toml
447      highlights.scm
448      semantic_token_rules.json
449```
450
451The file uses the same format as the `semantic_token_rules` array in user settings — a JSON array of rule objects:
452
453```json
454[
455  {
456    "token_type": "lifetime",
457    "style": ["lifetime"]
458  },
459  {
460    "token_type": "builtinType",
461    "style": ["type"]
462  },
463  {
464    "token_type": "selfKeyword",
465    "style": ["variable.special"]
466  }
467]
468```
469
470This is useful when a language server reports custom (non-standard) semantic token types that aren't covered by Zed's built-in default rules. Extension-provided rules act as sensible defaults for that language — users can always override them via `semantic_token_rules` in their settings file, and built-in default rules are only used when neither user nor extension rules match.
471
472#### Customizing Semantic Token Styles
473
474Zed 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.
475
476```json [settings]
477{
478  "global_lsp_settings": {
479    "semantic_token_rules": [
480      {
481        // Highlight macros as keywords.
482        "token_type": "macro",
483        "style": ["syntax.keyword"]
484      },
485      {
486        // Highlight unresolved references in bold red.
487        "token_type": "unresolvedReference",
488        "foreground_color": "#c93f3f",
489        "font_weight": "bold"
490      },
491      {
492        // Underline all mutable variables/references/etc.
493        "token_modifiers": ["mutable"],
494        "underline": true
495      }
496    ]
497  }
498}
499```
500
501All 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.
502
503Rules are applied in the following priority order (highest to lowest):
504
5051. **User settings** — rules from `semantic_token_rules` in your settings file.
5062. **Extension rules** — rules from `semantic_token_rules.json` in extension language directories.
5073. **Default rules** — Zed's built-in rules for standard LSP token types.
508
509Each rule in the `semantic_token_rules` array is defined as follows:
510
511- `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.
512- `token_modifiers`: A list of semantic token modifiers to match. All modifiers must be present to match.
513- `style`: A list of styles from the current syntax theme to use. The first style found is used. Any settings below override that style.
514- `foreground_color`: The foreground color to use for the token type, in hex format (e.g., `"#ff0000"`).
515- `background_color`: The background color to use for the token type, in hex format (e.g., `"#ff0000"`).
516- `underline`: A boolean or color to underline with, in hex format. If `true`, then the token will be underlined with the text color.
517- `strikethrough`: A boolean or color to strikethrough with, in hex format. If `true`, then the token have a strikethrough with the text color.
518- `font_weight`: One of `"normal"`, `"bold"`.
519- `font_style`: One of `"normal"`, `"italic"`.
520
521### Multi-Language Support
522
523If 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:
524
525```toml
526
527[language-servers.my-language-server]
528name = "Whatever LSP"
529languages = ["JavaScript", "HTML", "CSS"]
530
531[language-servers.my-language-server.language_ids]
532"JavaScript" = "javascript"
533"TSX" = "typescriptreact"
534"HTML" = "html"
535"CSS" = "css"
536```