Alternative approach to properly aligning lists and tasks with indentation

This commit is contained in:
Zef Hemel
2026-05-28 13:26:09 +02:00
parent 83765385d2
commit a3feeb9a71
9 changed files with 393 additions and 138 deletions
+2
View File
@@ -6,6 +6,7 @@ import { hideHeaderMarkPlugin, hideMarksPlugin } from "./hide_mark.ts";
import { cleanBlockPlugin } from "./block.ts";
import { linkPlugin } from "./link.ts";
import { listBulletPlugin } from "./list.ts";
import { listIndentPlugin } from "./list_indent.ts";
import { tablePlugin } from "./table.ts";
import { taskListPlugin } from "./task.ts";
import { cleanWikiLinkPlugin } from "./wiki_link.ts";
@@ -71,6 +72,7 @@ export function cleanModePlugins(client: Client) {
})(),
}),
listBulletPlugin(),
listIndentPlugin(),
htmlInlinePlugin(client),
htmlBlockPlugin(client),
tablePlugin(client),
+6 -7
View File
@@ -26,7 +26,7 @@ export function listBulletPlugin() {
const listMark = state.sliceDoc(from, to);
if (bulletListMarkerRE.test(listMark)) {
const dec = Decoration.replace({
widget: new ListBulletWidget(listMark),
widget: new ListBulletWidget(),
});
widgets.push(dec.range(from, to));
} else {
@@ -46,16 +46,15 @@ export function listBulletPlugin() {
}
/**
* Widget to render list bullet mark.
* Widget that renders the bullet glyph (`•`) inline at the source position of
* the markdown list marker (`*`, `-`, `+`). Uses no positioning tricks — the
* widget sits exactly where the source char would, so nested-list bullets
* step right naturally with their leading whitespace.
*/
class ListBulletWidget extends WidgetType {
constructor(readonly bullet: string) {
super();
}
toDOM(): HTMLElement {
const listBullet = document.createElement("span");
listBullet.textContent = this.bullet;
listBullet.textContent = "•"; // U+2022 BULLET
listBullet.className = "cm-list-bullet";
return listBullet;
}
+114
View File
@@ -0,0 +1,114 @@
import { expect, test } from "vitest";
import { parser as baseParser } from "@lezer/markdown";
import type { SyntaxNode } from "@lezer/common";
import { TaskList } from "../markdown_parser/extended_task.ts";
import { computeMarkerWidth } from "./list_indent.ts";
const parser = baseParser.configure([TaskList]);
// Parse a single-line markdown source and return its first ListItem node + line text.
function firstListItem(source: string): { node: SyntaxNode; source: string } {
const tree = parser.parse(source);
let node: SyntaxNode | null = null;
tree.iterate({
enter: (n) => {
if (n.type.name === "ListItem" && !node) {
node = n.node;
return false;
}
},
});
if (!node) throw new Error(`no ListItem in: ${JSON.stringify(source)}`);
return { node, source };
}
test("computeMarkerWidth: plain unordered with *", () => {
const { node } = firstListItem("* item");
expect(computeMarkerWidth(node, 0)).toBe(2);
});
test("computeMarkerWidth: plain unordered with -", () => {
const { node } = firstListItem("- item");
expect(computeMarkerWidth(node, 0)).toBe(2);
});
test("computeMarkerWidth: nested unordered (2 leading spaces)", () => {
const { node } = firstListItem(" * item");
expect(computeMarkerWidth(node, 0)).toBe(4);
});
test("computeMarkerWidth: task at level 1", () => {
const { node } = firstListItem("* [ ] task");
expect(computeMarkerWidth(node, 0)).toBe(6);
});
test("computeMarkerWidth: task at level 2", () => {
const { node } = firstListItem(" * [ ] task");
expect(computeMarkerWidth(node, 0)).toBe(8);
});
test("computeMarkerWidth: multi-status task `[done]`", () => {
// `* [done] task` → marker zone = `* [done] ` = 9 chars
const { node } = firstListItem("* [done] task");
expect(computeMarkerWidth(node, 0)).toBe(9);
});
test("computeMarkerWidth: ordered single digit", () => {
const { node } = firstListItem("1. item");
expect(computeMarkerWidth(node, 0)).toBe(3);
});
test("computeMarkerWidth: ordered two digits", () => {
const { node } = firstListItem("10. item");
expect(computeMarkerWidth(node, 0)).toBe(4);
});
test("computeMarkerWidth: ordered three digits", () => {
const { node } = firstListItem("100. item");
expect(computeMarkerWidth(node, 0)).toBe(5);
});
test("computeMarkerWidth: ordered with task", () => {
const { node } = firstListItem("1. [ ] task");
expect(computeMarkerWidth(node, 0)).toBe(7);
});
test("computeMarkerWidth: deeply nested unordered (6 leading spaces, level 4)", () => {
// 6 leading spaces only parses as a ListItem inside a proper nested list,
// so build a 4-level structure and pick the deepest ListItem.
const source = "* a\n * b\n * c\n * d";
const tree = parser.parse(source);
let deepest: SyntaxNode | null = null;
let deepestStart = -1;
tree.iterate({
enter: (n) => {
if (n.type.name === "ListItem" && n.from > deepestStart) {
deepest = n.node;
deepestStart = n.from;
}
},
});
if (!deepest) throw new Error("no ListItem");
const node: SyntaxNode = deepest;
// The deepest item's line starts at offset 14 (the " * d" line).
const lineStart = source.lastIndexOf("\n", node.from) + 1;
expect(computeMarkerWidth(node, lineStart)).toBe(8);
});
test("computeMarkerWidth: respects non-zero lineStart", () => {
// Two-line doc: first line is empty (or text), second line is "* item"
const source = "intro\n* item";
const tree = parser.parse(source);
let node: SyntaxNode | null = null;
tree.iterate({
enter: (n) => {
if (n.type.name === "ListItem" && !node) {
node = n.node;
return false;
}
},
});
if (!node) throw new Error("no ListItem");
// Line start for the second line is at offset 6 (after "intro\n").
expect(computeMarkerWidth(node, 6)).toBe(2);
});
+71
View File
@@ -0,0 +1,71 @@
import type { SyntaxNode } from "@lezer/common";
import type { Range } from "@codemirror/state";
import { Decoration } from "@codemirror/view";
import { syntaxTree } from "@codemirror/language";
import { decoratorStateField } from "./util.ts";
/**
* Compute the marker-zone width in source columns (== `ch` units) for a
* single ListItem node.
* @param listItem The `ListItem` syntax node.
* @param lineStart Absolute offset of the line this list-item starts on.
*/
export function computeMarkerWidth(
listItem: SyntaxNode,
lineStart: number,
): number {
const mark = listItem.firstChild;
if (!mark || mark.name !== "ListMark") {
return 0;
}
const leadingIndent = mark.from - lineStart;
const markLength = mark.to - mark.from;
// TaskState wraps `[X]` / `[done]` / etc. (length varies by status string).
// Width contribution = TaskState range length + 1 for the trailing space.
const taskState = listItem.getChild("Task")?.getChild("TaskState");
const taskExtra = taskState ? (taskState.to - taskState.from) + 1 : 0;
return leadingIndent + markLength + 1 + taskExtra;
}
/**
* Emit a per-line `padding-left` / `text-indent` for every line owned by a
* ListItem, using `computeMarkerWidth` to derive the value from source.
*
* Nested list lines: when we iterate the syntax tree, outer ListItems are
* visited before their nested children. CodeMirror's Decoration.set with
* `sort: true` resolves multiple line decorations at the same position by
* picking the latest one added in iteration order — so the inner item's
* (deeper) marker width overwrites the outer item's for the nested portion.
* This is the behaviour we want: every line gets the marker width of the
* innermost ListItem it belongs to.
*/
export function listIndentPlugin() {
return decoratorStateField((state) => {
const widgets: Range<Decoration>[] = [];
const doc = state.doc;
syntaxTree(state).iterate({
enter: ({ type, from, to, node }) => {
if (type.name !== "ListItem") return;
const startLine = doc.lineAt(from);
const width = computeMarkerWidth(node, startLine.from);
if (width <= 0) return;
const styleAttr =
`padding-left:${width}ch;text-indent:-${width}ch`;
const endLine = doc.lineAt(to);
for (
let lineNo = startLine.number;
lineNo <= endLine.number;
lineNo++
) {
const line = doc.line(lineNo);
widgets.push(
Decoration.line({
attributes: { style: styleAttr },
}).range(line.from),
);
}
},
});
return Decoration.set(widgets, true);
});
}
+1 -1
View File
@@ -243,7 +243,7 @@
}
}
.cm-list-bullet::after {
.cm-list-bullet {
color: var(--editor-list-bullet-color);
}
+23 -128
View File
@@ -92,133 +92,13 @@
border: 0;
}
// Indentation of follow-up lines
@mixin lineOverflow($baseIndent, $bulletIndent: 0) {
text-indent: calc(-1 * (#{$baseIndent}ch + 2ch));
padding-left: calc(#{$baseIndent}ch + 2ch);
&.sb-line-task {
text-indent: calc(-1 * (#{$baseIndent}ch + 5ch));
padding-left: calc(#{$baseIndent}ch + 5ch);
.cm-list-bullet::after {
left: calc(#{$baseIndent}ch + 5ch);
}
}
&.sb-line-blockquote {
text-indent: calc(-1 * (#{$baseIndent}ch + 4ch));
padding-left: calc(#{$baseIndent}ch + 4ch);
}
.cm-list-bullet::after {
left: calc(#{$baseIndent}ch + #{$bulletIndent}ch + 2ch);
}
}
.sb-line-ul {
&.sb-line-li-1 {
@include lineOverflow(0);
}
&.sb-line-li-1.sb-line-li-2 {
@include lineOverflow(2);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3 {
@include lineOverflow(4);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4 {
@include lineOverflow(6);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4.sb-line-li-5 {
@include lineOverflow(8);
}
}
.sb-line-ol {
&.sb-line-li-1 {
@include lineOverflow(1);
}
&.sb-line-li-1.sb-line-li-2 {
@include lineOverflow(4);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3 {
@include lineOverflow(7);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4 {
@include lineOverflow(10);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4.sb-line-li-5 {
@include lineOverflow(13);
}
}
.sb-line-ol.sb-line-ul {
// &.sb-line-li-1 {
// @include lineOverflow(1);
// }
&.sb-line-li-1.sb-line-li-2 {
@include lineOverflow(3);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3 {
@include lineOverflow(6);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4 {
@include lineOverflow(9);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4.sb-line-li-5 {
@include lineOverflow(12);
}
}
.sb-line-blockquote {
&.sb-line-li-1 {
@include lineOverflow(-1, 2);
}
&.sb-line-li-1.sb-line-li-2 {
@include lineOverflow(1, 2);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3 {
@include lineOverflow(4);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4 {
@include lineOverflow(6);
}
&.sb-line-li-1.sb-line-li-2.sb-line-li-3.sb-line-li-4.sb-line-li-5 {
@include lineOverflow(8);
}
}
.sb-line-comment {
text-indent: -1 * 3ch;
padding-left: 3ch;
}
.cm-list-bullet {
position: relative;
visibility: hidden;
}
.cm-list-bullet::after {
visibility: visible;
position: absolute;
content: "\2022";
/* U+2022 BULLET */
color: var(--editor-list-bullet-color, inherit);
}
.cm-task-checked,
@@ -268,6 +148,18 @@
text-indent: -7ch;
}
.sb-checkbox {
display: inline-block;
// 3 source columns ([, space, ]) → widget occupies the same 3ch so
// toggling cursor in/out doesn't cause a horizontal shift, and the
// wrapped-line hanging indent (computed at 6ch from `* [ ] `) lines
// up with the first line's text.
width: 3ch;
// Stop the inherited negative text-indent on list-item lines from
// dragging the inner <input> out of the checkbox's own box.
text-indent: 0;
}
.sb-checkbox > input[type="checkbox"] {
width: 3ch;
}
@@ -320,7 +212,12 @@
.sb-wiki-link {
border-radius: 5px;
// Horizontal-only chip gutter that doesn't take layout width or add
// vertical box height: 5px of padding on each side is cancelled by
// -5px margin, so the background extends visually around the text but
// adjacent inline content isn't pushed away.
padding: 0 5px;
margin: 0 -5px;
// white-space: nowrap;
text-decoration: none;
cursor: pointer;
@@ -369,13 +266,11 @@
flex-direction: column;
}
.sb-task-mark {
font-size: 91%;
}
.sb-task-state {
font-size: 91%;
}
// .sb-task-mark / .sb-task-state previously used font-size: 91% to make
// the `[`, ` `, `]` source chars visually subtle in cursor-in mode. That
// broke column-equivalence with the 3ch checkbox widget (cursor-out), so
// the size shrink is gone. Color/opacity rules in colors.scss continue to
// distinguish them visually.
.sb-task-dropdown {
cursor: pointer;
+86
View File
@@ -0,0 +1,86 @@
import { expect, gotoSilverBulletPage, test } from "./fixtures.ts";
const SPACE_FILES = {
"Outline.md": `# Outline
* plain
- hyphen
* [ ] task
10. ten
100. hundred
* outer
* inner
* deeper
`,
};
const PROBES = [
{ text: "plain", label: "plain-asterisk" },
{ text: "hyphen", label: "plain-hyphen" },
{ text: "task", label: "task" },
{ text: "ten", label: "ordered-2-digit" },
{ text: "hundred", label: "ordered-3-digit" },
{ text: "deeper", label: "deep-nesting" },
];
test.use({ spaceFiles: SPACE_FILES });
function measureFirstGlyphX(text: string) {
const line = Array.from(document.querySelectorAll(".cm-line"))
.find((l) => l.textContent?.includes(text));
if (!line) return null;
const lineRect = line.getBoundingClientRect();
const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
let node: Node | null;
while ((node = walker.nextNode())) {
const t = node.textContent ?? "";
if (!t.length) continue;
const r = document.createRange();
r.selectNodeContents(node);
const rect = r.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) continue;
return rect.left - lineRect.left;
}
return null;
}
test("list lines: zero horizontal shift on cursor in/out", async ({
sbPage,
sbServer,
}) => {
await gotoSilverBulletPage(sbPage, sbServer, "Outline");
await sbPage.locator(".cm-line.sb-line-li").first().waitFor({
state: "visible",
timeout: 10_000,
});
const h1 = sbPage.locator(".cm-line.sb-line-h1").first();
for (const probe of PROBES) {
const lineLocator = sbPage
.locator(".cm-line", { hasText: probe.text })
.first();
await lineLocator.scrollIntoViewIfNeeded();
// Cursor OUT: park on H1 (live-preview rendering for our line)
await h1.click();
await sbPage.waitForTimeout(75);
const xOut = await sbPage.evaluate(measureFirstGlyphX, probe.text);
expect(
xOut,
`${probe.label}: should have a measurable first glyph (out)`,
).not.toBeNull();
// Cursor IN: click into this list line (raw-source rendering)
await lineLocator.click();
await sbPage.waitForTimeout(75);
const xIn = await sbPage.evaluate(measureFirstGlyphX, probe.text);
expect(
xIn,
`${probe.label}: should have a measurable first glyph (in)`,
).not.toBeNull();
expect(Math.abs((xOut as number) - (xIn as number)), `${probe.label}: |xOut - xIn| ≤ 1px`).toBeLessThanOrEqual(1);
}
});
+87
View File
@@ -0,0 +1,87 @@
# Unordered lists
* Short
* Long item that will wrap its line eventually when I keep typing, this will be good
* Short sub-item
* Longer sub-item that will eventually wrap the line when I keep typing
* [ ] Task
* [x] Done task
* [ ] Task that will eventually also wrap its line to see how this goes etc.
* Unordered list item:
* [ ] With a task sub item
* [ ] And a long one that will eventually wrap its line if I keep typing
# Mixed bullet markers
- Hyphen marker
* Asterisk marker
- Hyphen with a long line that will wrap to verify hanging indent works for `-` too
# Deep nesting
* Level 1
* Level 2
* Level 3
* Level 4
* Level 5
* Level 6 — deeper than today's CSS covers
* Level 7 — long line that wraps so we can see the hanging indent at extreme depth
# Ordered lists
1. Short
2. Long item that will wrap its line eventually when I keep typing, this will be good
1. Short sub-item
2. Longer sub-item that will eventually wrap the line when I keep typing
4. And a third
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten — two-digit number, today's CSS reserves only 3ch
11. Eleven — wraps if I keep typing to see the hanging indent
100. Three-digit edge case — does it line up with the items above?
# Mixed ordered + unordered
1. Numbered parent
* Unordered child
* Another unordered child
* [ ] A task as ordered's child
* Unordered parent
1. Numbered child
2. Another numbered child
3. [ ] Task inside ordered child and now what will happen when this starts to wrap. Oh it looks nice!
# Inline formatting in list items
* **Bold** text in a list
* *Italic* text and `inline code`
* A [[SilverBullet]] wiki link embedded
* A regular [external link](https://example.com) in the middle of a line
* Mix: **bold**, *italic*, `code`, [[WikiLink]], [ext](http://x) — does the wrap stay aligned?
# Task states
* [ ] Open task
* [x] Completed task
* [ ] Task with **bold** and a [[WikiLink]] inside
* [ ] Long task with formatting: **bold**, *italic*, `code`, [[Link]] — verify wrapped lines hang correctly
# Code block inside list item
* Item with a fenced code block:
```js
const x = 1;
const y = 2;
```
* Next item — does alignment recover after the code block?
# Multi-paragraph list items
* First paragraph of an item.
Second paragraph of the same item, indented two spaces in source.
* Next item — does the indent of the second paragraph match the first?
# Links section
These two should vertically align perfectly:
[[SilverBullet]]
item
A a line above a link
A line with [[SilverBullet]] in the middle and `code` and **bold** — chip should not add box width.
+3 -2
View File
@@ -3,10 +3,11 @@ An attempt at documenting the changes/new features introduced in each release.
## Edge
Whenever a commit is pushed to the `main` branch, within ~5 minutes, it will be released as a docker image with the `:v2` tag, and a binary in the [edge release](https://github.com/silverbulletmd/silverbullet/releases/tag/edge). If you want to live on the bleeding edge of SilverBullet goodness (or regression) this is where to do it.
* New `relation` indexed object capturing generalized object-to-object relationships: typed edges from frontmatter, inline `[key: value]` attributes, and `#tag` fenced data blocks; untyped mentions; and co-mention edges between refs co-occurring in the same item, nested item, or paragraph. The (now) legacy `link` is reimplemented as a virtual collection on top of `relation` now and should keep acting as before.
* Fix: List/outline alignment: bullets, checkboxes and ordered-list numbers now line up in a clean column regardless of nesting depth, list type, or whether items are tasks.
* Potentially **breaking** CSS change for theme authors: per-nesting-level indent values previously carried by `.sb-line-ul.sb-line-li-N`, `.sb-line-ol.sb-line-li-N`, `.sb-line-task` and `.sb-line-blockquote.sb-line-li-N` selectors have been removed.
* `index.contentPages` now accepts an optional `tag` argument to filter content pages by an additional tag, matching the other type-specific [[API/index]] helpers.
* Picker fuzzy search: replaced Fuse.js with a custom scorer that supports multi-token queries (e.g. "silv todo" now matches "SilverBullet/TODO"), path-aware ranking, and bounded typo tolerance.
* New `relation` indexed object capturing generalized object-to-object relationships: typed edges from frontmatter, inline `[key: value]` attributes, and `#tag` fenced data blocks; untyped mentions; and co-mention edges between refs co-occurring in the same item, nested item, or paragraph. The (now) legacy `link` is reimplemented as a virtual collection on top of `relation` now and should keep acting as before.
* **Important**: Run `Space: Reindex` after upgrading (just once) to this version to make linked mentions and other features work again (this should be automatic, but just in case)
* Fix: forced space reindex handling
* Fix: clicking a wiki link to a page now places the cursor just after the page's frontmatter on first visit (matching fresh-load behavior), instead of at position 0. Pages already visited in the session still restore their previously saved cursor position.
* Fix: `$`-anchor refs now resolve through the index from every navigation path