Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

### Added

- Recognize standalone empty HTML section anchors as invisible navigation targets, preserve their source through visual edits, and retain inert targets in HTML export.
- Optional per-block soft wrapping, off by default, with a persistent **Wrapped** notice. Wrapping preserves code content, editing state, source/save/copy behavior, and independent export layout. See [code controls and soft wrapping](docs/editor-guide.md#code-controls-and-soft-wrapping).

## 0.4.1
Expand Down
8 changes: 8 additions & 0 deletions docs/editor-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ Visual formatting and insertion controls are disabled in Source and Split. Use V

The sidebar has **Outline** and **Document** tabs. Outline buttons locate headings in either view; in Split, they also locate the corresponding source heading and preview section. Document provides navigation through the first two heading levels and identifies the current section. The shared footer shows the document title, counts, and current section's position among the headings, with a thin section-progress indicator. Small windows conceal the rail without changing the stored desktop preference; use **Open Outline** to display it over the canvas and **Close Outline** to return to writing.

## Custom section anchors

A standalone empty HTML anchor such as `<a id="legacy-section"></a>` keeps an existing section link working after you rename its heading. The visual editor treats the anchor as invisible navigation metadata. `[Jump](#legacy-section)` locates the following content without editing the document. Consecutive anchors share that location; an anchor at the end locates the document end. Duplicate targets resolve to the first matching anchor or heading in document order.

Use a quoted, nonempty `id` or legacy `name` attribute, or both. Target values cannot contain whitespace or angle brackets. Edit anchors in **Source**; visual edits to surrounding content, saving, and Undo/Redo retain their original source. HTML export retains inert anchor targets. When a visual deletion or replacement spans an anchor, the anchor moves before the resulting content instead of being removed. Remove anchors in Source mode. Viewing anchors creates no document edit.

Recognition applies only to complete standalone lines at the document's top level, with fewer than four leading spaces. Inline anchors, anchors in lists or quotes, payload text, unquoted attributes, and extra attributes such as `href`, `style`, or event handlers remain literal source. Code examples and escaped tags also remain literal. Arbitrary HTML stays disabled.

## Find and Replace

Use `Cmd+F`/`Ctrl+F` to find, or `Cmd+H`/`Ctrl+H` to find and replace. Search operates on Markdown source, including syntax and metadata. Each result shows its source line and surrounding text. Click a result to locate it; results without a visible text counterpart offer **Source** to show the exact match. Previous/Next and Enter/Shift+Enter navigate results.
Expand Down
6 changes: 6 additions & 0 deletions docs/testing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ From the repository root, run `npm run compile`, `npm run test:markdown-blocks`,

For actual file persistence, build and install a new development VSIX in the [isolated native harness](../../test/native/export-smoke.md), then run its `paragraph-semantics` and `table-source-format` suites against that same package. They measure the installed view, type both kinds of break, save through VS Code, reopen files, check exact source bytes, exercise both table layouts and setting precedence, and export HTML. Both suites also run with `--suite all`. A browser pass alone does not establish installed-host saving or another operating system's behavior.

## Custom section anchor regressions

After compilation, run `npm run test:markdown-blocks`, `npm run test:build`, and `CI=1 npx playwright test test/specs/html-anchors.spec.ts --retries=0`. These checks cover restricted standalone anchors, literal unsupported syntax, source preservation, fragment navigation, all-theme zero-height layout, deletion/replacement, Undo/Redo, Source switching, and prepared HTML targets. Run the complete browser suite after shared parser or serializer changes.

For actual file persistence and host navigation, package and install the development VSIX in the [isolated native harness](../../test/native/export-smoke.md), then run `node test/native/export-smoke.cjs run --suite html-anchors` with the initialization options for that owned profile. Record the exact package identity; browser checks alone do not establish installed-extension saving.

## Save, list and inline-code regressions

The installed harness includes `save-correctness` and `list-code-preservation` in `--suite all`. Run them against a newly packaged and installed VSIX using the [focused procedure](../../test/native/export-smoke.md#save-list-and-inline-code-preservation). The save check controls delivery of actual editor messages during native Save and compares the captured snapshot, host buffer, disk and reopened Source view. The preservation check covers ordered starts and checklists, literal and padded inline code, Undo/Redo, Source mode and save/reopen. The guide describes their controlled inputs and coverage boundaries; retain results for the exact package tested.
Expand Down
39 changes: 39 additions & 0 deletions src/shared/markdown-blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,45 @@ parser.block.ruler.before('fence', 'binary_aux', (state, start, end, silent) =>
return true;
}, { alt: ['paragraph', 'reference', 'blockquote', 'list'] });

// Empty standalone anchors are navigation metadata, not arbitrary HTML.
// Require quoted id/name attributes; reject payloads and all other attributes.
function parseAnchor(line) {
const match = /^<a\b([^<>]*)>[ \t]*<\/a[ \t]*>$/i.exec(line.trim());
if (!match) return null;
let rest = match[1];
const attrs = {};
while (rest.trim()) {
const attribute = /^[ \t]+(id|name)[ \t]*=[ \t]*(["'])(.*?)\2/i.exec(rest);
if (!attribute) return null;
const name = attribute[1].toLowerCase();
if (Object.hasOwn(attrs, name) || /[\\\x00-\x1f]/.test(attribute[3])) return null;
const value = parser.utils.unescapeAll(attribute[3]);
if (!value || /[\s<>\x00-\x1f]/.test(value)) return null;
attrs[name] = value;
rest = rest.slice(attribute[0].length);
}
return Object.keys(attrs).length ? attrs : null;
}

parser.block.ruler.before('paragraph', 'binary_anchor', (state, start, end, silent) => {
// Nested containers and indented code retain their existing interpretation.
if (state.blkIndent || state.level !== 0 || state.sCount[start] >= 4) return false;
const anchors = [];
let line = start;
for (; line < end && state.sCount[line] < 4; line++) {
const attrs = parseAnchor(state.getLines(line, line + 1, 0, false));
if (!attrs) break;
anchors.push(attrs);
}
if (!anchors.length) return false;
if (silent) return true;
const token = state.push('binary_anchor', 'div', 0);
token.map = [start, line];
token.meta = { anchors };
state.line = line;
return true;
}, { alt: ['paragraph'] });

function tokenTree(tokens) {
const root = { children: [] };
const stack = [root];
Expand Down
138 changes: 107 additions & 31 deletions src/webview/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2732,6 +2732,14 @@

function renderMarkdownBlock(block, exportCode = false, parent = null, index = 0) {
const children = () => block.children.map((child, i) => renderMarkdownBlock(child, exportCode, block, i)).join('');
if (block.type === 'binary_anchor') {
const anchors = block.meta.anchors;
if (exportCode) return anchors.map(attrs => '<a' + Object.entries(attrs).map(([name, value]) =>
' ' + name + '="' + escapeHtml(value).replace(/"/g, '&quot;') + '"').join('') + '></a>').join('');
return '<div class="markdown-anchor" contenteditable="false" aria-hidden="true"' +
' data-anchor-targets="' + encodeURIComponent(JSON.stringify(anchors.flatMap(attrs => Object.values(attrs)))) +
'" data-anchor-source="' + encodeURIComponent(block.source) + '"></div>';
}
if (block.type === 'front_matter') return renderFrontMatter(block.content);
if (block.type === 'binary_aux') return renderTocBlock(block.content);
if (block.type === 'binary_math') return mathBlockHtml(block.meta);
Expand Down Expand Up @@ -3360,6 +3368,73 @@
event.preventDefault(); event.stopImmediatePropagation();
editInlineMath(span);
}, true);
// Invisible anchors cannot be selected intentionally in Visual mode. Keep
// them outside native deletion/replacement ranges; Source owns their removal.
function retainAnchorsForEdit(inputType) {
const selection = window.getSelection();
if (!selection?.rangeCount || isSourceMode || !editor.querySelector(':scope > .markdown-anchor')) return false;
const range = selection.getRangeAt(0);
const selected = !range.collapsed;
if (!editor.contains(range.commonAncestorContainer)) return false;
let start = range.startContainer;
while (start !== editor && start.parentNode !== editor) start = start.parentNode;
let block = start === editor ? editor.childNodes[range.startOffset] : start;
let anchors = [];
if (!range.collapsed) {
anchors = Array.from(editor.querySelectorAll(':scope > .markdown-anchor')).filter(node => range.intersectsNode(node));
while (block?.classList?.contains('markdown-anchor')) block = block.nextSibling;
} else if (/^deleteContent(?:Backward|Forward)$/.test(inputType) && block?.nodeType === 1) {
const backward = inputType === 'deleteContentBackward';
if (block.classList.contains('markdown-anchor')) {
block = backward ? block.nextElementSibling : block.previousElementSibling;
while (block?.classList.contains('markdown-anchor')) block = backward ? block.nextElementSibling : block.previousElementSibling;
if (!block) return 'boundary';
}
const edge = range.cloneRange(); edge.selectNodeContents(block);
if (backward) edge.setEnd(range.startContainer, range.startOffset);
else edge.setStart(range.startContainer, range.startOffset);
if (edge.toString() || edge.cloneContents().querySelector('img,.math-inline')) return false;
let sibling = backward ? block.previousElementSibling : block.nextElementSibling;
while (sibling?.classList.contains('markdown-anchor')) {
if (backward) anchors.unshift(sibling); else anchors.push(sibling);
sibling = backward ? sibling.previousElementSibling : sibling.nextElementSibling;
}
if (anchors.length && !sibling) return 'boundary';
if (backward) block = sibling;
}
if (!anchors.length) return false;
undoManager.saveSnapshot();
for (const anchor of anchors) editor.insertBefore(anchor, block || null);
if (!block && selected) {
// Chromium clamps a caret after only noneditable nodes to the start.
// Give replacement text an explicit editable position after metadata.
const paragraph = document.createElement('p'); paragraph.innerHTML = '<br>';
editor.appendChild(paragraph);
range.selectNodeContents(paragraph); range.collapse(true);
} else if (start === editor && selected) range.setStartAfter(anchors.at(-1));
selection.removeAllRanges(); selection.addRange(range);
return true;
}

editor.addEventListener('keydown', event => {
if (event.target.closest?.('.front-matter,.toc-block') || (event.key !== 'Backspace' && event.key !== 'Delete')) return;
const inputType = event.key === 'Backspace' ? 'deleteContentBackward' : 'deleteContentForward';
const retained = retainAnchorsForEdit(inputType);
if (retained) {
if (retained === 'boundary') event.preventDefault();
// Let Chromium merge the visible blocks after metadata moves out of
// its range, rather than applying custom handlers to hidden blocks.
event.stopImmediatePropagation();
}
}, true);
editor.addEventListener('beforeinput', event => {
if (event.target.closest?.('.front-matter,.toc-block')) return;
if (/^(?:insert|delete)/.test(event.inputType) && retainAnchorsForEdit(event.inputType) === 'boundary') event.preventDefault();
}, true);
for (const type of ['paste', 'cut']) editor.addEventListener(type, event => {
if (!event.target.closest?.('.front-matter,.toc-block')) retainAnchorsForEdit(type);
}, true);

editor.addEventListener('keydown', event => {
if (event.target.classList.contains('math-inline') && (event.key === 'Enter' || event.key === ' ')) {
event.preventDefault(); event.stopImmediatePropagation();
Expand Down Expand Up @@ -6314,6 +6389,7 @@

const tag = node.tagName.toLowerCase();

if (node.classList.contains('markdown-anchor')) return decodeURIComponent(node.dataset.anchorSource) + '\n';
if (node.classList.contains('toc-block')) return decodeURIComponent(node.dataset.tocSource) + '\n';
if (node.classList.contains('front-matter')) {
const raw = node.querySelector('textarea').value;
Expand Down Expand Up @@ -14835,38 +14911,38 @@
// Show toast notification for external change
showEditorToast(message.message);
} else if (message.type === 'scrollToAnchor') {
// Scroll to anchor (heading) in the document
const anchor = message.anchor;
if (anchor) {
// Find heading by id or by text content
const headings = editor.querySelectorAll('h1, h2, h3, h4, h5, h6');
for (const heading of headings) {
// Generate slug from heading text (same as GitHub-style anchor)
const headingText = heading.textContent || '';
const slug = headingText
.toLowerCase()
.trim()
.replace(/[^\w\s\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf\uac00-\ud7af-]/g, '') // Keep alphanumeric, Japanese, Chinese, Korean, hyphen
.replace(/\s+/g, '-'); // Replace spaces with hyphens

if (slug === anchor || heading.id === anchor) {
const wrapper = editor.closest('.editor-wrapper');
if (wrapper) {
const wrapperRect = wrapper.getBoundingClientRect();
const headingRect = heading.getBoundingClientRect();
wrapper.scrollTo({ top: wrapper.scrollTop + headingRect.top - wrapperRect.top, behavior: 'smooth' });
} else {
heading.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// Briefly highlight the heading
heading.style.transition = 'background-color 0.3s';
heading.style.backgroundColor = 'var(--selection-bg)';
setTimeout(() => {
heading.style.backgroundColor = '';
}, 1500);
break;
}
let anchor = message.anchor;
if (typeof anchor !== 'string' || !anchor) return;
try { anchor = decodeURIComponent(anchor); } catch (_) { /* Keep literal malformed percent signs. */ }
// Match metadata inside the document, never user-controlled CSS selectors
// or IDs on the surrounding application UI. First document target wins.
const targets = editor.querySelectorAll('.markdown-anchor,h1,h2,h3,h4,h5,h6');
for (const target of targets) {
const custom = target.classList.contains('markdown-anchor');
const matches = custom ? JSON.parse(decodeURIComponent(target.dataset.anchorTargets)).includes(anchor) :
target.id === anchor || (target.textContent || '').toLowerCase().trim()
.replace(/[^\w\s\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf\uac00-\ud7af-]/g, '')
.replace(/\s+/g, '-') === anchor;
if (!matches) continue;
let visible = target;
if (custom) {
visible = target.nextElementSibling;
while (visible?.classList.contains('markdown-anchor')) visible = visible.nextElementSibling;
// An anchor at EOF still has a zero-height scroll position.
visible ||= target;
}
const wrapper = editor.closest('.editor-wrapper');
if (wrapper) {
const wrapperRect = wrapper.getBoundingClientRect();
const targetRect = visible.getBoundingClientRect();
wrapper.scrollTo({ top: wrapper.scrollTop + targetRect.top - wrapperRect.top, behavior: 'smooth' });
} else visible.scrollIntoView({ behavior: 'smooth', block: 'start' });
if (!visible.classList.contains('markdown-anchor')) {
visible.style.transition = 'background-color 0.3s';
visible.style.backgroundColor = 'var(--selection-bg)';
setTimeout(() => { visible.style.backgroundColor = ''; }, 1500);
}
break;
}
}
});
Expand Down
13 changes: 12 additions & 1 deletion src/webview/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -1469,7 +1469,7 @@ button.command-palette-item { border: 0; width: 100%; text-align: start; font: i
#exportOpenOutput { margin-top: 8px; background: var(--link-color); border: 1px solid var(--link-color); border-radius: 4px; padding: 6px 8px; color: var(--bg-color); font: inherit; cursor: pointer; }
#exportOpenOutput:hover, #exportOpenOutput:focus-visible { background: var(--link-color); color: var(--bg-color); outline-offset: 2px; }
#exportOpenOutput[hidden] { display: none; }
#editor > :first-child { margin-top: 0; }
#editor > :nth-child(1 of :not(.markdown-anchor)) { margin-top: 0; }
.reading-progress progress::-webkit-progress-bar { background: var(--sidebar-border); }
.reading-progress progress::-webkit-progress-value { background: var(--outline-active-color, var(--link-color)); }
.block-diagnostic-text { white-space: pre-wrap; font: 11px/1.5 var(--font-mono); padding: 8px; max-height: 160px; overflow: auto; }
Expand Down Expand Up @@ -1657,3 +1657,14 @@ html[data-table-toolbar-position="bottom-left"] .editor table, html[data-table-t
.toolbar-overflow .command-palette-label { white-space: normal; overflow-wrap: anywhere; }
.toolbar-overflow .command-palette-label small { display: block; font-size: 11px; opacity: .75; }
.toolbar-overflow .command-palette-shortcut { margin-left: auto; }

/* Navigation metadata keeps source without a visible paragraph or caret stop. */
.editor > .markdown-anchor {
height: 0;
min-height: 0;
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
pointer-events: none;
}
Loading
Loading