Files
lucisv/editors/vscode/commentKeywords.js
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Release 0.66.2: every source file names its author
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00

224 lines
8.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Author: Guoliang Chen, a Senior Digital Design Engineer
// Highlight TODO, FIXME, FIX_ME, TBD and the user's own words inside comments
// (docs/features/comment-highlighting). Editor decorations, painted only on
// the lines an editor shows; where the comments are comes from
// `commentScan.js`, which mirrors the TextMate grammar.
//
// `vscode` is passed in rather than required so the wiring is testable with a
// fake (`commentKeywords_test.js`).
const { chooseWords, wordMatcher, LineStates, keywordRanges } = require('./commentScan');
/** The settings section this reads: `lucisv.commentKeywords.*`. */
const SECTION = 'lucisv.commentKeywords';
/** The theme colour the words are painted in. One dot: see the README. */
const COLOR_ID = 'lucisv.commentKeyword';
/** How long typing settles before the edited editor is repainted. */
const EDIT_DEBOUNCE_MS = 100;
/** Lines painted beyond each visible range, so a short scroll shows no gap. */
const MARGIN_LINES = 50;
/** VS Code's own default for `editor.maxTokenizationLineLength`. */
const DEFAULT_MAX_LINE_LENGTH = 20000;
/**
* VS Code never tokenizes a model above either size when
* `editor.largeFileOptimizations` is on (`textModel.ts`,
* `LARGE_FILE_SIZE_THRESHOLD` / `LARGE_FILE_LINE_COUNT_THRESHOLD`; the length
* is in UTF-16 units). Such a file shows no comment colour, so none of it is
* painted either.
*/
const UNTOKENIZED_LENGTH = 20 * 1024 * 1024;
const UNTOKENIZED_LINES = 300 * 1000;
class CommentKeywords {
/**
* @param vscode the `vscode` module (or a fake of it)
* @param isTarget which documents to paint (the Verilog ones)
* @param log where a line about skipped custom words goes
*/
constructor(vscode, isTarget, log = () => {}) {
this.vscode = vscode;
this.isTarget = isTarget;
this.log = log;
/**
* Per document object: `{ states, maxLineLength, untokenized }` — its
* block-comment line states, the line-length cutoff they were computed
* with, and whether VS Code tokenizes it at all.
*/
this.documents = new Map();
/** Editors this has painted, so only those are ever cleared. */
this.painted = new WeakSet();
this.timer = undefined;
this.decoration = vscode.window.createTextEditorDecorationType({
color: new vscode.ThemeColor(COLOR_ID),
fontWeight: 'bold',
});
this.readSettings();
}
/** Subscribe to everything that can change what is painted. */
activate(subscriptions) {
const { window, workspace } = this.vscode;
subscriptions.push(
this.decoration,
window.onDidChangeVisibleTextEditors(() => this.paintVisible()),
window.onDidChangeTextEditorVisibleRanges((event) => this.paintEditor(event.textEditor)),
workspace.onDidChangeTextDocument((event) => this.onEdit(event)),
// A language-mode change is reported as close then open of the same
// document (`languages.setTextDocumentLanguage`'s documentation), and
// the open fires before the editor shows the new mode — hence the tick.
workspace.onDidCloseTextDocument((document) => this.documents.delete(document)),
workspace.onDidOpenTextDocument(() => setTimeout(() => this.paintVisible(), 0)),
workspace.onDidChangeConfiguration((event) => this.onConfiguration(event)),
{ dispose: () => clearTimeout(this.timer) },
);
this.paintVisible();
}
/** Read the words and the case rule afresh. */
readSettings() {
const settings = this.vscode.workspace.getConfiguration(SECTION);
const caseSensitive = settings.get('caseSensitive', true) !== false;
const { words, skipped } = chooseWords({
builtIn: settings.get('builtIn', true),
custom: settings.get('custom', []),
caseSensitive,
});
if (skipped.length) {
this.log(`lucisv: ${SECTION}.custom: ignored ${skipped.length} entr${skipped.length === 1 ? 'y' : 'ies'} `
+ '(each must be 1–40 characters with no spaces, at most 50 words)');
}
this.matcher = wordMatcher(words, caseSensitive);
}
/**
* `editor.maxTokenizationLineLength` as VS Code applies it to `document`:
* read with the document as scope, so a `[systemverilog]` override counts.
*/
maxLineLength(document) {
const max = this.vscode.workspace.getConfiguration('editor', document).get('maxTokenizationLineLength');
return Number.isInteger(max) && max > 0 ? max : DEFAULT_MAX_LINE_LENGTH;
}
/**
* Whether VS Code tokenizes `document` at all. Decided once per document,
* as VS Code decides it once per model, at creation.
*/
isUntokenized(document) {
const editor = this.vscode.workspace.getConfiguration('editor', document);
if (editor.get('largeFileOptimizations', true) === false) return false;
if (document.lineCount > UNTOKENIZED_LINES) return true;
const last = document.lineAt(document.lineCount - 1);
return document.offsetAt(last.range.end) > UNTOKENIZED_LENGTH;
}
/** The cached record for `document`, fresh if its cutoff changed. */
recordOf(document) {
const maxLineLength = this.maxLineLength(document);
let record = this.documents.get(document);
if (!record) {
record = { states: new LineStates(), maxLineLength, untokenized: this.isUntokenized(document) };
this.documents.set(document, record);
} else if (record.maxLineLength !== maxLineLength) {
// The cutoff decides which lines carry a block comment over, so every
// cached state may be wrong.
record.states = new LineStates();
record.maxLineLength = maxLineLength;
}
return record;
}
/** A setting this depends on changed: honour it now, both ways. */
onConfiguration(event) {
const ours = event.affectsConfiguration(SECTION);
const lineLength = event.affectsConfiguration('editor.maxTokenizationLineLength');
if (!ours && !lineLength) return;
// A changed cutoff is noticed per document by `recordOf`.
if (ours) this.readSettings();
this.paintVisible();
}
/** Forget the states below the first edited line, then repaint soon. */
onEdit(event) {
if (!this.isTarget(event.document)) return;
const record = this.documents.get(event.document);
if (record && event.contentChanges.length) {
const first = Math.min(...event.contentChanges.map((change) => change.range.start.line));
record.states.invalidateFrom(first);
}
clearTimeout(this.timer);
this.timer = setTimeout(() => this.paintVisible(), EDIT_DEBOUNCE_MS);
}
paintVisible() {
for (const editor of this.vscode.window.visibleTextEditors) this.paintEditor(editor);
}
/**
* Paint the keywords on (and just around) the lines `editor` shows — or
* clear them, when there is nothing to paint or the document stopped being
* Verilog.
*/
paintEditor(editor) {
const document = editor.document;
if (!this.isTarget(document)) {
if (this.painted.has(editor)) this.setRanges(editor, []);
return;
}
if (!this.matcher) {
this.setRanges(editor, []);
return;
}
const { states, maxLineLength, untokenized } = this.recordOf(document);
if (untokenized) {
this.setRanges(editor, []);
return;
}
const lineText = (line) => document.lineAt(line).text;
const last = document.lineCount - 1;
const ranges = [];
for (const { from, to } of paddedLines(editor.visibleRanges, last)) {
const found = keywordRanges({
states, lineText, from, to, matcher: this.matcher, maxLineLength,
});
for (const { line, start, end } of found) ranges.push(new this.vscode.Range(line, start, line, end));
}
this.setRanges(editor, ranges);
}
setRanges(editor, ranges) {
editor.setDecorations(this.decoration, ranges);
if (ranges.length) this.painted.add(editor);
else this.painted.delete(editor);
}
}
/**
* The visible ranges as line spans, widened by `MARGIN_LINES`, clamped to the
* document and merged where they overlap, so no line is scanned twice.
*/
function paddedLines(visibleRanges, lastLine) {
const spans = visibleRanges
.map((range) => ({
from: Math.max(0, range.start.line - MARGIN_LINES),
to: Math.min(lastLine, range.end.line + MARGIN_LINES),
}))
.sort((a, b) => a.from - b.from);
const merged = [];
for (const span of spans) {
const previous = merged[merged.length - 1];
if (previous && span.from <= previous.to + 1) previous.to = Math.max(previous.to, span.to);
else merged.push({ ...span });
}
return merged;
}
module.exports = { CommentKeywords, paddedLines, COLOR_ID, SECTION };
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com