diff --git a/docs/design/promptly.md b/docs/design/promptly.md index 87c663805..fc9f71c3f 100644 --- a/docs/design/promptly.md +++ b/docs/design/promptly.md @@ -6587,7 +6587,6 @@ packages/chrome/ | Handlebars braces | Orange | `{{`, `}}` | | Handlebars helper | Purple | `#if`, `#each`, `#role` | | Variable | Cyan | `{{ name }}` | -| Dotprompt marker | Magenta | `<<>>` | | Comment | Gray italic | `{{! comment }}` | | Component | Status | Location | diff --git a/packages/codemirror/README.md b/packages/codemirror/README.md index 5861cc115..f9be44946 100644 --- a/packages/codemirror/README.md +++ b/packages/codemirror/README.md @@ -5,7 +5,7 @@ CodeMirror 6 language support for Dotprompt (`.prompt`) files. ## Features - **Syntax Highlighting**: YAML frontmatter, Handlebars templates, Dotprompt - markers + helpers - **Autocompletion**: Helpers, frontmatter fields, model names - **Theming**: Dark and light theme support @@ -40,6 +40,12 @@ pnpm install pnpm run build ``` +Run the completion tests (uses the workspace root `vitest`): + +```bash +pnpm exec vitest run +``` + ## License Apache-2.0 diff --git a/packages/codemirror/samples/08-sections-thinking.prompt b/packages/codemirror/samples/08-sections-thinking.prompt index d08127726..61cee633d 100644 --- a/packages/codemirror/samples/08-sections-thinking.prompt +++ b/packages/codemirror/samples/08-sections-thinking.prompt @@ -55,7 +55,6 @@ Let me think through this step by step: 1. First, I'll identify the key components of the problem 2. Then, I'll consider different approaches 3. Finally, I'll evaluate and select the best solution -{{/section}} {{/if}} Based on my analysis, here is my answer: diff --git a/packages/codemirror/samples/10-kitchen-sink.prompt b/packages/codemirror/samples/10-kitchen-sink.prompt index 6430bbd5f..424306439 100644 --- a/packages/codemirror/samples/10-kitchen-sink.prompt +++ b/packages/codemirror/samples/10-kitchen-sink.prompt @@ -128,7 +128,6 @@ Let me analyze the project requirements: - Budget constraint: ${{budget}} {{/if}} {{/with}} -{{/section}} Based on my analysis, here is the recommended project plan: diff --git a/packages/codemirror/src/completions.test.ts b/packages/codemirror/src/completions.test.ts new file mode 100644 index 000000000..6f088dcb0 --- /dev/null +++ b/packages/codemirror/src/completions.test.ts @@ -0,0 +1,131 @@ +/** + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + CompletionContext, + insertCompletionText, +} from '@codemirror/autocomplete'; +import { EditorState, type Transaction } from '@codemirror/state'; +import type { EditorView } from '@codemirror/view'; +import { describe, expect, it } from 'vitest'; +import { dotpromptCompletions } from './completions'; + +/** + * Runs the completion source on `docWithCursor` (`|` marks the cursor), accepts + * the option labelled `label` and returns the resulting doc plus the selected + * text (the active snippet field, if any). + */ +function accept( + docWithCursor: string, + label: string +): { doc: string; selected: string } { + const pos = docWithCursor.indexOf('|'); + const doc = docWithCursor.slice(0, pos) + docWithCursor.slice(pos + 1); + let state = EditorState.create({ doc, selection: { anchor: pos } }); + + const result = dotpromptCompletions(new CompletionContext(state, pos, true)); + const option = result?.options.find((o) => o.label === label); + if (!result || !option) { + throw new Error( + `no "${label}" completion for ${JSON.stringify(docWithCursor)}` + ); + } + const to = result.to ?? pos; + + if (typeof option.apply === 'function') { + // A real EditorView needs a DOM. Snippet apply functions only read `state` + // and call `dispatch`, so a minimal stand-in is enough here. + const editor = { + get state(): EditorState { + return state; + }, + dispatch(tr: Transaction): void { + state = tr.state; + }, + }; + option.apply(editor as unknown as EditorView, option, result.from, to); + } else { + const text = option.apply ?? option.label; + state = state.update( + insertCompletionText(state, text, result.from, to) + ).state; + } + + const sel = state.selection.main; + return { + doc: state.doc.toString(), + selected: state.sliceDoc(sel.from, sel.to), + }; +} + +describe('helper completions after {{', () => { + it.each([ + ['{{ro|', 'role', '{{role "system"}}\n', 'system'], + ['{{sec|', 'section', '{{section "name"}}\n', 'name'], + ['{{i|', 'if', '{{#if condition}}\n \n{{/if}}', 'condition'], + ['{{ea|', 'each', '{{#each items}}\n {{this}}\n{{/each}}', 'items'], + [ + '{{ifE|', + 'ifEquals', + '{{#ifEquals value1 value2}}\n \n{{/ifEquals}}', + 'value1', + ], + ['{{js|', 'json', '{{json value}}', 'value'], + ['{{me|', 'media', '{{media url=url}}', 'url'], + ['{{loo|', 'lookup', '{{lookup object key}}', 'object'], + ['{{hi|', 'history', '{{history}}', ''], + ['{{el|', 'else', '{{else}}', ''], + ])('%s + %s', (input, label, doc, selected) => { + expect(accept(input, label)).toEqual({ doc, selected }); + }); + + it('replaces an auto-closed }} instead of doubling it', () => { + expect(accept('{{ro|}}', 'role')).toEqual({ + doc: '{{role "system"}}\n', + selected: 'system', + }); + expect(accept('a {{hi|}} b', 'history').doc).toBe('a {{history}} b'); + }); + + it('indents block bodies relative to the current line', () => { + expect(accept(' {{w|', 'with').doc).toBe( + ' {{#with context}}\n \n {{/with}}' + ); + }); +}); + +describe('block open/close completions', () => { + it('inserts only the helper name after {{#', () => { + expect(accept('{{#i|', 'if').doc).toBe('{{#if'); + expect(accept('{{#unlessE|}}', 'unlessEquals').doc).toBe( + '{{#unlessEquals}}' + ); + }); + + it('inserts only the block name after {{/', () => { + expect(accept('{{/ea|', 'each').doc).toBe('{{/each'); + }); +}); + +describe('role snippets for a bare word', () => { + it('replaces the word with an inline role helper', () => { + expect(accept('Intro\nsys|', 'system').doc).toBe( + 'Intro\n{{role "system"}}\n' + ); + }); +}); diff --git a/packages/codemirror/src/completions.ts b/packages/codemirror/src/completions.ts index f00ad6bc4..267f64f0b 100644 --- a/packages/codemirror/src/completions.ts +++ b/packages/codemirror/src/completions.ts @@ -17,131 +17,149 @@ */ import { - Completion, - CompletionContext, - CompletionResult, + type Completion, + type CompletionContext, + type CompletionResult, + snippet, } from '@codemirror/autocomplete'; +/** + * Builds a completion for the helper name typed right after `{{`. + * + * The completion range covers only the typed word (not the `{{`), so templates + * start at the helper name and must not repeat the opening braces. Templates + * use CodeMirror snippet syntax: `${name}` is a field pre-filled with `name`, + * `${}` an empty one. Only `${` / `#{` start a field, so the literal Handlebars + * braces need no escaping. + * + * Every template closes its own expression, so a `}}` that already follows the + * cursor (e.g. auto-inserted by `closeBrackets` after typing `{{`) is replaced + * instead of doubled. + */ +function helperCompletion( + template: string, + completion: Completion +): Completion { + const applySnippet = snippet(template); + return { + ...completion, + apply: (view, picked, from, to) => { + const end = view.state.sliceDoc(to, to + 2) === '}}' ? to + 2 : to; + applySnippet(view, picked, from, end); + }, + }; +} + /** * Handlebars helper completions. */ const HANDLEBARS_HELPERS: Completion[] = [ - { + helperCompletion('#if ${condition}}}\n\t${}\n{{/if}}', { label: 'if', type: 'keyword', info: 'Conditionally renders content when the condition is truthy.', - apply: '{{#if ${condition}}}\n\t\n{{/if}}', - }, - { + }), + helperCompletion('#unless ${condition}}}\n\t${}\n{{/unless}}', { label: 'unless', type: 'keyword', info: 'Inverse of if - renders content when the condition is falsy.', - apply: '{{#unless ${condition}}}\n\t\n{{/unless}}', - }, - { + }), + helperCompletion('#each ${items}}}\n\t{{this}}${}\n{{/each}}', { label: 'each', type: 'keyword', info: 'Iterates over arrays or objects.', - apply: '{{#each ${items}}}\n\t{{this}}\n{{/each}}', - }, - { + }), + helperCompletion('#with ${context}}}\n\t${}\n{{/with}}', { label: 'with', type: 'keyword', info: 'Changes the current context for the enclosed block.', - apply: '{{#with ${context}}}\n\t\n{{/with}}', - }, - { + }), + helperCompletion('else}}', { label: 'else', type: 'keyword', info: 'Else branch for if/unless blocks.', - apply: '{{else}}', - }, - { + }), + helperCompletion('log ${value}}}', { label: 'log', type: 'function', info: 'Logs a value to the console for debugging.', - apply: '{{log ${value}}}', - }, - { + }), + helperCompletion('lookup ${object} ${key}}}', { label: 'lookup', type: 'function', info: 'Dynamically looks up a value by key from an object.', - apply: '{{lookup ${object} ${key}}}', - }, + }), ]; /** * Dotprompt-specific helper completions. */ const DOTPROMPT_HELPERS: Completion[] = [ - { + helperCompletion('role "${system}"}}\n${}', { label: 'role', type: 'keyword', - info: 'Defines a message with a specific role (system, user, model).', - apply: '{{#role "${role}"}}\n\t\n{{/role}}', + info: 'Starts a message with a specific role (system, user, model).', boost: 10, - }, - { + }), + helperCompletion('json ${value}}}', { label: 'json', type: 'function', info: 'Serializes a value to JSON format.', - apply: '{{ json ${value} }}', - }, - { + }), + helperCompletion('history}}', { label: 'history', type: 'function', info: 'Inserts the conversation history at this point.', - apply: '{{history}}', - }, - { + }), + helperCompletion('section "${name}"}}\n${}', { label: 'section', type: 'keyword', - info: 'Defines a named section that can be referenced elsewhere.', - apply: '{{#section "${name}"}}\n\t\n{{/section}}', - }, - { + info: 'Starts a named section that can be referenced elsewhere.', + }), + helperCompletion('media url=${url}}}', { label: 'media', type: 'function', info: 'Embeds media content (images, audio, video) by URL.', - apply: '{{media url=${url}}}', - }, - { + }), + helperCompletion('#ifEquals ${value1} ${value2}}}\n\t${}\n{{/ifEquals}}', { label: 'ifEquals', type: 'keyword', info: 'Renders content when two values are equal.', - apply: '{{#ifEquals ${value1} ${value2}}}\n\t\n{{/ifEquals}}', - }, - { - label: 'unlessEquals', - type: 'keyword', - info: 'Renders content when two values are NOT equal.', - apply: '{{#unlessEquals ${value1} ${value2}}}\n\t\n{{/unlessEquals}}', - }, + }), + helperCompletion( + '#unlessEquals ${value1} ${value2}}}\n\t${}\n{{/unlessEquals}}', + { + label: 'unlessEquals', + type: 'keyword', + info: 'Renders content when two values are NOT equal.', + } + ), ]; /** - * Role snippet completions. + * Role snippet completions, offered for a bare word outside `{{ }}`. The range + * is that word, so a plain string `apply` inserting the whole helper is right. */ const ROLE_SNIPPETS: Completion[] = [ { label: 'system', type: 'text', - info: "System role block - sets the AI's behavior and context.", - apply: '{{#role "system"}}\n\t\n{{/role}}', + info: "System message - sets the AI's behavior and context.", + apply: '{{role "system"}}\n', boost: 5, }, { label: 'user', type: 'text', - info: 'User role block - represents user input.', - apply: '{{#role "user"}}\n\t\n{{/role}}', + info: 'User message - represents user input.', + apply: '{{role "user"}}\n', boost: 5, }, { label: 'model', type: 'text', - info: 'Model role block - represents AI responses (for few-shot examples).', - apply: '{{#role "model"}}\n\t\n{{/role}}', + info: 'Model message - represents AI responses (for few-shot examples).', + apply: '{{role "model"}}\n', boost: 5, }, ]; @@ -316,14 +334,15 @@ export function dotpromptCompletions( const [, prefix, word] = handlebarsMatch; const from = pos - word.length; - // After {{# - block helpers + // After {{# - block helpers. `role` and `section` are inline helpers (a + // block form would discard its content), so they are not offered here. if (prefix === '#') { const blockHelpers = [ ...HANDLEBARS_HELPERS.filter((h) => ['if', 'unless', 'each', 'with'].includes(h.label) ), ...DOTPROMPT_HELPERS.filter((h) => - ['role', 'section', 'ifEquals', 'unlessEquals'].includes(h.label) + ['ifEquals', 'unlessEquals'].includes(h.label) ), ].map((h) => ({ ...h, @@ -343,8 +362,6 @@ export function dotpromptCompletions( 'unless', 'each', 'with', - 'role', - 'section', 'ifEquals', 'unlessEquals', ].map((name) => ({ diff --git a/packages/codemirror/src/language.ts b/packages/codemirror/src/language.ts index c58e8575d..5089eb172 100644 --- a/packages/codemirror/src/language.ts +++ b/packages/codemirror/src/language.ts @@ -155,11 +155,6 @@ export const dotpromptStreamParser = { return 'comment'; } - // Dotprompt markers - if (stream.match(/<<]+>>>/)) { - return 'keyword'; - } - // Handlebars block start {{#helper if (stream.match(/\{\{#/)) { state.context = 'handlebars'; diff --git a/packages/emacs/README.md b/packages/emacs/README.md index 06ec15b11..ae88d7497 100644 --- a/packages/emacs/README.md +++ b/packages/emacs/README.md @@ -4,7 +4,7 @@ Provides a major mode for editing Dotprompt (`.prompt`) files with syntax highli ## Features -- **Syntax Highlighting**: Handlebars helpers, partials, Dotprompt markers +- **Syntax Highlighting**: Handlebars helpers (including Dotprompt helpers), partials - **LSP Integration**: Diagnostics, formatting, hover via eglot or lsp-mode - **Format Buffer**: `C-c C-f` or `M-x dotprompt-format-buffer` - **Format on Save**: Optional automatic formatting diff --git a/packages/emacs/dotprompt-mode.el b/packages/emacs/dotprompt-mode.el index 1228e9e80..73d6fd1e4 100644 --- a/packages/emacs/dotprompt-mode.el +++ b/packages/emacs/dotprompt-mode.el @@ -23,7 +23,10 @@ ;;; Commentary: ;; Major mode for editing Dotprompt files (.prompt). -;; Provides syntax highlighting for markers, helpers, and partials. +;; Provides syntax highlighting for helpers and partials. Raw +;; `<<>>' text is intentionally left unhighlighted: runtimes +;; only honor nonce-tagged markers emitted by the helpers, so a literal +;; marker in a template is plain text. ;; Includes LSP integration via eglot or lsp-mode for diagnostics, ;; formatting, and hover documentation when `promptly` is installed. ;; @@ -69,9 +72,6 @@ ;; YAML numeric values '(":\\s-+\\([0-9]+\\.?[0-9]*\\)$" 1 font-lock-constant-face) - ;; Dotprompt markers <<>> etc. - '("<<]+>>>" . font-lock-preprocessor-face) - ;; Handlebars block comments {{!-- ... --}} '("{{!--\\(.\\|\n\\)*?--}}" . font-lock-comment-face) diff --git a/packages/jetbrains/BUILD.bazel b/packages/jetbrains/BUILD.bazel index 64b62ff6d..4af708627 100644 --- a/packages/jetbrains/BUILD.bazel +++ b/packages/jetbrains/BUILD.bazel @@ -16,7 +16,7 @@ """Build rules for the Dotprompt JetBrains plugin.""" -load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") +load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library", "kt_jvm_test") package(default_visibility = ["//visibility:public"]) @@ -58,6 +58,21 @@ kt_jvm_library( ], ) +# Lexer unit tests. The lexer only needs IElementType/LexerBase from the +# platform jars, so this runs as a plain JUnit test without an IDE fixture. +kt_jvm_test( + name = "DotpromptLexerTest", + size = "small", + srcs = ["src/test/kotlin/com/google/dotprompt/DotpromptLexerTest.kt"], + test_class = "com.google.dotprompt.DotpromptLexerTest", + deps = [ + ":dotprompt-intellij", + "@intellij_maven//:com_jetbrains_intellij_platform_core", + "@intellij_maven//:com_jetbrains_intellij_platform_util", + "@maven//:junit_junit", + ], +) + # Export all source files for IDE support filegroup( name = "sources", diff --git a/packages/jetbrains/README.md b/packages/jetbrains/README.md index 92264d8d6..1f115fc42 100644 --- a/packages/jetbrains/README.md +++ b/packages/jetbrains/README.md @@ -4,7 +4,7 @@ Language support for Dotprompt (`.prompt`) files in JetBrains IDEs (IntelliJ IDE ## Features -- **Syntax Highlighting**: YAML frontmatter, Handlebars templates, Dotprompt markers +- **Syntax Highlighting**: YAML frontmatter keys, Handlebars comments, braces, variables, and helper names (built-ins like `if`/`each` and Dotprompt helpers like `role`, `history`, `section`, `media`) - **LSP Integration**: Real-time diagnostics, formatting, and hover documentation (via LSP4IJ) - **Live Templates**: Type `role`, `if`, `each`, `json` + Tab for quick insertions - **Code Comments**: Block comment support using `{{! ... }}` @@ -49,6 +49,12 @@ bazel build //packages/jetbrains:dotprompt-intellij This produces `bazel-bin/packages/jetbrains/dotprompt-intellij.jar`. +Run the lexer tests with: + +```bash +bazel test //packages/jetbrains:DotpromptLexerTest +``` + > **Note**: For full plugin packaging (with plugin.xml, icons, LSP4IJ integration), > use the Gradle build. The Bazel target is useful for incremental compilation > during development and IDE integration. @@ -80,10 +86,10 @@ Type these abbreviations and press Tab to expand: | Abbreviation | Expands To | |--------------|------------| -| `role` | Role block with customizable role name | -| `system` | System role block | -| `user` | User role block | -| `model` | Model role block | +| `role` | `{{role "..."}}` with customizable role name | +| `system` | `{{role "system"}}` | +| `user` | `{{role "user"}}` | +| `model` | `{{role "model"}}` | | `if` | Handlebars if block | | `ifelse` | Handlebars if-else block | | `unless` | Handlebars unless block | @@ -92,7 +98,7 @@ Type these abbreviations and press Tab to expand: | `json` | JSON serialization helper | | `media` | Media embedding helper | | `history` | History insertion | -| `section` | Named section block | +| `section` | `{{section "..."}}` | | `partial` | Partial template inclusion | | `comment` | Handlebars comment | | `prompt` | Complete prompt template | diff --git a/packages/jetbrains/build.gradle.kts b/packages/jetbrains/build.gradle.kts index b5f308df2..52edabcdb 100644 --- a/packages/jetbrains/build.gradle.kts +++ b/packages/jetbrains/build.gradle.kts @@ -28,6 +28,8 @@ version = "0.1.0" repositories { mavenCentral() } +dependencies { testImplementation("junit:junit:4.13.2") } + intellij { version.set("2024.1") type.set("IC") // IntelliJ IDEA Community Edition diff --git a/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptLexer.kt b/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptLexer.kt index b648a8557..f3382c07a 100644 --- a/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptLexer.kt +++ b/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptLexer.kt @@ -21,12 +21,33 @@ import com.intellij.psi.tree.IElementType /** * Simple lexer for Dotprompt files. - * + * * This lexer recognizes: - * - YAML frontmatter delimiters (---) - * - Handlebars expressions ({{ ... }}) - * - Dotprompt markers (<<>>) - * - Comments ({{! ... }}) + * - Header comments (`#` lines before the first frontmatter delimiter) + * - YAML frontmatter delimiters (`---`) and top-level YAML keys + * - Handlebars comments (`{{! ... }}`) + * - Handlebars expressions in the template body: + * - `{{`, `{{{`, `{{~` plus an optional `#`, `/`, `>`, `^` or `&` as HANDLEBARS_OPEN + * - the name in helper position (right after the opener or `(`) as + * HANDLEBARS_HELPER when it is a Handlebars built-in or Dotprompt helper + * (`{{role "system"}}`, `{{#if x}}`, `{{else if y}}`, `{{/each}}`) + * - any other identifier or path (`name`, `user.name`, `@root`, `this`, + * `../x`) as HANDLEBARS_VARIABLE + * - `}}`, `~}}` (and `}}}` for triple-stash) as HANDLEBARS_CLOSE + * - string/number/boolean literals, whitespace and punctuation as TEXT + * + * Inside frontmatter `{{` is still only HANDLEBARS_OPEN followed by TEXT. + * + * Raw `<<>>` text is deliberately lexed as TEXT: runtimes only + * honor nonce-tagged markers emitted by the helpers ({{role}}, {{history}}, + * {{section}}, {{media}}), so a literal marker in a template is plain text. + * + * The highlighter restarts lexing from a token's start offset with the value + * [getState] reported for that token, so [getState] returns the state at the + * start of the current token (like FlexAdapter), and everything needed to + * resume (section of the file, whether we are inside an expression, + * triple-stash, helper position) lives in that int. See the `STATE_*` / + * `FLAG_*` constants. */ class DotpromptLexer : LexerBase() { private var buffer: CharSequence = "" @@ -34,12 +55,38 @@ class DotpromptLexer : LexerBase() { private var tokenStart: Int = 0 private var tokenEnd: Int = 0 private var tokenType: IElementType? = null + /** State the lexer was in when the current token started. */ + private var tokenStartState: Int = STATE_HEADER private var state: Int = STATE_HEADER companion object { + // Low bits: which part of the file we are in. private const val STATE_HEADER = 0 private const val STATE_CONTENT = 1 private const val STATE_FRONTMATTER = 2 + private const val MODE_MASK = 0x3 + + // Flags OR-ed on top of the mode while inside `{{ ... }}`. + private const val FLAG_EXPR = 0x4 + /** Opened with `{{{`, so the closer is `}}}`. */ + private const val FLAG_TRIPLE = 0x8 + /** The next identifier is in helper position (after the opener, `(` or `else`). */ + private const val FLAG_HEAD = 0x10 + + /** Handlebars built-ins plus the helpers registered by Dotprompt runtimes. */ + private val KNOWN_HELPERS = setOf( + "if", "unless", "each", "with", "else", "log", "lookup", + "role", "history", "section", "media", "json", "ifEquals", "unlessEquals", + ) + + private val LITERALS = setOf("true", "false", "null", "undefined") + private val NUMBER = Regex("-?[0-9]+(\\.[0-9]+)?") + + /** Characters Handlebars excludes from identifiers (besides whitespace). */ + private const val NON_ID_CHARS = "!\"#%&'()*+,./;<=>@[\\]^`{|}~" + + /** Characters that may follow `{{` (after an optional `~`) to form the opener. */ + private const val OPEN_PREFIXES = "#/>^&" } override fun start(buffer: CharSequence, startOffset: Int, endOffset: Int, initialState: Int) { @@ -51,7 +98,7 @@ class DotpromptLexer : LexerBase() { advance() } - override fun getState(): Int = state + override fun getState(): Int = tokenStartState override fun getTokenType(): IElementType? = tokenType @@ -59,13 +106,29 @@ class DotpromptLexer : LexerBase() { override fun getTokenEnd(): Int = tokenEnd + private val mode: Int + get() = state and MODE_MASK + + private fun hasFlag(flag: Int): Boolean = (state and flag) != 0 + override fun advance() { tokenStart = tokenEnd + tokenStartState = state if (tokenStart >= bufferEnd) { tokenType = null return } + if (hasFlag(FLAG_EXPR)) { + if (lookingAt("{{")) { + // Unterminated expression: recover by treating this as a new opener. + state = mode + } else { + advanceInExpression() + return + } + } + // Check for header comments (lines starting with # before first frontmatter) if (state == STATE_HEADER && (tokenStart == 0 || buffer[tokenStart - 1] == '\n') && buffer[tokenStart] == '#') { tokenEnd = findEndOfLine() @@ -85,16 +148,8 @@ class DotpromptLexer : LexerBase() { return } - // Check for Dotprompt marker - if (lookingAt("<< bufferEnd) return false - for (i in s.indices) { - if (buffer[tokenStart + i] != s[i]) return false + /** Consumes `{{`, an optional `{`, an optional `~` and an optional opener prefix. */ + private fun lexOpener() { + var pos = tokenStart + 2 + var flags = FLAG_EXPR or FLAG_HEAD + if (pos < bufferEnd && buffer[pos] == '{') { + flags = flags or FLAG_TRIPLE + pos++ } - return true + if (pos < bufferEnd && buffer[pos] == '~') pos++ + if (pos < bufferEnd && buffer[pos] in OPEN_PREFIXES) pos++ + tokenEnd = pos + state = mode or flags + } + + private fun advanceInExpression() { + val c = buffer[tokenStart] + + val closeLen = closerLength() + if (closeLen > 0) { + tokenEnd = tokenStart + closeLen + tokenType = DotpromptTokenTypes.HANDLEBARS_CLOSE + state = mode + return + } + + if (c.isWhitespace()) { + var pos = tokenStart + 1 + while (pos < bufferEnd && buffer[pos].isWhitespace()) pos++ + tokenEnd = pos + tokenType = DotpromptTokenTypes.TEXT + return + } + + if (c == '"' || c == '\'') { + tokenEnd = findEndOfString(c) + tokenType = DotpromptTokenTypes.TEXT + clearFlag(FLAG_HEAD) + return + } + + if (c == '(') { + tokenEnd = tokenStart + 1 + tokenType = DotpromptTokenTypes.TEXT + state = state or FLAG_HEAD + return + } + + if (isPathStart(c)) { + tokenEnd = findEndOfPath() + val text = buffer.subSequence(tokenStart, tokenEnd).toString() + val inHead = hasFlag(FLAG_HEAD) + tokenType = when { + text in LITERALS || NUMBER.matches(text) -> DotpromptTokenTypes.TEXT + inHead && text in KNOWN_HELPERS -> DotpromptTokenTypes.HANDLEBARS_HELPER + else -> DotpromptTokenTypes.HANDLEBARS_VARIABLE + } + // `{{else if x}}`: the name after `else` is still in helper position. + if (!(inHead && text == "else")) clearFlag(FLAG_HEAD) + return + } + + // Anything else (`=`, `|`, `)`, a stray `}` or `~`, ...) is single-char TEXT. + tokenEnd = tokenStart + 1 + tokenType = DotpromptTokenTypes.TEXT + clearFlag(FLAG_HEAD) + } + + private fun clearFlag(flag: Int) { + state = state and flag.inv() } - private fun findEndOfMarker(): Int { + /** Length of the expression closer at [tokenStart], or 0 if there is none. */ + private fun closerLength(): Int { var pos = tokenStart - while (pos < bufferEnd - 2) { - if (buffer[pos] == '>' && buffer[pos + 1] == '>' && buffer[pos + 2] == '>') { - return pos + 3 + if (pos < bufferEnd && buffer[pos] == '~') pos++ + if (!lookingAtPos(pos, "}}")) return 0 + pos += 2 + if (hasFlag(FLAG_TRIPLE) && pos < bufferEnd && buffer[pos] == '}') pos++ + return pos - tokenStart + } + + private fun isIdChar(c: Char): Boolean = !c.isWhitespace() && c !in NON_ID_CHARS + + private fun isPathStart(c: Char): Boolean = isIdChar(c) || c == '@' || c == '.' || c == '[' + + /** Consumes a path like `@root.user.name`, `../x`, `this` or `items.[0]`. */ + private fun findEndOfPath(): Int { + var pos = tokenStart + if (buffer[pos] == '@') pos++ + while (pos < bufferEnd) { + val c = buffer[pos] + when { + isIdChar(c) || c == '.' || c == '/' -> pos++ + c == '[' -> { + // Literal segment; stop at `]`, a closer or end of line if unterminated. + pos++ + while (pos < bufferEnd && buffer[pos] != ']' && buffer[pos] != '\n' && !lookingAtPos(pos, "}}")) pos++ + if (pos < bufferEnd && buffer[pos] == ']') pos++ + } + else -> return pos } + } + return pos + } + + /** + * Ends after the closing quote. An unterminated string stops before `}}` so + * the closer still gets its own token; this also means a string literal that + * itself contains `}}` is split, which is rare enough to accept. + */ + private fun findEndOfString(quote: Char): Int { + var pos = tokenStart + 1 + while (pos < bufferEnd) { + val c = buffer[pos] + if (c == '\\' && pos + 1 < bufferEnd) { + pos += 2 + continue + } + if (c == quote) return pos + 1 + if (lookingAtPos(pos, "}}")) return pos pos++ } return bufferEnd } + private fun lookingAt(s: String): Boolean = lookingAtPos(tokenStart, s) + private fun findEndOfHandlebars(): Int { var pos = tokenStart while (pos < bufferEnd - 1) { @@ -174,9 +341,8 @@ class DotpromptLexer : LexerBase() { private fun findNextToken(): Int { var pos = tokenStart + 1 while (pos < bufferEnd) { - if (lookingAtPos(pos, "---") || - lookingAtPos(pos, "{{") || - lookingAtPos(pos, "<< HANDLEBARS_BRACE_KEYS DotpromptTokenTypes.HANDLEBARS_HELPER -> HANDLEBARS_HELPER_KEYS DotpromptTokenTypes.HANDLEBARS_VARIABLE -> HANDLEBARS_VARIABLE_KEYS - DotpromptTokenTypes.MARKER -> MARKER_KEYS DotpromptTokenTypes.COMMENT -> COMMENT_KEYS DotpromptTokenTypes.HEADER_COMMENT -> COMMENT_KEYS else -> EMPTY_KEYS @@ -89,10 +88,6 @@ class DotpromptSyntaxHighlighter : SyntaxHighlighterBase() { "DOTPROMPT_HANDLEBARS_VARIABLE", DefaultLanguageHighlighterColors.IDENTIFIER ) - private val MARKER = TextAttributesKey.createTextAttributesKey( - "DOTPROMPT_MARKER", - DefaultLanguageHighlighterColors.METADATA - ) private val COMMENT = TextAttributesKey.createTextAttributesKey( "DOTPROMPT_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT @@ -104,7 +99,6 @@ class DotpromptSyntaxHighlighter : SyntaxHighlighterBase() { private val HANDLEBARS_BRACE_KEYS = arrayOf(HANDLEBARS_BRACE) private val HANDLEBARS_HELPER_KEYS = arrayOf(HANDLEBARS_HELPER) private val HANDLEBARS_VARIABLE_KEYS = arrayOf(HANDLEBARS_VARIABLE) - private val MARKER_KEYS = arrayOf(MARKER) private val COMMENT_KEYS = arrayOf(COMMENT) } } diff --git a/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptTokenTypes.kt b/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptTokenTypes.kt index dfd3bf4af..d1fa1ba5a 100644 --- a/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptTokenTypes.kt +++ b/packages/jetbrains/src/main/kotlin/com/google/dotprompt/DotpromptTokenTypes.kt @@ -29,7 +29,6 @@ object DotpromptTokenTypes { @JvmField val HANDLEBARS_CLOSE = IElementType("HANDLEBARS_CLOSE", DotpromptLanguage.INSTANCE) @JvmField val HANDLEBARS_HELPER = IElementType("HANDLEBARS_HELPER", DotpromptLanguage.INSTANCE) @JvmField val HANDLEBARS_VARIABLE = IElementType("HANDLEBARS_VARIABLE", DotpromptLanguage.INSTANCE) - @JvmField val MARKER = IElementType("MARKER", DotpromptLanguage.INSTANCE) @JvmField val COMMENT = IElementType("COMMENT", DotpromptLanguage.INSTANCE) @JvmField val HEADER_COMMENT = IElementType("HEADER_COMMENT", DotpromptLanguage.INSTANCE) @JvmField val TEXT = IElementType("TEXT", DotpromptLanguage.INSTANCE) diff --git a/packages/jetbrains/src/main/resources/liveTemplates/Dotprompt.xml b/packages/jetbrains/src/main/resources/liveTemplates/Dotprompt.xml index e3973900b..7eab7e4dc 100644 --- a/packages/jetbrains/src/main/resources/liveTemplates/Dotprompt.xml +++ b/packages/jetbrains/src/main/resources/liveTemplates/Dotprompt.xml @@ -17,8 +17,8 @@ SPDX-License-Identifier: Apache-2.0 --> - -