diff --git a/client/src/CodeMirror-integration.mts b/client/src/CodeMirror-integration.mts index d44628ba..b032cde3 100644 --- a/client/src/CodeMirror-integration.mts +++ b/client/src/CodeMirror-integration.mts @@ -1254,6 +1254,10 @@ export const DocBlockPlugin = ViewPlugin.fromClass( // TinyMCE's own init happens to put it (its start). // Anchoring on a text node instead keeps the // walk -- and thus the edge placement -- intact. + // The first child of a block is often a hidden + // line marker (``); step over it, so that the + // caret isn't put in hidden text. + // let edgeNode: Node = contents; while ( atEnd ? edgeNode.lastChild : edgeNode.firstChild @@ -1261,6 +1265,12 @@ export const DocBlockPlugin = ViewPlugin.fromClass( edgeNode = atEnd ? edgeNode.lastChild! : edgeNode.firstChild!; + if ( + edgeNode.nodeName === "L-N" && + edgeNode.nextSibling + ) { + edgeNode = edgeNode.nextSibling; + } } if (edgeNode.nodeType === Node.TEXT_NODE) { const offset = atEnd diff --git a/client/src/css/CodeChatEditor.css b/client/src/css/CodeChatEditor.css index 839e27f6..ebdb3df8 100644 --- a/client/src/css/CodeChatEditor.css +++ b/client/src/css/CodeChatEditor.css @@ -43,8 +43,9 @@ [gathered fragment styling](gathered-fragments) needs: it aligns generated content against the source it came from, and a theme which happened to style the elements it uses would break that alignment rather than restyle it. - Nothing but that section belongs out here; anything a theme should be free to - restyle goes in [CodeChatEditorBase.css](CodeChatEditorBase.css) instead. + Nothing but that section and the rule which hides line markers belongs out + here; anything a theme should be free to restyle goes in + [CodeChatEditorBase.css](CodeChatEditorBase.css) instead. Eventually, the theme will be a user-configurable setting. */ @import url("themes/light.css") layer(app); @@ -174,3 +175,10 @@ text-align: right; opacity: 0.5; } + +/* A line marker such as `24`, which the Server puts before the + content of each Markdown line to record its line number in the source file + (see `line-number-spec.md`). It is metadata, never shown. */ +l-n { + display: none; +} diff --git a/client/src/tinymce-config.mts b/client/src/tinymce-config.mts index a68cbd84..3daa6756 100644 --- a/client/src/tinymce-config.mts +++ b/client/src/tinymce-config.mts @@ -146,11 +146,12 @@ export const init = async ( quickbars_selection_toolbar: "bold italic underline codeformat | quicklink h2 h3", - // Needed to allow custom elements. + // Needed to allow custom elements. Without `l-n`, TinyMCE would + // drop each line marker but keep its number as visible text. extended_valid_elements: - "graphviz-graph[scale],wc-mermaid,xref[contenteditable|ref],fragment[contenteditable|following|id]", + "graphviz-graph[scale],wc-mermaid,xref[contenteditable|ref],fragment[contenteditable|following|id],l-n", // Per the [docs](https://www.tiny.cloud/docs/tinymce/latest/content-filtering/#custom_elements), `~` marks tags as an inline element, not a block element. - custom_elements: "graphviz-graph,wc-mermaid,~xref,~fragment", + custom_elements: "graphviz-graph,wc-mermaid,~xref,~fragment,~l-n", // Setting the // [context menu](https://www.tiny.cloud/docs/tinymce/latest/contextmenu/#contextmenu) @@ -181,6 +182,7 @@ export const init = async ( }); takeLinkGestures(editor); addLinkMenu(editor); + handleLineMarkers(editor); }; // Use these combined options to @@ -189,6 +191,79 @@ export const init = async ( return await tinymce.init(combinedOptions); }; +// Line markers +// ------------ +// +// The Server puts a hidden marker before the content of each Markdown line; +// see [line-number-spec.md](../../line-number-spec.md). +// +// TinyMCE counts the number inside a marker as content, so a block which holds +// only markers doesn't get the `
` TinyMCE puts in an empty block. That +// block has no height, so the caret can't enter it, and saving drops it, since +// the Server removes the markers. Such a block appears when Enter splits a +// paragraph just after its marker, and when TinyMCE parses contents, as in +// `setContent`: its parser removes the `
` which ends a block it doesn't +// consider empty. Add the `
` in both cases. +// +// A copy or cut puts the selected HTML on the clipboard. Leave the markers out +// of it: their numbers don't fit where the text is pasted, and an editor +// without the Client's CSS shows them. +// +const handleLineMarkers = ( + // The editor whose markers are handled. + editor: Editor, +) => { + editor.on("NewBlock", ({ newBlock }) => { + // When Enter splits a block, the first half stays in place and the + // second half becomes `newBlock`. + const block = newBlock.previousElementSibling; + if (block?.querySelector("l-n") && !block.querySelector("br")) { + const withoutMarkers = block.cloneNode(true) as Element; + withoutMarkers + .querySelectorAll("l-n") + .forEach((marker) => marker.remove()); + if (editor.dom.isEmpty(withoutMarkers)) { + editor.dom.add(block, "br", { "data-mce-bogus": "1" }); + } + } + }); + // The parser exists once the editor starts to initialize. + editor.on("PreInit", () => { + const blockElements = editor.schema.getBlockElements(); + editor.parser.addNodeFilter("l-n", (markers) => { + for (const marker of markers) { + const block = marker.parent; + if (!block || !(block.name in blockElements)) { + continue; + } + // TinyMCE's own filter may run before or after this one, so + // the block may still hold its `
`. + const children = block.children(); + const brs = children.filter((child) => child.name === "br"); + if ( + brs.length <= 1 && + children.every( + (child) => child.name === "l-n" || child.name === "br", + ) + ) { + brs.forEach((br) => br.remove()); + block.append( + tinymce.html.Node.create("br", { + "data-mce-bogus": "1", + }), + ); + } + } + }); + }); + // TinyMCE builds the clipboard's HTML from the selection's contents. + editor.on("GetContent", (event) => { + if (event.selection) { + event.content = event.content.replace(/\d+<\/l-n>/g, ""); + } + }); +}; + // Following links // --------------- // diff --git a/line-number-spec.md b/line-number-spec.md new file mode 100644 index 00000000..5bb70341 --- /dev/null +++ b/line-number-spec.md @@ -0,0 +1,151 @@ +Markdown source line numbers +============================ + +Goal +---- + +The Server includes source line markers in the HTML it sends to the Client +for Markdown documents and for the doc blocks of source files. A marker such +as `24` says that the content after it starts on line 24 of the +original file. For example, a paragraph on lines 24 and 25 is sent as: + +```html +

24First line +25Second line

+``` + +The markers are hidden metadata for later features. `TargetFact.line` and +`FragmentFact.line` stay 0 (see the comment in `processing.rs`, "Line numbers +aren't available ..."); filling them is out of scope, as is any visible +line-number interface. + +Placement +--------- + +Lines count from 1 in the original file, including blank lines and code. +Every caller passes LF-normalized text. + +Insert a marker before the first *inline event* which starts on a line not +yet marked. The inline events are `Text`, `Code`, `InlineMath`, +`DisplayMath`, `InlineHtml`, `FootnoteReference`, `TaskListMarker`, and the +`Start` of `Emphasis`, `Strong`, `Strikethrough`, `Superscript`, `Subscript`, +`Link` and `Image`. These always sit inside a paragraph, heading, list item, +table cell or definition, so a marker never lands between `` and ``, +where html5ever would move it. + +Insert nothing inside an image (its text becomes the `alt` attribute), a code +block, a raw HTML block or a metadata block. Insert nothing either after a +tag, inline or in an HTML block, which opens one of these elements, up to the +tag which closes it or the end of the doc block: + +* text html5ever doesn't parse as HTML: `iframe`, `noembed`, `noframes`, + `noscript`, `script`, `style`, `textarea`, `title`, `xmp`; +* text a diagram reads as its source: `wc-mermaid`, `graphviz-graph`; +* `xref`, whose content `hydrate_source_xref` copies into `data-content`, + which a save writes back unchanged. + +A marker there would become visible text, or be saved. + +A line with no inline event of its own gets no marker: a blank line, a code +fence, a setext underline, a thematic break, a table delimiter row, a link +reference definition, or the second line of a multi-line inline code span, +inline HTML tag or display math. + +This is the prototype `add_line_comments` (book repo, +`project_notes/md-ast-line-numbers`), with `` in place of the HTML +comment and the marker moved from the first event of a line to its first +inline event. + +Server changes +-------------- + +All in `server/src/processing.rs` unless noted. + +1. `markdown_to_html` gains a parameter: the byte ranges of its input which + come from the file, each with the file line of its first line. It inserts + `InlineHtml("N")` events as described above. Text outside the + ranges (the doc block separators) gets no marker; an empty list gives the + old output. +2. Markdown documents pass one range, the whole input, starting at line 1. +3. Source files: the loop which builds `doc_contents` records each doc + block's range and first line, which is 1 plus the sum of + `code_doc_block_lines` over the blocks before it (the count + `render_fragment_content` uses for its gutter). +4. `AMMONIA_OPTIONS`: add `l-n` to `add_tags`, so `minify` keeps markers. +5. `CLEAN_LINK_CONTENT_HTML` and `CLEAN_FRAGMENT_HTML`: add `l-n` to + `add_clean_content_tags`. Link text copied from a heading, and gathered + fragments, then carry no markers from another place. +6. `dehydrating_walk_node`: remove every `` with its number. `l-n` is + reserved for generated markers; one written by hand is removed too. +7. `compare_html` (`translation.rs`): remove markers from both inputs before + comparing. Otherwise every Client edit which shifts lines makes the Server + send a re-translation. +8. `send_re_translation` (`translation.rs`): when a re-translation is sent + anyway (something besides markers differs), keep the Client's contents for + each doc block which `compare_html` finds equal. A new marker in the doc + block being edited would otherwise mark TinyMCE dirty and shift the child + index the Client uses to restore the caret. Markers in the Client may be + stale after a Client edit until the next translation which isn't a + re-translation. + +Client changes +-------------- + +* `tinymce-config.mts`: add `l-n` to `extended_valid_elements` and `~l-n` + (inline) to `custom_elements`; TinyMCE drops unknown tags but keeps their + text. +* `css/CodeChatEditor.css`: `l-n { display: none; }`, outside the cascade + layer so no theme can show it. The TOC page loads this file too. +* `tinymce-config.mts`, `handleLineMarkers`: a block holding only markers + gets the `
` TinyMCE gives an empty block. TinyMCE + counts the marker's number as content, so without this the block has no + height and is lost on save. Such a block appears when Enter splits a + paragraph just after its marker (`NewBlock` event) and when TinyMCE parses + contents (a parser node filter on `l-n`), since the parser removes the + `
` which ends a block it doesn't consider empty. +* `tinymce-config.mts`, `handleLineMarkers`: remove markers from selection + contents (`GetContent` with `selection`), which TinyMCE puts on the + clipboard on copy or cut. +* `CodeMirror-integration.mts`: the walk which puts the caret at the start of + a doc block entered from above skips a marker, so the caret doesn't land in + hidden text. + +Known deviation +--------------- + +For a block comment whose text starts on the line after the opening +delimiter (`/*⏎`), the generic lexer (every language but C, C++ and Python) +drops that newline, so the markers in it are one line early, and each such +comment moves every later marker in the file one more line early. The +fragment gutter numbers have the same offset; fixing the lexer is out of +scope. + +Tests +----- + +In `server/src/processing/tests.rs` (exact expected HTML) and +`server/src/translation.rs`: + +| Input | Expected | +| --- | --- | +| Markdown: two prose lines, blank line, `# Head` | Markers 1 and 2 in the `

`, 4 in the `

` | +| Prose on lines 1 and 7 around a fenced code block on 3-5; a metadata block on lines 1-3, then prose | Markers 1 and 7 only; same with a raw HTML block and with `$$` display math (marker on its first line); marker 5 only after the metadata block | +| Hard break (two spaces, `\`, `
`), list continuation, block quote | One marker per line, inside the `

`, `

  • ` or quote | +| Table with an empty first cell; task list | One marker per row, in its first cell with content; marker before the checkbox | +| Image whose alt text spans two lines, or holds `