LSP Integration Guide

This guide covers PHPRegex’s Language Server Protocol (LSP) server and how to integrate it with your IDE for real-time regex analysis.


Overview

The PHPRegex LSP server provides:

  • Real-time diagnostics - Parse errors, validation issues, and lint warnings
  • Hover information - Pattern explanation on mouse hover
  • Code actions - Quick fixes for common issues
  • Completions - Regex syntax suggestions and documentation

Quick Start

The server requires PHP 8.1 or later.

Installation

composer config minimum-stability dev
composer config prefer-stable true
composer require --dev php-regex/regex-language-server:2.x-dev

The server binary is vendor/bin/regex-lsp. Run it with --help for its options, --version for the release it was built from:

vendor/bin/regex-lsp --help

The phar carries the server too: php regex.phar lsp runs it, one download for Neovim, Helix, Zed or any editor that starts a command. Wherever the sections below name vendor/bin/regex-lsp, the phar’s command works the same way.

Configure Your IDE

See the IDE-specific sections below for configuration instructions.


Features

Real-time Diagnostics

The LSP server analyzes PHP files and reports regex issues as you type:

Diagnostic Type Description
Parse Errors Invalid regex syntax
Validation Errors PCRE compatibility issues
Unicode Errors Missing /u flag: a property or an escape above U+FF fails as an error
Style Issues Anti-patterns and best practice violations, as ASCII-only shorthands without /u — information level, off by default
Performance Hints Lint warnings on shapes that backtrack, as nested quantifiers
ReDoS The verdict of the ReDoS analysis, when it is turned on (off by default)

Example diagnostics:

Info: Shorthand "\w" matches only ASCII without /u flag.
Error: Without the /u flag, Unicode property "\p{L}" only covers the first 256 code points.
Error: Unicode escape "\x{100}" requires /u flag for code points > U+FF.

An invalid pattern’s diagnostic gives its fix on the line under the error, as the hint of validate() does:

Error: Invalid quantifier range "{2,1}": min > max.
       Write the smaller count first: "{1,2}".

What each diagnostic underlines:

  • an error, the character regex validate puts its caret under, where PCRE reports it: the closing delimiter when the pattern ends too early;
  • a lint issue, the whole construct it names, as [aa] or (a+)+;
  • a ReDoS verdict, the part of the pattern at risk, else the whole body;
  • a pattern not analyzed for a limit, the whole body.

A lint issue, a ReDoS verdict, an inline marker that silences nothing and a @regex-target marker that cannot be read carry their identifier as the diagnostic’s code, and a codeDescription linking to its section of the rule reference: an editor that supports it shows the code as a link.

Columns count UTF-16 code units, as the protocol does, and follow the literal as written: in "/\t(a/" an offset past the tab lands past the \t escape.

A change analyses only the patterns whose text it changed; the findings of the others move with them. A keystroke inside a pattern that a call takes whole, as in preg_match('/a+b/', $s), is read in place, the rest of the document standing as it stood; any other change reads the document again. In a file holding about 330 patterns, a keystroke inside one of them takes about 5 ms.

Hover Information

Hover over any regex pattern to see:

  • The complete pattern with syntax highlighting
  • A plain-English explanation of what it matches
  • Flag documentation

Example:

**Regex Pattern**

`/^[a-z]+@[a-z]+\.[a-z]+$/i`

**Explanation**

Start of string
  One or more characters from: a-z
  Literal '@'
  One or more characters from: a-z
  Literal '.'
  One or more characters from: a-z
End of string (case-insensitive)

Code Actions

Quick fixes appear when issues are detected:

Code Action Description
Add /u flag Fix Unicode-related warnings
Apply optimization Simplify or improve the pattern, offered only when the automata prove the rewrite writes the same $matches, as regex lint checks the rewrites it suggests
Format pattern over lines Lay a long pattern out over lines under x (see Formatting patterns)
Compact pattern to one line Write a laid-out pattern back on one line, without x, layout or comments

Completions

Context-aware completions for:

  • Character classes - \d, \w, \s, \h, \v, etc.
  • Anchors - ^, $, \b, \A, \Z, \z, etc.
  • Quantifiers - +, *, ?, {n}, {n,m}, etc.
  • Groups - (?:...), (?=...), (?!...), (?>...), etc.
  • Unicode properties - \p{L}, \p{N}, \p{Script=Latin}, etc.
  • POSIX classes - [:alpha:], [:digit:], [:space:], etc.
  • Flags - i, m, s, x, u, etc.

Target PHP and PCRE2

Whether a pattern compiles depends on the PCRE2 release and, for a few rules, on the PHP version. The server judges every pattern of the workspace for one target, chosen once, when the editor sends initialize:

  1. initializationOptions.phpVersion and initializationOptions.pcreVersion sent by the editor;
  2. phpVersion and pcreVersion in regex.json (and regex.dist.json) at the root folder;
  3. composer.json at the root folder: config.platform.php if set, else the lowest version require.php allows, with the later versions it allows;
  4. the PHP running the server.

The locale is chosen the same way: initializationOptions.locale, then locale in regex.json, then the one of the PHP running the server (see Which locale judges a pattern). Every version a @regex-target marker keeps is judged under it.

The root folder is the first entry of workspaceFolders, else rootUri. Each version is chosen on its own, and every version judged (the target and each version a marker keeps) gets its PCRE2 in this order, the order of every entry point:

  1. initializationOptions.pcreVersion, else pcreVersion in regex.json, else the release composer.json at the root folder pins in config.platform.lib-pcre (“10.42”, or “10.42.0”` as Composer spells it). A pin is used as is, older or newer than the one that PHP bundles;
  2. the PCRE2 of the PHP running the server, when the version judged is its minor version: on a PHP 8.4.27 that links 10.49, PHP 8.4 is judged with 10.49;
  3. the PCRE2 that PHP bundles: 10.32 for PHP 7.3, 10.33 for 7.4, 10.35 for 8.0, 10.39 for 8.1, 10.40 for 8.2, 10.42 for 8.3, 10.44 for 8.4 and 8.5.

A config.platform.lib-pcre that names no PCRE2 release is passed over with a notice.

{
  "initializationOptions": {
    "phpVersion": "8.2",
    "pcreVersion": "10.40",
    "locale": "tr_TR.UTF-8"
  }
}

phpVersion takes "8.2", "8.2.4" or 80200, or a range: a Composer constraint such as ">=8.1", or {"min": "8.1", "max": "8.6"}, as in regex.json; pcreVersion takes a release such as "10.42"; locale a locale this machine can set. A value the server cannot read is logged as a warning and the next source is used. A locale in regex.json the machine cannot set is shown as an error, and no pattern is judged.

The server logs the target once through window/logMessage, where most editors show the language server output:

Target: PHP 8.2, PCRE2 10.40, locale tr_TR.UTF-8 (initializationOptions)

What it noticed on the way, such as a composer.json without require.php, comes in messages of its own. Changing the target takes a restart of the server.

ReDoS Analysis

The server can run the ReDoS analysis regex lint runs under checks.redos, and publish its verdict on each pattern. It is off by default: the analysis costs more than the lint, on every change. It is on when the editor sends initializationOptions.redos:

{
  "initializationOptions": {
    "redos": true
  }
}

else when checks.redos.enabled is true in the workspace’s regex.json, the switch regex lint reads; "redos": false turns it off for the editor whatever regex.json says. The mode and the threshold are those of checks.redos in regex.json, theoretical and high when unset, as for regex lint:

{
  "checks": {
    "redos": {
      "enabled": true,
      "threshold": "medium"
    }
  }
}

The verdict is published as regex lint reports it: regex.lint.redos, an Error when it is confirmed at high severity or above, a Warning otherwise, over the risky part of the pattern, with the attack the analysis found on the line under it:

Warning: Exponential backtracking (proven). Severity: CRITICAL, confidence: MEDIUM.
         Attack: "a" x n . "!"

The quadratic cost of an unanchored search whose every attempt is linear is regex.lint.redos.search, a Warning, at a threshold of medium or low. So is the cost of the loop of a call that looks for every match, preg_match_all() or preg_split() for instance, on a pattern whose search stops at an empty match inside a run, as on the command line. Once the analysis proves a pattern linear, the lint warnings that guess at backtracking (quantifier.nested, dotstar.nested, overlap.charset) are no longer published for it. The analysis is bounded as on the command line: a pattern past its budget says so in the verdict. Changing the setting takes a restart of the server.


Which Calls Are Read

The server reads the calls regex lint reads (see the CLI guide), with the same rules: the native calls, the presets extraction.interop names in the workspace’s regex.json (every preset when unset), and the helpers extraction.functions names. A regex.json the server cannot read, a name in extraction.interop that is no preset included, is an error shown to the user (window/showMessage) and logged, and the server reads as without the file, every preset included, rather than a list that reads fewer calls than meant:

regex.json ignored: Invalid "extraction.interop" in /app/regex.json: unknown preset "laravel-str"; did you mean "illuminate-support"?

A pattern held in a constant, a local variable or a property of the same document is diagnosed where its literal is written, once, as regex lint reports it; @regex-ignore on that line silences it, and a marker on the call does not. A ternary or a match whose arms are literals is diagnosed at each arm. A pattern built at the call from several parts, a concatenation or an interpolated string, is not diagnosed in the editor: regex lint reads it. A class constant, an enum case or a global constant (const or define()) of another file of the workspace, or of vendor/, holding a pattern, preg_match(Patterns::BROKEN, $s), is read as regex lint reads it, an open document standing for its file; the lint reports the pattern at its literal, the editor reports it at the argument naming it, each message saying which constant and where it is written. With public const BROKEN = '/(a/'; on line 9 of src/Support/Patterns.php:

Patterns::BROKEN, written in src/Support/Patterns.php on line 9: Expected ) at end of input (found eof).

A document naming the same constant twice is reported at the first argument, as the lint reports the literal once. Hovering the argument shows the pattern and its explanation; it has no quick fix, which would edit the other file. A marker may name the issues it silences (// @regex-ignore regex.lint.flag.useless.i), and a marker that silences nothing is a warning on the marker, regex.ignore.unmatched, unless "reportUnmatchedIgnores": false in regex.json turns it off (see the CLI guide). A pattern under a guard on PHP_VERSION_ID (the forms the tokenizer reads) or under @regex-target is judged for the lowest version they keep of the project’s range (see the CLI guide); a marker that keeps none, or cannot be read, is an error on the marker. When the target is a range, each pattern is also validated at the later versions it allows, as the lint validates it: a version that refuses the pattern is an error naming it, and one that reads it otherwise a warning, regex.lint.compat.meaningChanges. On opening a file, and when a watched file changes, the server publishes the lowest version’s diagnostics first, then every version’s, so the editor shows the first ones without waiting for the later versions; a keystroke publishes once. A namespace that declares its own function shadows a global pattern function of the same name, as in the lint: an unqualified call in that namespace is not read.

Two differences: a diagnostic needs one string literal to land in, so a pattern the call assembles from several pieces ('/'.self::PART.'/') and a pattern written as a heredoc or a nowdoc get no diagnostic in the editor, although regex lint reports them. And a string that does not open with a delimiter, after the spaces PHP skips, is not taken for a pattern: one starting with a letter, a digit, a backslash or NUL gets no diagnostic, where regex lint reports its invalid delimiter. Any other first byte is a delimiter PHP accepts, |, + and " included, and the pattern is diagnosed.

Functions Marked #[RegexPattern]

A parameter marked with the attribute PHPRegex\Parser\Attribute\RegexPattern, or with PhpStorm’s #[Language('RegExp')], makes its function or static method a pattern function, as for regex lint (see the CLI guide): the string literal passed at that argument is checked like the pattern of a preg_*() call.

namespace App\Support;

use PHPRegex\Parser\Attribute\RegexPattern;

final class Str
{
    public static function matches(string $subject, #[RegexPattern] string $regex): bool
    {
        return 1 === preg_match($regex, $subject);
    }
}

Str::matches($input, '/(a/'); // reported: missing closing parenthesis

The server finds the declarations in three places:

  • the PHP files of the workspace, read once at initialize: those under paths in regex.json (the root folder when unset), but those under an exclude entry (vendor when unset) and templates (.blade.php, .tpl.php, .twig.php). Only a file that names PHPRegex\Parser\Attribute or JetBrains\PhpStorm\Language is tokenized; the scan stops after 20,000 PHP files and logs a warning, so a larger workspace narrows paths or exclude;
  • the libraries of the workspace’s vendor/, read at initialize whatever exclude says, as regex lint reads them: a helper a package declares is known. This scan also stops after 20,000 PHP files and logs a warning (Functions declaring #[RegexPattern] were read from the first PHP files of vendor/ only.): a helper declared in a library past that point is not known to the server, though regex lint still reads it. A document opened from vendor/ gives its declarations and gets no diagnostics. A project declaration wins over a library’s of the same function. When the editor reports vendor/composer/installed.json changed, the libraries are read again;
  • the open documents, read on every change: an open document stands for its file, saved or not, and when its declarations change, the other open documents are checked again.

A saved document (textDocument/didSave) and a file the editor reports as created, changed or deleted (workspace/didChangeWatchedFiles) are read again. A client that offers dynamic registration is asked, right after initialized, to watch the workspace’s PHP files and vendor/composer/installed.json — the manifest above all, whose change reads the libraries again; a client without it sends the events only when configured to, as before. A file changed outside the editor that it does not report keeps its declarations until the server restarts.

The calls are read as regex lint reads them: function calls and static calls that name their class, their names resolved through the namespace and the use imports, a named argument read under the marked parameter’s name; an unqualified call in the function’s own namespace, grep() in namespace App, is read, as PHP calls App\grep() first. An instance call ($str->matches(...)) and a call through self::, static:: or parent:: are not read.


IDE Configuration

VS Code

VS Code has no setting that points at an arbitrary language server: the supported path is a small extension built on the vscode-languageclient npm package. The official Language Server Extension Guide walks through the whole process; for PHPRegex, the client boils down to:

// src/extension.ts
import * as vscode from 'vscode';
import { LanguageClient, TransportKind } from 'vscode-languageclient/node';

const server = {
  command: 'vendor/bin/regex-lsp', // resolved from the workspace root
  transport: TransportKind.stdio,
};

export function activate(context: vscode.ExtensionContext): void {
  const client = new LanguageClient(
    'php-regex',
    'PHPRegex',
    { run: server, debug: server },
    { documentSelector: [{ scheme: 'file', language: 'php' }] },
  );

  context.subscriptions.push(client.start());
}

Installing a PHP editor extension such as Intelephense or phpactor is not an alternative: those are language servers of their own, not clients that host others, so they cannot run regex-lsp for you.

PhpStorm / IntelliJ IDEA

Use the LSP4IJ plugin by Red Hat for LSP support:

  1. Install LSP4IJ from the JetBrains Marketplace

  2. Go to Settings → Languages & Frameworks → Language Servers

  3. Click + to add a new server definition:
    • Name: PHPRegex
    • Command: vendor/bin/regex-lsp
    • File Mappings: *.php
  4. The server will now provide diagnostics, hover, and code actions for regex patterns

Alternative: PHPStan Integration

PHPRegex also integrates with PHPStan (see the PHPStan guide):

  1. Install the PHPStan plugin for PhpStorm
  2. Configure PHPStan in Settings → PHP → Quality Tools → PHPStan
  3. Enable real-time inspection

This provides the same regex diagnostics through PHPStan’s analysis

Neovim

Using nvim-lspconfig

Add to your init.lua:

local lspconfig = require('lspconfig')
local configs = require('lspconfig.configs')

-- Define the php-regex LSP server
if not configs.php_regex then
  configs.php_regex = {
    default_config = {
      cmd = { 'vendor/bin/regex-lsp' },
      filetypes = { 'php' },
      root_dir = lspconfig.util.root_pattern('composer.json', '.git'),
      settings = {},
    },
  }
end

-- Enable the server
lspconfig.php_regex.setup({
  on_attach = function(client, bufnr)
    -- Your on_attach function
  end,
})

Using coc.nvim

Add to coc-settings.json:

{
  "languageserver": {
    "php-regex": {
      "command": "vendor/bin/regex-lsp",
      "filetypes": ["php"],
      "rootPatterns": ["composer.json", ".git"]
    }
  }
}

Vim (with vim-lsp)

Add to your .vimrc:

if executable('vendor/bin/regex-lsp')
    au User lsp_setup call lsp#register_server({
        \ 'name': 'php-regex',
        \ 'cmd': {server_info->['vendor/bin/regex-lsp']},
        \ 'allowlist': ['php'],
        \ })
endif

Emacs (with lsp-mode)

Add to your Emacs config:

(require 'lsp-mode)

(add-to-list 'lsp-language-id-configuration '(php-mode . "php"))

(lsp-register-client
 (make-lsp-client
  :new-connection (lsp-stdio-connection '("vendor/bin/regex-lsp"))
  :major-modes '(php-mode)
  :server-id 'php-regex))

Sublime Text (with LSP package)

  1. Install the LSP package

  2. Add to Preferences → Package Settings → LSP → Settings:

{
  "clients": {
    "php-regex": {
      "enabled": true,
      "command": ["vendor/bin/regex-lsp"],
      "selector": "source.php"
    }
  }
}

Helix

Add to ~/.config/helix/languages.toml:

[[language]]
name = "php"
language-servers = ["intelephense", "php-regex"]

[language-server.php-regex]
command = "vendor/bin/regex-lsp"

Zed

Add to your settings:

{
  "lsp": {
    "php-regex": {
      "binary": {
        "path": "vendor/bin/regex-lsp"
      }
    }
  },
  "languages": {
    "PHP": {
      "language_servers": ["intelephense", "php-regex"]
    }
  }
}

Coding Agents (OpenCode)

OpenCode feeds the diagnostics of the language servers it runs back to its agent, so the patterns the agent writes are checked as it writes them. A custom server goes under lsp in opencode.json at the project root; initialization is sent as the initializationOptions of initialize:

{
  "$schema": "https://opencode.ai/config.json",
  "lsp": {
    "php-regex": {
      "command": ["vendor/bin/regex-lsp"],
      "extensions": [".php"],
      "initialization": {
        "redos": true
      }
    }
  }
}

Configured as an object beside the built-in servers, it keeps them on: Intelephense still serves PHP. The other initializationOptions the server reads, phpVersion, pcreVersion, locale and trace, go under initialization too.


LSP Protocol Details

Supported Methods

Method Description
initialize Server capabilities negotiation; a second one is answered Invalid Request (-32600)
initialized Initialization complete
shutdown Graceful shutdown request: nothing else is served until exit, and a request sent in between, a second shutdown included, is answered Invalid Request (-32600)
exit Server exit: code 0 after shutdown, 1 without it
textDocument/didOpen Document opened
textDocument/didChange Document changed: the changes are whole texts (full sync), applied in order, so the last one is the document
textDocument/didClose Document closed
textDocument/didSave Document saved: its declarations are read again
workspace/didChangeWatchedFiles Files changed outside the editor: their declarations are read again; the watcher is registered with the client when it offers dynamic registration
textDocument/hover Hover information
textDocument/codeAction Code actions (quick fixes)
textDocument/completion Completion suggestions
textDocument/publishDiagnostics Push diagnostics to client, with the document’s version when the client sent one
$/setTrace The level of the frame log from now on

A notification that arrives before initialize is dropped with a line on stderr — the $/ ones silently, the client’s own plumbing — and a request is answered ServerNotInitialized (-32002), shutdown excepted, which is answered and ends the session as ever. A second initialize initializes nothing again: the request is answered Invalid Request (-32600), the notification dropped the same way.

Malformed Messages

A message the server cannot use is answered with a JSON-RPC error, and the session goes on — except for a header block the reader cannot bound, which ends it:

Message Answer
A body that is not JSON, or empty (Content-Length: 0) -32700 Parse error, id null
Headers without a usable Content-Length -32700 Parse error, id null; the body has no known end, so reading starts again at the next Content-Length header — as long as the skipped bytes stay under the 8 KiB header cap; past it the session ends as the row below
A declared Content-Length over 16 MiB -32600 Invalid Request, id null; the declared bytes are drained and the session goes on
A header block over 8 KiB, an endless run of header lines above all -32600 Invalid Request, id null; the session ends there, exit 0 — exit 1 stays the crash signal, not the answer to garbage
JSON that is not a JSON-RPC 2.0 object: a batch, a scalar, no "jsonrpc": "2.0", a method that is not a string, an id that is neither an integer nor a string, params that are neither an object nor an array -32600 Invalid Request, with the message’s id when it is an integer or a string, else null

A textDocument/hover, textDocument/completion or textDocument/codeAction request that names no document, no position or no range is answered with nothing (null, or [] for code actions). The same method sent as a notification, without an id, is never answered.

A pattern may hold bytes that are no UTF-8, as "/^\xff\xd8\xff/" does; the protocol speaks JSON, which holds UTF-8 only. The hover and the diagnostics spell such a byte \xFF, and a code action writes the pattern between double quotes with the same escape. The quick fix that adds u is not offered for such a pattern: PCRE refuses it under u.

Server Capabilities

{
  "capabilities": {
    "textDocumentSync": {
      "openClose": true,
      "change": 1,
      "save": { "includeText": true }
    },
    "hoverProvider": true,
    "codeActionProvider": {
      "codeActionKinds": ["quickfix", "refactor.rewrite"]
    },
    "completionProvider": {
      "triggerCharacters": ["\\", "[", "(", "/"],
      "resolveProvider": false
    }
  }
}

The watched-files watcher is not part of these capabilities: a client that offers workspace.didChangeWatchedFiles dynamic registration is asked to watch **/*.php and vendor/composer/installed.json with a client/registerCapability request after initialized; its answer, a refusal included, is never retried.


Troubleshooting

Server Not Starting

  1. Verify the binary exists:

    ls -la vendor/bin/regex-lsp
    
  2. Check it’s executable:

    chmod +x vendor/bin/regex-lsp
    
  3. Test it directly. The server speaks LSP over stdio, where a message is a Content-Length header followed by its JSON body — a bare echo prints nothing: the server reads the line as a header, the input ends before the blank line that closes the headers, and it exits without a message to answer. Frame the message:

    MSG='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{},"rootUri":null}}'
    printf 'Content-Length: %d\r\n\r\n%s' "$(printf '%s' "$MSG" | wc -c)" "$MSG" \
      | vendor/bin/regex-lsp
    

    The server answers with its capabilities, then logs its target, and exits when the input ends:

    Content-Length: 369
    
    {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"textDocumentSync":{"openClose":true,"change":1,"save":{"includeText":true}},"hoverProvider":true,"codeActionProvider":{"codeActionKinds":["quickfix","refactor.rewrite"]},"completionProvider":{"triggerCharacters":["\\","[","(","/"],"resolveProvider":false}},"serverInfo":{"name":"php-regex-lsp","version":"2.0.0-RC1"}}}
    Content-Length: 124
    
    {"jsonrpc":"2.0","method":"window/logMessage","params":{"type":3,"message":"Target: PHP 8.4.26, PCRE2 10.49 (running PHP)"}}
    

    The Target: line is the PHP and PCRE2 release the server judges for (see Target PHP and PCRE2). Silence here means the framing is wrong, not that the server is broken.

Tracing the Frames

The server can log every frame it reads and writes on stderr, which editors collect in the language server’s log panel. The level is the protocol’s trace value: off (the default), messages, one line per frame with its kind, method and id, or verbose, which adds the frame’s payload as JSON, cut past 1 KiB on a character boundary so a document’s text never floods the log. Most editors send their trace setting with initialize; to set it whatever the editor sends, pass it in the initialization options:

{
  "initializationOptions": {
    "trace": "messages"
  }
}

initializationOptions.trace wins over the request’s trace, and a $/setTrace notification changes the level for the rest of the session. A value that is not one of the three is ignored with a warning. With messages, a session starts like this:

regex-lsp: trace: received request "initialize" (id 1)
regex-lsp: trace: sent response (id 1)
regex-lsp: trace: sent notification "window/logMessage"
regex-lsp: trace: received notification "initialized"

Stdout carries the frames only, traced or not.

A Warning About vendor/ or the File Limit

Two coverage gaps are shown once, at initialize, as a warning the editor displays, and logged:

  • vendor/ is missing from a workspace whose composer.json requires a package: the dependencies are installed somewhere the editor does not read, a container most often, so the functions they declare with #[RegexPattern] are not read and the patterns passed to them are not checked. Install the dependencies on the host too, or open the workspace where they are installed.
  • The workspace or vendor/ holds more than 20,000 PHP files: the declarations were read from the first ones only. Narrow paths or exclude in regex.json.

No Diagnostics Appearing

  1. Ensure the file contains preg_* function calls
  2. Check that the file is saved (some editors require saved files)
  3. Verify the server is running:
    ps aux | grep regex-lsp
    

Diagnostics Not Updating

The server uses full document sync. If you see stale diagnostics:

  1. Save the file
  2. Close and reopen the file
  3. Restart the LSP server

High CPU Usage

If the server uses excessive CPU:

  1. Exclude large files or directories
  2. Check for infinite loops in patterns

Connection Issues

For stdio-based connections:

  1. Ensure no output is written to stdout before the server starts
  2. Check that stderr is not redirected to stdout
  3. Verify the Content-Length header format

Advanced Configuration

Custom Regex Detection

The LSP server detects regex patterns in:

  • the preg_* functions, RegexIterator, and filter_var() with FILTER_VALIDATE_REGEXP
  • the calls of the presets extraction.interop names, every one by default: Preg::match(), Str::match(), PHPUnit’s regex assertions, Assert::regex(), #[Assert\Regex] and the others (Which calls are read)
  • the helpers extraction.functions names
  • the calls to the functions marked #[RegexPattern]

Both single-quoted and double-quoted strings are supported.

Performance Tuning

The server keeps what it found in each pattern it analysed, for the life of the session: a change analyses only the patterns whose text it changed, and moves the findings of the others to where they now stand. In a document of about 330 patterns, an edit to one pattern takes about 20 ms where it took about 380 ms, most of it spent finding the patterns in the text again (measured with PHP 8.4 on an Apple M1 Max).

For large codebases:

  1. Use workspace folders to limit the scope
  2. Configure file watching exclusions in your IDE
  3. Consider disabling real-time diagnostics for non-PHP files

Diagnostic Codes

Each lint rule’s severity is sent as the LSP diagnostic severity: critical and error as Error, warning as Warning, and style, perf and info as Information, the same mapping as regex lint (see Severity in Each Format). No diagnostic is sent as Hint, which editors tend to show faintly or not at all. The rules checks.lint.rules in the workspace’s regex.json turns on or off ({"checks": {"lint": {"rules": {"quantifier.nested": false}}}}) are read at initialize, so the editor reports what regex lint reports. A pattern not analyzed for a limit is published as a Warning carrying the limit’s code, Not analyzed: before its message — the same outcome and severity regex lint reports.

| Code | Severity | Description | |——|———-|————-| | regex.<area>.<problem> | Error | A pattern PCRE refuses, with its error code, such as regex.group.unclosed | | regex.lint.unicode.shorthandWithoutU | Information | \w, \d, \s without /u | | regex.lint.unicode.propertyWithoutU | Error | \p{L} without /u | | regex.lint.unicode.bracedHexWithoutU | Error | \x{100} without /u | | regex.lint.unicode.multibyteInClassWithoutU | Error | [é] without /u | | regex.lint.unicode.quantifiedMultibyteWithoutU | Error | é+ without /u | | regex.lint.group.quantifiedCapture | Information, Warning for a named group | (a)+ keeps only the last iteration | | regex.lint.group.alwaysEmptyCapture | Warning | a+(a*): $1 is always empty | | regex.lint.anchor.dollarNewline | Information | /^\d+$/ accepts "123\n" (off by default) | | regex.lint.literal.invisible | Warning | a raw tab or zero-width space in the pattern; a double-quoted "\t" is not one | | regex.lint.charclass.single | Information | [a] is a (style, off by default) | | regex.lint.literal.multipleSpaces | Information | a run of literal spaces, ` {2} (style, off by default) | | regex.lint.quantifier.uselessLazy | Information | (a+?)b matches as (a+)b (style, off by default) | | regex.lint.lookaround.edgeQuantifier | Information | (?=a{2,6}) asserts what (?=a{2}) asserts (perf, off by default) | | regex.lint.lookaround.redundant | Information | (?=a(?=b)) asserts what (?=ab) asserts (style, off by default) | | regex.lint.quantifier.lazyToClass | Information | ”.?” where ”[^”\n]” reads the run at once (perf, off by default) | | regex.lint.redos | Error when confirmed at high severity or above, else Warning | The verdict of the [ReDoS analysis](#redos-analysis), when it is on | | regex.lint.redos.search | Warning | The quadratic cost of an unanchored search, or of the loop of a call that looks for every match, when the analysis is on | | other regex.lint.*` | Warning | The lint rules |


Learn More

New to regex? Start with the tutorial.


Contributing

Found a bug or want to add a feature? Contributions are welcome!

  1. Fork the repository
  2. Create a feature branch
  3. Submit a pull request

Edit on GitHub Feedback