This documentation is under construction. Pages can be missing or change at any time. Follow it on GitHub.

Skip to content

Use Phem in Your Editor

The Phem language server (phemc lsp) shows phemc check errors as you type, and adds completion, go to definition, find references, rename, formatting and hover to .phem files. For coding agents, see Use Phem with coding agents.

Choose an Editor#

Editor Install Server Closing tag as you type Open Compiled Markup colors
VS Code Marketplace extension Bundled Yes Yes TextMate grammar and semantic tokens
PhpStorm JetBrains Marketplace plugin Bundled, or a phemc binary Yes Yes TextMate grammar and semantic tokens
Zed Zed extension vendor/bin/phemc Yes No Tree-sitter grammar, and semantic tokens with a setting
Neovim Config vendor/bin/phemc Yes, with the config No Tree-sitter grammar and semantic tokens
Helix Config vendor/bin/phemc No No Tree-sitter grammar

The VS Code extension and the PhpStorm plugin bundle the server compiled to WebAssembly, so they don't need a phemc binary. The other editors run your app's vendor/bin/phemc lsp, so the server always matches your compiler and runtime version.

VS Code#

Install the yceruto.phem extension from the Visual Studio Marketplace. It includes the server, so you don't need phemc, PHP or Rust. Keep the built-in PHP extension (vscode.php) enabled: Phem uses its grammar for the PHP code.

The extension finds the project from the nearest composer.json. These settings are the server's initialization options:

  • phem.phemc.sourceDir (default src)
  • phem.phemc.buildDir (default var/phem)
  • phem.phemc.path runs a native phemc binary instead of the bundled server

The extension turns on Tailwind CSS IntelliSense in .phem files, so you get completion, hover and linting for classes in className, including className={{ classes('px-4 py-2') }} and lists. Classes in PHP code (Phem\classes()) don't get completion. To turn on Emmet too, see Tailwind CSS and Emmet. For other settings and troubleshooting, see editors/vscode/README.md.

PhpStorm#

You need PhpStorm 2026.3 or later. Install the Phem plugin from Settings > Plugins > Marketplace (search for Phem). The plugin runs the bundled server with Node.js, or a phemc binary.

Open Settings > Languages & Frameworks > Phem to set the source directory, the build directory, and the paths of phemc and Node.js. The executable paths are application settings, not project settings, so a project can't make PhpStorm run an executable. For more, see editors/phpstorm/README.md.

Zed#

Zed starts language servers only from extensions. Open zed: extensions, search for Phem, and click Install. The extension starts vendor/bin/phemc lsp in the root of the Zed project, so open the directory that holds composer.json. Zed opens new projects in Restricted Mode and starts the server only after you click Trust and Continue.

The extension colors .phem files with the Phem Tree-sitter grammar. When you type the > of a start tag, Zed adds the closing tag (<ul> becomes <ul></ul>); the jsx_tag_auto_close setting turns this off. In markup, editor: toggle comments writes a Twig comment ({# #}).

The grammar colors every capitalized tag as a component. To also get the server's semantic tokens, which know whether <Missing /> really exists and whether a Twig name is a prop, a method or a local variable, add this to .zed/settings.json or ~/.config/zed/settings.json:

{
  "languages": {
    "Phem": { "semantic_tokens": "combined" }
  },
  "lsp": {
    "phem": {
      "initialization_options": { "sourceDir": "src", "buildDir": "var/phem" }
    }
  }
}

combined layers the semantic tokens on top of the grammar's colors. You only need initialization_options if your directories aren't the defaults. To start another phemc, set lsp.phem.binary ({ "path": "/usr/local/bin/phemc", "arguments": ["lsp"] }). If the server doesn't start, zed: open log shows why (see editors/zed/README.md).

Use Another Editor#

Any editor with an LSP client can run vendor/bin/phemc lsp without a plugin. You need four things:

  • File type: a phem file type for .phem files.
  • Command: vendor/bin/phemc lsp, started in the project root (the directory of composer.json).
  • Initialization options: sourceDir and buildDir, if they aren't the defaults (see What the Language Server Does).
  • Highlighting: the Tree-sitter grammar in editors/tree-sitter-phem/. Its queries/ directory has queries for Neovim and Helix; for another editor, adapt them to its capture names (see the grammar's README). Editors that read TextMate grammars can use editors/vscode/syntaxes/phem.tmLanguage.json.

All standard LSP features work. Three features are custom requests that need some editor code: the closing tag as you type (phem/closingTag, see the Neovim autocmd), and Open Compiled Template and Open Compiled PHP (phem/compiledFiles).

Neovim#

You need Neovim 0.11 or later. Add the server to ~/.config/nvim/init.lua:

vim.filetype.add({ extension = { phem = 'phem' } })

vim.lsp.config('phem', {
  -- Starts the server in the root, so the relative path works in a subdirectory.
  cmd = function(dispatchers, config)
    return vim.lsp.rpc.start({ 'vendor/bin/phemc', 'lsp' }, dispatchers, { cwd = config.root_dir })
  end,
  filetypes = { 'phem' },
  root_markers = { 'composer.json' },
  init_options = { sourceDir = 'src', buildDir = 'var/phem' },
})
vim.lsp.enable('phem')

For colors, install the Phem grammar with nvim-treesitter (the main branch, which needs the tree-sitter CLI). Add the parser to init.lua, then run :TSInstall phem:

vim.api.nvim_create_autocmd('User', {
  pattern = 'TSUpdate',
  callback = function()
    require('nvim-treesitter.parsers').phem = {
      install_info = {
        url = 'https://github.com/phemphp/phem',
        location = 'editors/tree-sitter-phem',
        queries = 'editors/tree-sitter-phem/queries/neovim',
      },
    }
  end,
})

vim.api.nvim_create_autocmd('FileType', {
  pattern = 'phem',
  callback = function()
    vim.treesitter.start()
  end,
})

This installs the grammar from the main branch. To match your Phem version, add revision with the release tag (revision = 'v0.13.0'), then run :TSUpdate. The queries also give you folds and nvim-treesitter's indentation (indentexpr). Neovim turns on the server's semantic tokens by default.

To add the closing tag as you type, add this autocmd. After you type the > of a start tag, it asks the server for the closing tag and inserts it after the cursor:

vim.api.nvim_create_autocmd('InsertCharPre', {
  pattern = '*.phem',
  callback = function(args)
    if vim.v.char ~= '>' then
      return
    end

    vim.schedule(function()
      local client = vim.lsp.get_clients({ bufnr = args.buf, name = 'phem' })[1]
      if not client or vim.api.nvim_get_current_buf() ~= args.buf then
        return
      end

      local win = vim.api.nvim_get_current_win()
      local tick = vim.api.nvim_buf_get_changedtick(args.buf)
      local params = vim.lsp.util.make_position_params(win, client.offset_encoding)
      client:request('phem/closingTag', params, function(err, tag)
        if err or type(tag) ~= 'string' or vim.api.nvim_buf_get_changedtick(args.buf) ~= tick then
          return
        end

        local row, col = unpack(vim.api.nvim_win_get_cursor(win))
        vim.api.nvim_buf_set_text(args.buf, row - 1, col, row - 1, col, { tag })
      end, args.buf)
    end)
  end,
})

Helix#

Add the language, the server and the grammar to .helix/languages.toml (Helix looks for it in the Git repository root) or ~/.config/helix/languages.toml:

[language-server.phem]
# Helix starts the server in the root, and `sh` finds the relative path there.
command = "sh"
args = ["-c", "exec vendor/bin/phemc lsp"]
config = { sourceDir = "src", buildDir = "var/phem" }

[[language]]
name = "phem"
scope = "source.phem"
file-types = ["phem"]
roots = ["composer.json"]
language-servers = ["phem"]
grammar = "phem"

[[grammar]]
name = "phem"
source = { git = "https://github.com/phemphp/phem", rev = "main", subpath = "editors/tree-sitter-phem" }

Helix sends config as the initialization options. To match your Phem version, set rev to the release tag (rev = "v0.13.0"). Then fetch and build the grammar (you need a C compiler), and copy its queries into Helix's runtime directory, using the same rev:

hx --grammar fetch && hx --grammar build
mkdir -p ~/.config/helix/runtime/queries/phem
for query in highlights injections indents; do
  curl -fsSL -o ~/.config/helix/runtime/queries/phem/$query.scm \
    https://raw.githubusercontent.com/phemphp/phem/main/editors/tree-sitter-phem/queries/helix/$query.scm
done

Helix has no semantic tokens, so component tags get their color from their capitalized name, and Twig names are colored as variables. It can't add the closing tag as you type. hx --health phem shows which server, parser and queries Helix found.

Use Claude Code#

The Phem plugin for Claude Code runs your app's vendor/bin/phemc lsp, so Claude Code gets the diagnostics after each edit of a .phem file. The plugin also adds the MCP server, skills and a check hook (see Use Claude Code).

What the Language Server Does#

phemc lsp runs on stdin and stdout and takes no command-line options. The editor can pass two initialization options:

  • sourceDir (default src): the server checks only the .phem files in this directory.
  • buildDir (default var/phem): the output directory of phemc build (its --out option), relative to the project root. The server reads compiled files from here.

As you type, the server reports the same diagnostics as phemc check, plus an unknown-asset warning for an asset() path with no file. After a change, it recompiles only the changed files and the files that depend on them.

Note — The server reads .php files, translation files, route files and Stimulus controllers from disk. Save those files to see your changes in a .phem file.

Completion, Hover and Signature Help#

Completion and hover work in both the PHP code and the Twig code of the markup, including Twig code inside a quoted attribute value (href="/en{{ path('|') }}"). Inside a value, only {{ }} is Twig code, and only when its }} is on the same line.

Signature help shows a call's parameters and highlights the one at the cursor. It works for PHP calls ($this->remove(, new Scientist(), Twig handler calls (onClick={{ remove(1, | ) }}), methods of a Twig variable, and Twig functions and filters, including the app's own ({{ price|money(| ) }}). Named arguments highlight their parameter.

The server also knows:

  • PHP built-ins: the functions, classes and constants of PHP 8.4's common extensions (Core, standard, SPL, mbstring, intl, PDO, dom, curl and others), from JetBrains' phpstorm-stubs, so no PHP install is needed. Your project's and vendor/'s symbols come first. Built-ins have no go to definition, and renaming one is refused.
  • Generic types: @template, @extends, @implements and @use tags (also with the phpstan- and psalm- prefixes), and class-string<T> arguments. With /** @extends ServiceEntityRepository<Scientist> */ on ScientistRepository, $repo->find(1)-> completes Scientist's members, and so does $em->getRepository(Scientist::class)->find(1)->.
  • Global constants: hover and go to definition on const and define() constants, also inside constant('App\\Ui\\LIMIT') in Twig. Twig strips a single \, so write \\ there.
  • The app's Twig extensions: methods with #[AsTwigFilter], #[AsTwigFunction] and #[AsTwigTest], read from the autoload PSR-4 directories of composer.json. The signature hides the parameters Twig fills in (the value, the environment, the context).
  • Route names: path(' and url(' complete the #[Route] routes of your controllers and .phem pages, plus the routes of config/routes/ and bundles from the dev router cache (var/cache/dev/url_generating_routes.php). Hover shows a route's path and controller, and go to definition opens the controller method or the .phem page. phemc build and phemc watch keep the cache up to date; after you edit config/routes/, run phemc build.
  • Translation keys: inside {{ 'cart.|'|trans }} and {{ t('cart.|') }}, from translations/ (YAML, XLIFF, PHP and JSON), in the call's domain or {% trans_default_domain %}. Each item shows the text in the default locale (framework.default_locale), and its doc shows every locale. Bundle keys (validators, security) aren't listed.
  • Asset paths: inside {{ asset('images/|') }}, one directory level at a time, from AssetMapper's paths (read from the dev container cache, or framework.asset_mapper.paths, or assets/) and then public/. Hover previews images, and go to definition opens the file. A literal path with no file gets the unknown-asset warning (for example asset('images/lgo.svg')), except with a Webpack Encore manifest (framework.assets.json_manifest_path).
  • Enum values: in the value of a backed enum prop (<Button variant="|" />), the enum's case values, in order, with each case's doc comment.
  • Stimulus controllers: data-controller="|" completes the built-in controllers, then the app's controllers in assets/controllers/ (admin/user_card-controller.ts is admin--user-card) and the packages enabled in assets/controllers.json. On an element, it completes the controllers' data-<controller>-<name>-value and data-<controller>-target attributes. Hover and go to definition work on controller names, targets and values. The server doesn't read StimulusBundle's controller_paths option or controllers that app.js registers itself.
  • Skeletons: in an empty .phem file (or one with a single word), completion offers component, class component and page. The namespace comes from the file's PSR-4 directory and the name from the file name; a page gets the Page suffix and a kebab-case path (TeamMembers.phem gives TeamMembersPage at /team-members).
  • Go to definition and find references work on components, functions, classes, methods, properties, props, slots, class constants, enum cases and global constants, from their declaration or any usage. References include tags, Twig names, Twig handlers (onClick={{ save }}), tag attributes (<Card title="Hello" />), and calls in the project's .php files (not vendor/ or var/). On a PHP built-in, find references lists its usages in your project.
  • Code lens shows the usage count of each function, class and method.
  • Document highlight marks the other occurrences of a name in the current file, with writes ($this->count = 1, ++$this->count) and reads in different colors.
  • Workspace symbols find the components and pages of the project and its packages, with fuzzy matching (tp finds TeamPage). Each page also matches its route path, so /team finds #[Page('/team')]. Use Go to Symbol in Workspace (Cmd+T) in VS Code, or Navigate > Symbol in PhpStorm.
  • Folding covers elements, components, Twig blocks, classes, functions, use groups, block comments and // region markers.
  • Semantic tokens tell the editor what each resolved name is: a component tag, a prop, an event attribute (onClick), a method, a parameter, a local variable, an enum case, a Twig filter. An unknown tag (<Missing />, error E010) keeps the plain grammar color. In VS Code, the theme must enable editor.semanticHighlighting.enabled (most do).

Quick Fixes#

Code Fix
E010 Add the use import of an unknown component (one fix for each matching component)
W004 Add the use import of an attribute
E013 Change the old slot syntax <Card:footer> to <Card.footer>, in both tags
E004 Self-close a void element (<br> becomes <br />)
H001 Remove a variable that only copies a property for the markup, and use the property's name in the markup
H002 Remove an unused import

No import fix appears for a qualified name (<Parts\Card>), or when the file already imports or declares another symbol with the same short name.

Refactors#

Select complete sibling nodes of markup, or put the cursor in an open tag, to get two refactors:

  • Wrap with Element (refactor.rewrite) wraps the markup in a new <div>. Put the cursor in div and type a new name: tag editing changes both tags together.
  • Extract Component (refactor.extract) moves the markup to a new function component named NewComponent, in a new file in the same directory and namespace, and replaces it with a tag. Each variable the markup reads from its surroundings becomes a typed parameter, and a class handler becomes a \Closure parameter. Rename it with F2, which also renames the file (except in PhpStorm).
// src/Ui/TodoList.phem: select the <li>, then "Extract Component `NewComponent`"
{% for todo in todos %}
    <NewComponent key={{ todo.id }} todo={{ todo }} remove={{ remove }} />
{% endfor %}

// src/Ui/NewComponent.phem: the new file
#[Component]
function NewComponent(Todo $todo, \Closure $remove): Node
{
    return (
        <li>
            {{ todo.title }}
            <button onClick={{ remove(todo.id) }}>Remove</button>
        </li>
    );
}

Extract Component isn't offered when the markup reads a variable named key or children (the tag can't pass those), when a {% set %} in the selection binds a variable used after it, or when the editor can't create files in a workspace edit. It shows in the refactor menu and Ctrl+., not in the automatic suggestions on each cursor move.

Organize Imports (source.organizeImports) removes unused imports (H002) and sorts the rest: class imports, then use function, then use const, each alphabetical, with a blank line between groups. It leaves the imports alone when a comment or other code sits between them. In VS Code, use Organize Imports (Shift+Alt+O) or "editor.codeActionsOnSave": {"source.organizeImports": "explicit"}. In PhpStorm, it's in the Alt+Enter list.

Rename and Move#

Rename works on the same symbols as find references. It updates the declaration, tags and closing tags, slot tags (<Layout.footer>), tag attributes, use imports (an alias stays), PHP and Twig names, class names in Twig (path(TeamPage)), handlers, constant('...') strings, and calls in .php files. Renaming a prop of a function component also renames its variable. A method renames together with the same method in parent and child classes. A page with a default route name also updates path('app_ui_teampage').

When a file declares only the renamed function or class and has its name, the file is renamed too: Card to Panel moves src/Ui/Card.phem to src/Ui/Panel.phem.

Warning — Save your .php files before a rename. The server reads them from disk. The VS Code extension and the PhpStorm plugin save them for you; other editors don't.

The server refuses a rename that would break the code, and says why. For example: a declaration in a .php file or a package, a component that another one replaces, the children slot, render() and magic methods, a reserved PHP name (E068), or a name that's already taken in the namespace, class, file or markup. A name in a string or a comment doesn't change (except constant('...')), and neither do named arguments (new Card(title: 'x')). PhpStorm doesn't rename files.

Move a file: when you move a .phem file or folder in the editor, the server sets each moved file's namespace to the PSR-4 namespace of its new directory (workspace/willRenameFiles). It updates imports, qualified names, relative names, constant('...') strings and default route names across the project's .phem and .php files, and adds imports where a file relied on a shared namespace. A file keeps its namespace when the new directory isn't a PSR-4 directory, when the new namespace already has one of its names, or when you only rename the file (use Rename on the class for that). VS Code supports this; PhpStorm doesn't send these requests.

Formatting and Tag Editing#

Formatting applies the rules of phemc fmt to the markup, with the editor's tabSize (1 to 16) and insertSpaces. PHP code stays as written, and a file that doesn't parse isn't changed. Use Format Document or editor.formatOnSave in VS Code, and Code > Reformat Code in PhpStorm (its indent comes from Settings | Editor | Code Style | Other File Types).

Tag editing links an open tag's name with its closing tag's name (textDocument/linkedEditingRange), so editing one edits the other. It works on HTML elements, components, slot tags and raw elements like <script>. The PhpStorm plugin sends this request itself, since PhpStorm's LSP API has no linked editing.

Packages#

The server checks your Composer packages' .phem files together with the app. Completion, definition and hover work for package components, and a package file's errors show in that file (also at its real path for a Composer path repository). Only the app that installs a package checks its files, so a linked package in the same workspace doesn't check itself.

The server reloads packages after a Composer change, when a package file changes on disk, and when a source directory or package root appears or disappears. If it can't read a package root (a bad extra.phem.source), it shows the error once and checks only the app's files.

Custom Requests#

Request Params Result
phem/closingTag text document and position The closing tag to insert after the > of an open tag ("</Card.footer>"), or null (in PHP or Twig code, an attribute value, a comment, or after a void element)
phem/compiledFiles text document and position {"php": {"uri", "line"}, "templates": [{"uri", "name", "line", "current"}]}

phem/compiledFiles returns the compiled files of a .phem file in buildDir. The PHP line matches the position, because compiled PHP keeps the .phem file's line numbers. Each template has the line of its markup (from 0), and current marks the one at the position. A package file returns the files compiled by the app that installs it. Without a build, the request fails with No build output in `var/phem`. Run `phemc build`. The VS Code extension and the PhpStorm plugin use it for Open Compiled Template and Open Compiled PHP (see Open the compiled output).

Edit this page on GitHubLast updated
Phem
Esc
↑↓ to navigate↵ to openEsc to close