@adguard/rules-editor

中文文档
2.0.3发布于 2026/10/23GPL-3.0-onlyTypeScriptESM + CJS近 30 天下载 2413

User rules text editor based on Codemirror and AdGuard textmate highlight

原始使用文档
文档目录15 节
  1. Table of Contents
  2. Installation
  3. Key Concepts
  4. Quick Start
  5. Editor
  6. Tokenizing a Rule
  7. Inspecting a Line (scope debugging)
  8. API
  9. initEditor
  10. getTokenizer
  11. inspectLine
  12. Rendering tokens to HTML (display-only)
  13. Error Classes
  14. Peer Dependencies
  15. Documentation

AdGuard Rules Editor

Note: This package is developed in AdGuardSoftwareLimited/ext-rules-editor. The AdguardTeam/RulesEditor repository is a public mirror.

A browser-based library for editing and tokenizing AdGuard filter rules. It provides a CodeMirror 6 text editor with TextMate syntax highlighting (via WebAssembly Oniguruma backed by vscode-textmate + vscode-oniguruma) and a WASM-backed tokenizer for custom rule rendering.

Table of Contents

Installation

vscode-oniguruma and CodeMirror/Lezer packages are peer dependencies — your project must install them separately. vscode-oniguruma is required so the WASM binary is available in your bundle; the CodeMirror packages are required because the library returns a live EditorView instance. CodeMirror's @codemirror/state relies on instanceof checks for extensions and facets — if your bundler duplicates @codemirror/state (the library bundles one copy and your app another), these checks will fail. Externalizing the peer deps ensures a single shared copy.

pnpm add @adguard/rules-editor vscode-oniguruma @codemirror/state \
    @codemirror/view @codemirror/language @codemirror/commands \
    @codemirror/search @lezer/highlight

Key Concepts

  • Editor — a CodeMirror 6 instance with adblock syntax highlighting (embedded JavaScript regions are scoped as source.js but use a minimal placeholder grammar to keep the bundle small), powered by WASM-based Oniguruma regex from vscode-oniguruma.
  • Tokenizer — splits a rule into highlighted segments using WASM; highest precision.
  • Token — an enum of token types aligned with the CodeMirror 6 / @lezer/highlight tag taxonomy (keyword, operator, string, comment, regexp, etc.).
  • inspectLine — returns per-token segments with full TextMate scope stacks for debugging and tests.

Quick Start

Editor

import { initEditor } from '@adguard/rules-editor';

// Let your bundler (rspack / Vite) emit the asset and compute the URL.
const wasm = new URL('vscode-oniguruma/release/onig.wasm', import.meta.url);

const textarea = document.getElementById('textarea');
const view = await initEditor(textarea, wasm, {
    hotkeys: { mode: 'mac' },
});
view.dispatch({ changes: { from: 0, insert: '||example.org^' } });

Theming

Tokens are highlighted using standard @lezer/highlight tags, so any CodeMirror 6 theme works out of the box. By default the editor applies CodeMirror's defaultHighlightStyle; pass your own theme (or HighlightStyle) via conf.extensions to override it:

import { oneDark } from '@codemirror/theme-one-dark';

const view = await initEditor(textarea, wasm, {
    hotkeys: { mode: 'mac' },
    extensions: [oneDark],
});

initEditor always adds CodeMirror's drawSelection() extension, so the caret and the selection are drawn by CodeMirror rather than by the browser: native ::selection and caret styles do not apply, and you should not add drawSelection() yourself. Multi-cursor editing can be turned off with withMultipleSelections: false, which disables the extra selection ranges while leaving the drawing as it is.

Highlighting strategy

By default the editor uses full TextMate highlighting backed by Oniguruma WASM. When you do not need syntax highlighting, choose highlight: 'none' — it never loads WASM, so the wasm argument can be undefined:

// No highlighting at all, no WASM:
const plain = await initEditor(textarea, undefined, {
    hotkeys: { mode: 'mac' },
    highlight: 'none',
});

initEditor still returns a Promise<EditorView> for every strategy, so existing await initEditor(...) call sites are unaffected.

Multi-cursor editing

The editor supports editing several lines at once. Hold Ctrl (Windows/Linux) or Cmd (macOS) and click each line you want to edit: every click adds a secondary cursor, and typing inserts the same text at all cursors. A single Ctrl+Z / Cmd+Z reverts the whole multi-line edit. Holding the modifier and clicking an existing secondary cursor removes it; a plain click collapses back to a single cursor.

Set withMultipleSelections: false to switch multi-cursor editing off; without it the editor cannot be turned back to single-selection mode from conf.extensions, because EditorState.allowMultipleSelections combines its values with some. Switching it off also leaves the keyboard commands below unbound, so their chords fall through to CodeMirror's own keymap and to the browser.

The same commands are available on the keyboard, with the bindings the previous Ace-based editor used. Ace binds them to Ctrl+Alt on every platform, and on macOS this library does the same — Cmd+Alt is deliberately not used there, because Chrome and Firefox intercept Cmd+Option+Left/Right for previous/next tab, so those shortcuts would never reach the editor:

  • Ctrl+Alt+Up / Ctrl+Alt+Down — add a cursor on the line above / below;
  • Ctrl+Alt+Shift+Up / Ctrl+Alt+Shift+Down — move the last cursor up / down instead of adding one; with a single cursor the first press adds one, as in Ace;
  • Ctrl+Alt+Right / Ctrl+Alt+Left — add the next / previous occurrence of the selection;
  • Ctrl+Alt+Shift+Right / Ctrl+Alt+Shift+Left — move the main cursor to the next / previous occurrence instead of adding one;
  • Esc — collapse back to a single cursor.

A selection that spans several lines is moved by the line commands instead of being copied: the copy would overlap the original and CodeMirror would merge the two into one longer selection. When the move would leave the document the command declines and the selection is left as it is — though on Windows and Linux the chord then falls through to CodeMirror's own add-cursor commands bound to the same keys, which can still add a bare cursor.

With an empty cursor the occurrence shortcuts select the word under the cursor first — the search expands to the adjacent word when the cursor itself is not on a word character, so it selects example.com on the ^ of ||example.com^. Letters, digits and combining marks are matched with Unicode property escapes, so non-ASCII domains are selected as well.

Ctrl+/ / Cmd+/ comments (or uncomments) the line under every cursor and toggles the enabled-rule marker on every line whose rule state flips. Commenting a rule toggles its marker, and uncommenting the rule toggles it again, so a rule keeps its enabled state across a comment and uncomment cycle. A disabled rule therefore gains a marker while it is a comment. Ctrl+S / Cmd+S triggers the onSave handler.

The toggleRule callback also fires for a comment-only selection that the toggle turns back into rules. A comment line in a mixed selection gets no marker. A line that stays a comment (! ! note) does not change its marker, while a line that becomes empty (!) loses any marker it had, because an empty line cannot hold one. Empty lines are skipped, but a whitespace-only line is not empty and still gets a marker.

On Linux desktops Ctrl+Alt+Arrow is usually captured by the window manager for workspace switching, so those keys never reach the browser there; the mouse gesture and the remaining shortcuts are unaffected.

Tokenizing a Rule

import { getTokenizer } from '@adguard/rules-editor';

// WASM-based (async init, highest precision)
const wasm = new URL('vscode-oniguruma/release/onig.wasm', import.meta.url);
const tokenize = await getTokenizer(wasm);
const tokens = tokenize('||example.org^$important');

Inspecting a Line (scope debugging)

import { inspectLine } from '@adguard/rules-editor';

const wasm = new URL('vscode-oniguruma/release/onig.wasm', import.meta.url);
const segments = await inspectLine(wasm, '||example.org^$important');
// segments: TokenSegment[] — each with text, startIndex, endIndex,
//            scopes (full TextMate scope stack), and token (resolved class)

API

initEditor

async function initEditor(
    element: HTMLTextAreaElement,
    wasm: WasmSource,
    conf: InitEditorConfig,
): Promise<EditorView>

A WasmSource is a URL/string (fetched at runtime), Response, ArrayBuffer, or a Promise/thunk resolving to any of these.

ParameterDescription
elementTextarea element to attach the editor to
wasmA WasmSource (see above). Required for highlight: 'full' (the default); pass undefined when using 'none'
conf.hotkeys.modeOS mode for hotkey mapping ('windows' or 'mac')
conf.hotkeys.toggleRuleCallback for Ctrl/Cmd+/ (toggle rule breakpoint); also fires when comments turn into rules
conf.hotkeys.onSaveCallback for Ctrl/Cmd+S
conf.hotkeys.markerColorCSS color for this editor's breakpoint marker; other editors keep their own color
conf.hotkeys.markerHTMLCustom innerHTML for this editor's breakpoint marker; other editors keep their own HTML
conf.withMultipleSelectionsEnable multi-cursor editing (default true)
conf.withBreakpointsEnable breakpoint gutter
conf.onChangeCalled after each document change
conf.extensionsExtra CodeMirror 6 extensions appended last
conf.highlightHighlight strategy: 'full' (WASM TextMate, default) or 'none' (no WASM)
conf.autofocusFocus the editor on creation (default true); pass false to manage focus yourself

Returns a CodeMirror.EditorView instance. See the CodeMirror 6 docs for events and keymaps.

Hotkeys

By default the editor is focused as soon as it is created (pass conf.autofocus: false to opt out, e.g. when the host page mounts several editors), so editor hotkeys work immediately. Ctrl means Windows/Linux, Cmd means macOS — CodeMirror resolves the modifier from the user's platform automatically, so the bindings below ignore conf.hotkeys.mode (the option only selects the modifiers of the multi-cursor chords — see Multi-cursor editing above). The search panel is rendered at the bottom of the editor by default; pass your own search({ top: true }) through conf.extensions to change that. The panel's buttons and labels are not selectable as text — a double-click or a drag on them selects nothing — while the input fields keep the browser's text selection, so a query can still be selected and copied. The same applies to every CodeMirror dialog opened in the editor, the go-to-line dialog and a dialog a consumer opens with showDialog included: their form controls (input, textarea, select) stay selectable, their other content does not. The rule is a base theme, so it sits below consumer themes — add your own theme to override it — and, like every base theme, it is not limited to this editor: it also applies to other CodeMirror 6 editors on the same page.

  • Ctrl+F / Cmd+F opens the search panel
  • Ctrl+H opens the search panel with the focus in the replace field ("find & replace"; on Windows/Linux only — on macOS Cmd+H is reserved by the OS/browser, so Cmd+Alt+F is the "find & replace" shortcut there)
  • Ctrl+Alt+F / Cmd+Alt+F opens the search panel with the focus in the replace field ("find & replace") on every platform
  • F3 or Ctrl+G finds the next match; Shift+F3 or Ctrl+Shift+G finds the previous one (on macOS: Cmd+G / Cmd+Shift+G). On Windows/Linux the previous editor's Ctrl+K / Ctrl+Shift+K chords work as well; on macOS Ctrl+K keeps its "delete to line end" default
  • Escape closes the search panel
  • Ctrl+Alt+G / Cmd+Alt+G moves the cursor to a line with a given number ("go to line"); the previous editor's Ctrl+L / Cmd+L works as well
  • Alt+Up / Alt+Down moves the selected lines up or down
  • Shift+Alt+Up / Shift+Alt+Down copies the selected lines up or down (Cmd+Option+Up / Cmd+Option+Down on macOS, as in the previous editor)
  • Ctrl+D / Cmd+D deletes the current line or selection
  • Ctrl+S / Cmd+S triggers the conf.hotkeys.onSave callback
  • Ctrl+/ / Cmd+/ toggles !/# comments on the selected lines and the enabled-rule marker on every line whose rule state flips, so a rule keeps its enabled state across a comment and uncomment cycle

Note: the chords restored from the previous (Ace-based) editor are registered before the CodeMirror defaults, so they win where both bind the same key: the macOS copy-lines chord Cmd+Option+Arrow supersedes "add cursor above/below", Ctrl+D / Cmd+D supersedes "select next occurrence" with "delete line", and on Windows/Linux Ctrl+Shift+K supersedes "delete line" with "find previous". "Select all occurrences" (Ctrl+Shift+L / Cmd+Shift+L) is left as CodeMirror binds it — it acts on the current selection and does nothing while no text is selected.

Like the search bindings (Ctrl+F, F3, Ctrl+G, Escape), the find & replace, save, and comment-toggle shortcuts also work while the focus is inside the open search panel.

The built-in keymaps are registered before conf.extensions. The AdGuard bindings (line operations, multi-cursor, find & replace, save, and comment toggle) run at Prec.high, and at equal precedence the earlier extension wins, so a Prec.high binding added through conf.extensions cannot shadow them — the built-in binding is consulted first. The stock CodeMirror keymaps (defaultKeymap, historyKeymap, searchKeymap) run at the default precedence instead, so a Prec.high binding in conf.extensions does shadow them — Mod-f from searchKeymap is one example. To override an AdGuard binding as well, raise the precedence of your keymap above the built-ins with Prec.highest(...):

import { Prec } from '@codemirror/state';
import { keymap } from '@codemirror/view';

extensions: [
    // Overrides the AdGuard `Prec.high` bindings (and the stock keymaps).
    Prec.highest(keymap.of([{ key: 'Mod-s', run: mySaveCommand }])),
]

getTokenizer

async function getTokenizer(
    wasm: WasmSource,
): Promise<(rule: string) => RuleTokens>
ParameterDescription
wasmA WasmSource (see above)

Returns a function that accepts a rule string and returns RuleTokens ({ str: string, token: Token | null }[]).

inspectLine

async function inspectLine(
    wasm: WasmSource,
    line: string,
    scopeName?: string,
): Promise<TokenSegment[]>
ParameterDescription
wasmA WasmSource (see above)
lineThe line of filter rule text to tokenize
scopeNameGrammar scope; defaults to text.adblock

Returns a contiguous, gap-free array of TokenSegment objects covering the input line. Each segment has text, startIndex, endIndex, scopes (full scope stack), and token (resolved class or null).

Rendering tokens to HTML (display-only)

For read-only views (e.g. a virtualized list of rule rows) you can render a token list to colorized HTML whose classes match the editor — without creating a CodeMirror editor per row. Set white-space: pre on the container to preserve spacing.

renderTokensToHtml

function renderTokensToHtml(
    tokens: RuleTokens,
    options?: RenderOptions,
): string
ParameterDescription
tokensToken list from getTokenizer
options.highlightStyleHighlightStyle or array; defaults to defaultHighlightStyle

Returns an HTML string safe for innerHTML/dangerouslySetInnerHTML.

getHtmlRenderer

async function getHtmlRenderer(
    wasm: WasmSource,
    options?: RenderOptions,
): Promise<(rule: string, search?: SearchHighlightOptions) => string>
ParameterDescription
wasmA WasmSource (see above)
options.highlightStyleSame as renderTokensToHtml

Returns an async factory that initializes the grammar once, then returns a synchronous (rule, search?) => html function for full-precision (WASM) highlighting reusable across many rows.

The returned function accepts an optional search argument to highlight a search term within the rule:

interface SearchHighlightOptions {
    searchTerm?: string;     // plain-text, case-insensitive
    searchClassName?: string; // CSS class on each matched chunk
}

When searchTerm is a non-empty string, every case-insensitive occurrence — including matches that span multiple tokens — is wrapped in a <span> carrying searchClassName. Omitting search (or passing an empty term) leaves the output identical to plain rendering. Both the matched text and searchClassName are HTML-escaped.

const render = await getHtmlRenderer(wasm);
// Plain rendering — unchanged from previous versions:
const html = render('||example.org^');
// With search highlighting:
const highlighted = render('||example.org^', {
    searchTerm: 'example',
    searchClassName: 'search-hit',
});

mountHighlightStyle

function mountHighlightStyle(
    highlightStyle?: HighlightStyle,
    root?: Document | ShadowRoot,
): void
ParameterDescription
highlightStyleStyle whose CSS to mount; defaults to defaultHighlightStyle
rootTarget document or shadow root; defaults to document (no-ops in non-browser envs)

Mounts a HighlightStyle's CSS so emitted classes are colorized without an editor. Call once; repeated calls are idempotent.

RenderOptions

interface RenderOptions {
    highlightStyle?: HighlightStyle | HighlightStyle[];
}

Pass a custom HighlightStyle (e.g. oneDarkHighlightStyle) to match a custom editor theme.

Error Classes

ClassDescription
WasmLoadErrorThrown when the Oniguruma WASM binary fails to load
GrammarNotFoundErrorThrown when a grammar scope has no registration

Peer Dependencies

PackageVersion
vscode-oniguruma^2.0.1
@codemirror/commands^6.10.3
@codemirror/language^6.12.3
@codemirror/search^6.7.0
@codemirror/state^6.6.0
@codemirror/view^6.43.0
@lezer/highlight^1.2.3

Documentation

版本与发布记录

@adguard/rules-editor 共发布 27 个版本,首次发布于 2023/10/20;过去 12 个月发布了 13 个版本。

版本发布日期距今
2.0.3latest2026/10/2315 天前
2.0.3-beta.2beta2026/10/2216 天前
2.0.3-beta.12026/10/1722 天前
2.0.3-beta.02026/10/1524 天前
2.0.22026/09/072 个月前
2.0.12026/08/192 个月前

其他发布通道:alpha → 2.0.0-alpha.1,beta → 2.0.3-beta.2。

关于 @adguard/rules-editor 的常见问题

@adguard/rules-editor 是什么?

User rules text editor based on Codemirror and AdGuard textmate highlight

如何安装 @adguard/rules-editor?

在项目目录运行 npm install @adguard/rules-editor,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@codemirror/view(^6.43.0)、@lezer/highlight(^1.2.3)、vscode-oniguruma(^2.0.1)、@codemirror/state(^6.6.0)、@codemirror/search(^6.7.0)、@codemirror/commands(^6.10.3)、@codemirror/language(^6.12.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@adguard/rules-editor 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adguard/rules-editor 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@adguard/rules-editor 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.22.2。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adguard/rules-editor 可以商用吗?

@adguard/rules-editor 使用 GPL-3.0-only 许可。强 Copyleft:分发包含该代码的软件时,整个作品需以 GPL-3.0 兼容许可开源,并附带专利与反锁定条款。仅内部使用不触发此义务。以上为概括,不构成法律意见,请以许可原文为准。

@adguard/rules-editor 的下载量有多少?

根据 npm 官方下载统计,@adguard/rules-editor 在 2026/10/05 – 2026/11/03 这 30 天内被下载 2,413 次,日均约 80 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adguard/rules-editor 还在维护吗?

最新版本 2.0.3 发布于 2026/10/23(15 天前);至今共发布 27 个版本,其中过去 12 个月发布了 13 个;首次发布于 2023/10/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。