Skip to content

feat(editor): add JSP syntax highlighting backed by the HTML language service - #11309

Closed
taehwanis wants to merge 3 commits into
stablyai:mainfrom
taehwanis:feat/jsp-language-service
Closed

taehwanis wants to merge 3 commits into
stablyai:mainfrom
taehwanis:feat/jsp-language-service

Conversation

@taehwanis

@taehwanis taehwanis commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

.jsp and .jspf files open as plaintext today — they are not in EXT_TO_LANGUAGE, so detectLanguage() returns 'plaintext' and nothing is highlighted.

This registers a dedicated jsp language with a Monarch tokenizer for directives, scriptlets, expressions, EL and JSTL/custom tags, and attaches Monaco's HTML language service to it.

That second part is the reason this is not just another tokenizer. Monaco already serves Razor and Handlebars through registerHTMLLanguageService because they are "HTML plus server-side template syntax" — exactly what JSP is. Reusing it gives tag completion, hovers, document symbols and syntax-aware folding inside JSP markup, which a tokenizer-only registration silently gives up. The worker route (case 'jsp' in the existing html group) is required rather than optional: MonacoEnvironment.getWorker takes precedence over Monaco's own fallback, so without it every language-service call would reach the plain editor worker and fail.

rename and both formatting providers stay off. They are the ones that act on a parse of the file as HTML, and <% ... %> is not markup — formatting would relocate it and rename would edit spans derived from a mis-parse.

Related: #10858 by @hwantage addresses the same issue with a Monarch tokenizer. I read that PR before writing this, and it is what prompted me to check whether the HTML language service could be attached to a custom language id — that turned out to be the gap this PR closes. If the maintainers prefer that PR's shape, the language-service wiring here can be lifted into it and I am happy to close this one.

Screenshots

Same demo.jsp opened in a build from this branch.

Before — .jsp is not in the extension table, so the file falls back to plaintext:

JSP file rendered as plaintext

After — directives, scriptlets, EL, JSTL tags and the embedded JS/CSS blocks are highlighted:

JSP file with directives, scriptlets, EL and JSTL highlighted

Verified in the running app, not only in tests: typing < inside markup produces HTML tag completions, and folding handles are placed on tag boundaries rather than indentation.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

The two unchecked boxes are explained under Notes.

AI Review Report

Three independent AI review passes were run against this branch — layering/registration, tokenizer correctness, and conventions/security — each checking Monaco's own sources rather than reasoning from memory. They found four defects that are fixed in ffaa740a2:

  • State could leak past its terminator (two paths). tagRest and both attribute-value states had no <%-- rule, so a JSP comment inside a tag (<c:out value="x" <%-- note --%> />) entered the scriptlet state, where --%> was absorbed by the operator character class instead of closing it — Java tokenization then ran to end of file. The same class contained both % and >, so an operator run written against the terminator (<%=i++%>, no spaces) swallowed it. Fixed by adding the comment rule to all three states and giving % a negative lookahead.
  • rename: true edited the buffer from an untrusted parse. It is the only enabled provider that writes, and htmlWorker.doRename() derives its edits from parsing the file as HTML, which scriptlets break. Turned off, which also makes the configuration internally consistent with formatting being off.
  • ignoreCase: true mis-coloured Java identifiers. Carried over from the sibling Vue/Svelte/Astro modules, where it only affects HTML tag matching. JSP is the one language here that tokenizes a case-sensitive language directly, so List list, Map map and String string coloured the variable as a type. Turned off; the four HTML tags that genuinely need case-insensitivity spell the characters out.
  • Two mode-configuration flags were inert. diagnostics and colors are not read by the HTML mode at all (it consumes ten keys; those two are handled only by the css and typescript modes), so an earlier revision of this PR described them as the guard against scriptlet false positives. That was wrong — the actual guard is formatting and rename staying off. The flags are removed and the comment corrected.

Tests grew from 8 to 16 as a result, covering the paths the reviews identified as unprotected: the embedded-language pop contract (Monarch throws, not just mis-colours, if it is missing), match lengths that distinguish the namespaced-tag rule from the generic one, every state's exit delimiter, and a state-reference integrity check.

Cross-platform compatibility (macOS, Linux, Windows) was explicitly checked. Nothing here branches on platform: the change is a language registration plus lookup-table entries, and extension matching already handles both path separators and casing. No keyboard shortcuts, labels, shell behavior, path utilities or Electron platform differences are touched, and nothing is specific to SSH, remote or local hosts, a particular agent, or a git provider. The HTML worker is already bundled and routed, so there is no new dependency; the worker is constructed only when a jsp model exists and is released after idle.

Security Audit

No meaningful risk surface. The change registers a tokenizer and reuses an already-bundled language worker. There is no command execution, no path resolution, no IPC, no auth, no secrets and no dependency change. The tokenizer only classifies text; it never evaluates scriptlets or EL. The regex rules were reviewed individually for catastrophic backtracking — every quantifier sits on a single character class or on an alternation whose branches start with disjoint characters, so there is no nested-quantifier path, and Monarch matches within a single line regardless. No follow-up needed.

Notes

  • pnpm lint: oxlint and the code-quality audits pass. The chain stops later at verify:skill-bundle-manifest, which reports stale generated artifacts under resources/skills/ — a pre-existing state unrelated to this change, and those files are not part of this diff.
  • pnpm test: the full suite on a Windows machine fails a set of pre-existing tests that require a POSIX shell (spawn /bin/sh ENOENT); the count is unchanged by this PR. The test files touched here pass.
  • Scriptlets and EL inside <script> blocks are not highlighted as JSP. Once the tokenizer hands the block to the embedded JavaScript tokenizer, Monarch cannot re-enter host rules — the same limitation Monaco's own HTML mode has. Worth stating explicitly because embedding ${...} in a script block is common in real JSP.
  • Registering the HTML language service twice would create a second worker and provider set — the call has no internal dedupe — so it sits behind the same guard as the language registration, and a test asserts it runs once across repeated calls.
  • mobile/src/session/mobile-file-language.ts has a separate extension table for the mobile surface and is not touched here; it feeds a different highlighter.

… service

Registers a dedicated `jsp` language for .jsp/.jspf with a Monarch tokenizer
covering directives, scriptlets, expressions, EL and JSTL/custom tags, and
routes it to the HTML worker.

Monaco already serves Razor and Handlebars through registerHTMLLanguageService
because they are HTML plus template syntax; JSP is the same shape, so it reuses
that service and keeps tag completion, hovers and folding. Diagnostics and
formatting stay off since the HTML service does not understand scriptlets and
would report them as malformed markup.
@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds JSP/JSPF syntax highlighting by registering a dedicated jsp language id backed by a Monarch tokenizer and Monaco's HTML language service (the same pattern used for Razor and Handlebars). It maps .jsp/.jspf extensions in EXT_TO_LANGUAGE, routes the jsp label to the existing htmlWorker, and disables the two HTML providers that write to the buffer (rename, formatting) since they operate on an HTML parse that scriptlets would corrupt.

  • Tokenizer handles JSP directives, scriptlets (<% %>, <%= %>, <%! %>), JSP/HTML comments, deferred EL (#{…} and ${…}), JSTL/custom tags, and embedded JS/CSS blocks, with correct scriptlet-terminator lookaheads and ignoreCase left off to avoid Java variable/type collisions.
  • HTML language service attachment gives tag completion, hovers, document symbols, and folding for free; registration is guarded so repeated registerJspLanguage calls don't spin up a second worker.
  • Tests (16 cases) cover state transitions, delimiter exit contracts, embedded-language pop requirements, the operator-run/terminator-swallow fix, and a state-reference integrity check that Monarch would otherwise surface only at runtime.

Confidence Score: 5/5

Safe to merge — the change is a self-contained language registration with no writes to user data, no new dependencies, and no changes to existing language behavior.

All five changed files are either pure lookup-table additions or a new language module. The registration is guarded against duplicate calls. The tokenizer correctly handles the known edge cases (operator-run swallowing the scriptlet terminator, JSP comments in attribute contexts, case-sensitive Java types vs. identifiers, deferred EL). The 16 tests verify every state's exit delimiter and the embedded-language pop contract that Monarch enforces at runtime.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/lib/monaco-languages/register-jsp.ts New file: Monarch tokenizer + HTML language service registration for JSP/JSPF, with careful handling of scriptlet terminators, EL/deferred-EL, embedded JS/CSS, and case-sensitivity
src/renderer/src/lib/monaco-languages/register-jsp.test.ts New file: 16 targeted tests covering tokenizer state transitions, delimiter correctness, embedded-language pop contracts, state-reference integrity, and idempotent registration
src/renderer/src/lib/language-detect.ts Adds .jsp and .jspf to EXT_TO_LANGUAGE mapping both pointing to the new 'jsp' language id
src/renderer/src/lib/language-detect.test.ts Adds test covering .jsp, .jspf, and uppercase .JSP extension detection mapping to 'jsp'
src/renderer/src/lib/monaco-setup.ts Adds 'jsp' to the HTML worker switch case and calls registerJspLanguage at module startup

Reviews (3): Last reviewed commit: "fix(editor): stop a scriptlet comment fr..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a07a278e-db44-4e91-aa18-43ce5aca0b6c

📥 Commits

Reviewing files that changed from the base of the PR and between ffaa740 and a04b55a.

📒 Files selected for processing (2)
  • src/renderer/src/lib/monaco-languages/register-jsp.test.ts
  • src/renderer/src/lib/monaco-languages/register-jsp.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/lib/monaco-languages/register-jsp.ts
  • src/renderer/src/lib/monaco-languages/register-jsp.test.ts

📝 Walkthrough

Walkthrough

Added JSP language detection for .jsp and .jspf files, including uppercase extensions. Implemented Monaco JSP tokenization with JSP, EL, HTML, JavaScript, and CSS handling. Added JSP language configuration, HTML service settings, registration logic, startup initialization, HTML worker routing, and comprehensive tests.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding JSP syntax highlighting with the HTML language service.
Description check ✅ Passed All required template sections are present with specific details, including screenshots, testing, AI review, security audit, and notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: da4683f6-f182-44ad-9068-2c481e404b03

📥 Commits

Reviewing files that changed from the base of the PR and between 9cf31bd and 007337f.

📒 Files selected for processing (5)
  • src/renderer/src/lib/language-detect.test.ts
  • src/renderer/src/lib/language-detect.ts
  • src/renderer/src/lib/monaco-languages/register-jsp.test.ts
  • src/renderer/src/lib/monaco-languages/register-jsp.ts
  • src/renderer/src/lib/monaco-setup.ts

Comment on lines +175 to +188
export const jspHtmlModeConfiguration: Monaco.html.ModeConfiguration = {
completionItems: true,
hovers: true,
documentSymbols: true,
links: true,
documentHighlights: true,
rename: true,
colors: true,
foldingRanges: true,
selectionRanges: true,
diagnostics: false,
documentFormattingEdits: false,
documentRangeFormattingEdits: false
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does monaco-editor 0.55.1 export monaco.html.registerHTMLLanguageService, or is it under monaco.languages.html?

💡 Result:

In monaco-editor version 0.55.1, the registerHTMLLanguageService function is not directly exported under the monaco.languages.html namespace [1]. While registerHTMLLanguageService exists in the codebase as a function used to register additional language IDs for HTML services [2][3], it is technically located in the languages.features.html.register module [2][4][5]. Depending on how you import and consume the monaco-editor package, it is generally accessed via the specific entry point for HTML language features rather than being globally available on the monaco object under monaco.languages.html [1]. Historically, users have faced issues accessing this function in certain environments (such as AMD) [1], and it is common to encounter confusion regarding its exact namespace due to how the editor structures its contributions and API exports [3][1]. If you are working in an environment that requires this function, you typically need to import it from the corresponding internal path (e.g., vs/language/html/monaco.contribution or the relevant features/html/register module) [3][6].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package references =="
for f in package.json pnpm-lock.yaml package-lock.json yarn.lock bun.lockb pnpm-workspace.yaml; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    if [ "$f" = "package.json" ]; then
      node -e 'const p=require("./package.json"); console.log(JSON.stringify({dependencies:p.dependencies?.["monaco-editor"], devDependencies:p.devDependencies?.["monaco-editor"], scripts:p.scripts}, null, 2))'
    elif [ "$f" = "pnpm-lock.yaml" ]; then
      rg -n "monaco-editor|monaco" "$f" | head -80 || true
    else
      rg -n "monaco-editor" "$f" | head -80 || true
    fi
  fi
done

echo "== locate relevant source =="
git ls-files | rg '(^|/)register-jsp\.ts$|(^|/)monaco-setup\.ts$|(^|/)StyleGuide\.md$|(^|/)main\.css$'

echo "== inspect register-jsp around namespace/types =="
sed -n '150,220p' src/renderer/src/lib/monaco-languages/register-jsp.ts

echo "== inspect monaco html usages =="
rg -n "monaco\.(languages\.html|html)|registerHTMLLanguageService|ModeConfiguration" src/renderer/src lib renderer -g '*.{ts,tsx,js,jsx,json}' || true

Repository: stablyai/orca

Length of output: 16447


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import urllib.request
versions = ["0.54.3", "0.55.0", "0.55.1", "0.56.0"]
for version in versions:
    url = f"https://unpkg.com/monaco-editor@{version}/esm/vs/language/html/editorWorkerService.js"
    try:
        with urllib.request.urlopen(url, timeout=15) as r:
            text = r.read().decode("utf-8")[:2000]
        print(f"--- {version} editorWorkerService preview ---")
        print(text.split("\n", 20)[21] if len(text.split("\n", 21))>20 else text[:500])
    except Exception as e:
        print(f"--- {version} failed --- {type(e).__name__}: {e}")
PY

python3 - <<'PY'
import urllib.request

for version in ["0.55.1"]:
    dts = f"https://unpkg.com/monaco-editor@{version}/esm/vs/basic-languages/html/html.d.ts"
    pkl = f"https://unpkg.com/monaco-editor@{version}/esm/vs/language/html/html.workerImpl.d.ts"
    contrib = f"https://unpkg.com/monaco-editor@{version}/esm/vs/languages/features/html/register.d.ts"
    worker = f"https://unpkg.com/monaco-editor@{version}/esm/vs/languages/features/html/workerMain.d.ts"
    for url in [dts, pkl, contrib, worker]:
        print(f"--- {url} ---")
        try:
            with urllib.request.urlopen(url, timeout=15) as r:
                txt = r.read().decode("utf-8")
            for line in txt.splitlines():
                if "registerHTMLLanguageService" in line or "ModeConfiguration" in line or "LanguageServiceRegistration" in line:
                    print(line)
        except Exception as e:
            print(f"ERROR: {type(e).__name__}: {e}")
PY

Repository: stablyai/orca

Length of output: 1787


🌐 Web query:

monaco-editor 0.55.1 registerHTMLLanguageService languages.features.html.register ModeConfiguration

💡 Result:

In Monaco Editor 0.55.1, the registerHTMLLanguageService function is used to register a new HTML language service for a specified language ID [1][2]. While the default languages 'html', 'handlebars', and 'razor' are registered automatically, this method allows developers to add custom language IDs to the HTML language service [1][2]. The registerHTMLLanguageService function has the following signature [1][2]: registerHTMLLanguageService(languageId: string, options: Options = optionsDefault, modeConfiguration: ModeConfiguration = getConfigurationDefault(languageId)): LanguageServiceRegistration The ModeConfiguration interface defines which built-in providers are enabled for the registered language [3][4]. It consists of optional boolean properties, including [3][4]: - colors - completionItems - diagnostics - documentFormattingEdits - documentHighlights - documentRangeFormattingEdits - documentSymbols - foldingRanges - hovers - links - rename - selectionRanges When calling registerHTMLLanguageService, the language server must be registered before an editor model is opened for the specified language [1][2]. The function returns a LanguageServiceRegistration object that contains the default configuration and an IDisposable interface for cleanup [1][2].

Citations:


Use the module path for the HTML language service instead of monaco.html.

registerHTMLLanguageService and its ModeConfiguration are not attached to monaco.html in Monte Editor 0.55.1; use the vs/languages/features/html/register.* API/module path instead. If the same ModeConfiguration object is used elsewhere for a public Monaco API, ensure the consumer supports that type shape too.

Two states could run past their closing delimiter and tokenize the rest of
the file as Java:

- `tagRest` and both attribute-value states had no `<%--` rule, so a JSP
  comment inside a tag entered the scriptlet state, where `--%>` was absorbed
  by the operator character class instead of closing it.
- That class contained both `%` and `>`, so an operator run written against
  the terminator (`i++%>`) swallowed it. `%` now carries a negative lookahead.

Also turns `ignoreCase` off: scriptlets are Java, which is case-sensitive, and
with it on `List list` coloured the variable as a type. Monarch has no per-rule
casing, so the four HTML tags that need it spell the characters out.

Drops `rename` from the HTML mode configuration. It is the only enabled
provider that edits the buffer, and it does so from a parse of the file as
HTML, which scriptlets break. `diagnostics` and `colors` are removed because
the HTML mode never reads them; the real guard is formatting staying off.
…imiter

`<% doStuff(); // done %>` is valid JSP — the container looks for `%>`
first, so the line comment ends there. The rule consumed to end of line
instead, taking the terminator with it and leaving the tokenizer inside
the scriptlet for the rest of the file. The block comment had the same
gap. Both now stop before a literal `%>`.
@taehwanis

Copy link
Copy Markdown
Contributor Author

Thanks both bots — all four comments were made against the first commit (007337fdc). Status after ffaa740a2 and a04b55a65:

Fixed

  • ignoreCase colouring variables as types (greptile) — correct, and worse than cosmetic in practice: List list, Map map and String string are the most common shapes in a scriptlet, so the variable took the same token as the class. ignoreCase is now off, and the four HTML tags that genuinely need it spell the characters out. A test asserts list = null tokenizes as identifier while List list still starts with type.
  • Deferred EL #{...} not highlighted (greptile) — added to root, tagRest and both attribute-value states, reusing the existing elExpression state.
  • Line/block comment swallowing %> (coderabbit) — good catch, and the sharpest of the four. <% doStuff(); // done %> is valid JSP because the container looks for %> first, so the comment has to stop there rather than run to end of line; otherwise the tokenizer stays in the scriptlet for the rest of the file. Both comment rules now carry a (?!%>) guard, with a regression test on the match lengths.

Not applicable

  • monaco.html.registerHTMLLanguageService namespace (coderabbit, flagged Critical) — the sources cited describe monaco.languages.html, which is indeed not where it lives. In the bundled types for the version this repo pins, html is a top-level export alongside languages (monaco.d.ts: monaco_contribution$2 as html). I ran into exactly this while writing it: Monaco.languages.html.ModeConfiguration fails with TS2694, and Monaco.html.ModeConfiguration type-checks. It also works at runtime — tag completion appears inside JSP markup in a local build, which is what the screenshots in the description show.

Two of the four were real defects that I had missed, so the review was worth it. The remaining <script>-block limitation is documented under Notes rather than fixed, since Monarch cannot re-enter host rules mid-embed.

@taehwanis

Copy link
Copy Markdown
Contributor Author

Closing in favor of #10858, which now carries this work.

@hwantage folded the HTML language service wiring and the tokenizer fixes from this PR into #10858 with co-author credit, so the two had converged on the same five files. Keeping both open only splits reviewer attention, and #10858 is the more complete of the two — it also carries the newer scriptlet-terminator and Java type-list fixes.

I've opened a much smaller .jsp/.jspf → html fallback as a separate first step in #12402. It is markup-only and explicitly defers to #10858; context there.

@taehwanis taehwanis closed this Aug 4, 2026
senadaruc pushed a commit to senadaruc/orca-plugins that referenced this pull request Oct 31, 2026
Highlights .jsp, .jspf and .tag files with the vscode-jsp grammar (MIT) and
bundles the HTML, Java, CSS and JavaScript grammars it embeds (VS Code, MIT;
TextMate HTML bundle notice included). Orca reads no grammar injections, so
JSP's injected rules are inlined. Needs Orca 1.4.246, the first release where
an enabled plugin syntax beats Orca's HTML stopgap for .jsp/.jspf.

Replaces stablyai/orca#10858 and stablyai/orca#11309 for stablyai/orca#9795.

Co-authored-by: hwantage <[email protected]>
Co-authored-by: taehwanis <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants