feat: continue nested markdown lists on return

This commit is contained in:
Valdemar Lorenzen
2026-10-19 11:11:32 +02:00
parent 9ce2997c19
commit 8e1546d502
3 changed files with 165 additions and 2 deletions
+1 -1
View File
@@ -139,7 +139,7 @@ Search for **Conjure Notes**, identified by its centered 📔 icon, or assign it
Actions opens the same searchable popup style used throughout Conjure, with **Browse Notes** (Command-P) and **New Note** (Command-N). Command-N creates a note while the editor or either popup is focused. Command-P toggles Browse Notes even while its footer pill is covered. Escape, Back, or clicking outside closes an open popup and returns focus to the editor without leaving Notes; another Escape dismisses the launcher. Control-J/K navigates only while a popup is open, preserving normal editor commands when it is closed. Actions opens the same searchable popup style used throughout Conjure, with **Browse Notes** (Command-P) and **New Note** (Command-N). Command-N creates a note while the editor or either popup is focused. Command-P toggles Browse Notes even while its footer pill is covered. Escape, Back, or clicking outside closes an open popup and returns focus to the editor without leaving Notes; another Escape dismisses the launcher. Control-J/K navigates only while a popup is open, preserving normal editor commands when it is closed.
Edit Markdown directly: headings, bold, italic, lists, links, inline code, and fenced code blocks are highlighted while the source remains visible. Paste images or drag image files into the editor to embed them locally; no file-picker button is needed. Return inserts a newline. Command-Z undoes edits; Command-Shift-Z redoes them. Undo history is cleared when switching notes so edits cannot spill into another note. Edit Markdown directly: headings, bold, italic, lists, links, inline code, and fenced code blocks are highlighted while the source remains visible. Paste images or drag image files into the editor to embed them locally; no file-picker button is needed. Return continues bullet (`-`, `*`, `+`), numbered (`1.`, `1)`), and task lists at the same indentation, incrementing numbers and resetting task checkboxes. On an empty item, Return exits one nesting level; repeat to leave the list entirely. Nesting has no fixed depth limit. Prose and fenced code retain ordinary newlines. Command-Z undoes edits; Command-Shift-Z redoes them. Undo history is cleared when switching notes so edits cannot spill into another note.
Fenced code uses [HighlighterSwift](https://github.com/smittytone/HighlighterSwift) (Highlight.js) for language-aware token colors. Add a language after the opening backticks or tildes, for example `py`, `python`, `swift`, `js`, or `json`. Unlabeled fences use automatic detection; unknown languages remain plain monospace. Highlighting runs entirely offline. Fenced code uses [HighlighterSwift](https://github.com/smittytone/HighlighterSwift) (Highlight.js) for language-aware token colors. Add a language after the opening backticks or tildes, for example `py`, `python`, `swift`, `js`, or `json`. Unlabeled fences use automatic detection; unknown languages remain plain monospace. Highlighting runs entirely offline.
+72 -1
View File
@@ -119,6 +119,77 @@ final class NotesController: NSViewController, NSTextViewDelegate {
_ = save() _ = save()
} }
private static let listItem = try! NSRegularExpression(
pattern: "^([ \\t]*)([-+*]|([0-9]+)([.)]))([ \\t]+|$)(?:\\[([ xX])\\]([ \\t]+|$))?"
)
private static func indentationWidth(_ indentation: String) -> Int {
indentation.reduce(0) { $1 == "\t" ? $0 + 4 - $0 % 4 : $0 + 1 }
}
private static func continuedPrefix(_ item: NSTextCheckingResult, in line: NSString) -> String? {
var marker = line.substring(with: item.range(at: 2))
if item.range(at: 3).location != NSNotFound {
guard let number = UInt64(line.substring(with: item.range(at: 3))), number < UInt64.max else { return nil }
marker = "\(number + 1)" + line.substring(with: item.range(at: 4))
}
var prefix = line.substring(with: item.range(at: 1)) + marker + line.substring(with: item.range(at: 5))
if item.range(at: 6).location != NSNotFound {
prefix += "[ ]" + line.substring(with: item.range(at: 7))
}
return prefix
}
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
guard textView === editor, editor.isEditable,
commandSelector == #selector(NSResponder.insertNewline(_:)) else { return false }
let source = editor.string as NSString
let selection = editor.selectedRange()
var start = 0, end = 0
source.getLineStart(&start, end: nil, contentsEnd: &end,
for: NSRange(location: selection.location, length: 0))
let line = source.substring(with: NSRange(location: start, length: end - start)) as NSString
guard let item = Self.listItem.firstMatch(in: line as String, range: NSRange(location: 0, length: line.length)),
selection.location >= start + item.range.length, NSMaxRange(selection) <= end,
!MarkdownHighlighting.codeBlocks(in: editor.string).contains(where: {
selection.location >= $0.body.location && selection.location <= NSMaxRange($0.body)
}) else { return false }
let indent = line.substring(with: item.range(at: 1))
let marker = line.substring(with: item.range(at: 2))
// Spaced thematic breaks are not list items.
if marker == "-" || marker == "*" {
let characters = (line as String).lazy.filter { !$0.isWhitespace }
let bullet = marker.first!
if characters.count >= 3, characters.allSatisfy({ $0 == bullet }) { return false }
}
let body = line.substring(from: item.range.length)
if body.trimmingCharacters(in: .whitespaces).isEmpty {
var replacement = ""
var previous = start
let depth = Self.indentationWidth(indent)
while depth > 0, previous > 0 {
let range = source.lineRange(for: NSRange(location: previous - 1, length: 0))
previous = range.location
let ancestor = source.substring(with: range) as NSString
if let parent = Self.listItem.firstMatch(in: ancestor as String, range: NSRange(location: 0, length: ancestor.length)) {
let parentIndent = ancestor.substring(with: parent.range(at: 1))
if Self.indentationWidth(parentIndent) < depth {
replacement = Self.continuedPrefix(parent, in: ancestor) ?? ""
break
}
} else if !(ancestor as String).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
let leading = (ancestor as String).prefix { $0 == " " || $0 == "\t" }
if Self.indentationWidth(String(leading)) < depth { break }
}
}
editor.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
} else {
guard let prefix = Self.continuedPrefix(item, in: line) else { return false }
editor.insertText("\n" + prefix, replacementRange: selection)
}
return true
}
@discardableResult @discardableResult
func save() -> Bool { func save() -> Bool {
guard isDirty, let store, let selectedID else { return true } guard isDirty, let store, let selectedID else { return true }
@@ -244,7 +315,7 @@ enum MarkdownHighlighting {
}() }()
private static let openingFence = try! NSRegularExpression(pattern: "(?m)^ {0,3}(`{3,}|~{3,})([^\\r\\n]*)\\r?\\n") private static let openingFence = try! NSRegularExpression(pattern: "(?m)^ {0,3}(`{3,}|~{3,})([^\\r\\n]*)\\r?\\n")
private static func codeBlocks(in text: String) -> [(range: NSRange, body: NSRange, language: String?)] { fileprivate static func codeBlocks(in text: String) -> [(range: NSRange, body: NSRange, language: String?)] {
let source = text as NSString let source = text as NSString
var blocks: [(NSRange, NSRange, String?)] = [] var blocks: [(NSRange, NSRange, String?)] = []
var cursor = 0 var cursor = 0
@@ -230,3 +230,95 @@ func notesLauncherRoutesShortcutsAndTearsDownPickersWithoutTakingEditorNavigatio
#expect(!descendants(content).compactMap { $0 as? NSSearchField }.contains { $0.accessibilityLabel() == "Search notes" }) #expect(!descendants(content).compactMap { $0 as? NSSearchField }.contains { $0.accessibilityLabel() == "Search notes" })
#expect(launcherSearch.isHidden == false) #expect(launcherSearch.isHidden == false)
} }
@Test @MainActor
func markdownListReturnContinuesExitsAndUndoesAtArbitraryDepths() throws {
_ = NSApplication.shared
let suite = "NotesLists.\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: suite))
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(suite)
defer {
defaults.removePersistentDomain(forName: suite)
try? FileManager.default.removeItem(at: directory)
}
let controller = NotesController(defaults: defaults, directory: directory)
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 750, height: 390),
styleMask: .borderless, backing: .buffered, defer: false)
window.contentViewController = controller
defer { _ = controller.close(); window.orderOut(nil) }
func descendants(_ view: NSView) -> [NSView] { [view] + view.subviews.flatMap(descendants) }
let editor = try #require(descendants(controller.view).compactMap { $0 as? NSTextView }.first)
window.makeFirstResponder(editor)
let enter = try #require(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [],
timestamp: 1, windowNumber: window.windowNumber, context: nil, characters: "\r",
charactersIgnoringModifiers: "\r", isARepeat: false, keyCode: 36))
func reset(_ text: String) {
editor.insertText(text, replacementRange: NSRange(location: 0, length: editor.string.utf16.count))
editor.breakUndoCoalescing()
editor.undoManager?.removeAllActions()
}
let examples = [
("- fox 🦊", "- fox 🦊\n- "),
(" * nested", " * nested\n * "),
("\t+ nested", "\t+ nested\n\t+ "),
("9. ninth", "9. ninth\n10. "),
(" 12) nested", " 12) nested\n 13) "),
("- [x] finished", "- [x] finished\n- [ ] "),
("- ", ""), ("+ \t ", ""), ("4. ", ""), ("- [ ] ", ""),
("- parent\n - ", "- parent\n- "),
("1. parent\n * ", "1. parent\n2. "),
("- parent\n\t+ child\n\t\t3) ", "- parent\n\t+ child\n\t+ "),
("- first\n - child\n - ", "- first\n - child\n- "),
("- parent\n continuation\n - ", "- parent\n continuation\n- "),
("- parent\nparagraph\n - ", "- parent\nparagraph\n"),
("- parent\n + ", "- parent\n- "),
("- parent\r\n - ", "- parent\r\n- "),
("prose", "prose\n"), ("* * *", "* * *\n"),
("```md\n- literal", "```md\n- literal\n"),
("~~~\n 1. literal", "~~~\n 1. literal\n"),
("```\n- literal\n```\n- real", "```\n- literal\n```\n- real\n- "),
]
for (before, after) in examples {
reset(before)
editor.keyDown(with: enter)
#expect(editor.string == after, "Return in \(before.debugDescription)")
#expect(editor.selectedRange() == NSRange(location: after.utf16.count, length: 0))
}
reset("- ab🦊cd")
editor.setSelectedRange((editor.string as NSString).range(of: "🦊"))
editor.keyDown(with: enter)
#expect(editor.string == "- ab\n- cd")
#expect(editor.selectedRange() == NSRange(location: 7, length: 0))
reset("- parent\n - child\n - leaf")
editor.keyDown(with: enter)
#expect(editor.string == "- parent\n - child\n - leaf\n - ")
editor.keyDown(with: enter)
#expect(editor.string == "- parent\n - child\n - leaf\n - ")
editor.keyDown(with: enter)
#expect(editor.string == "- parent\n - child\n - leaf\n- ")
editor.keyDown(with: enter)
#expect(editor.string == "- parent\n - child\n - leaf\n")
// Nesting follows actual ancestor indentation, not a fixed depth or indent size.
let ancestors = (0..<80).map { String(repeating: " ", count: $0 * 2) + "- level \($0)" }.joined(separator: "\n")
let before = ancestors + "\n" + String(repeating: " ", count: 160) + "- leaf"
reset(before)
editor.keyDown(with: enter)
#expect(editor.string == before + "\n" + String(repeating: " ", count: 160) + "- ")
for depth in stride(from: 79, through: 0, by: -1) {
editor.keyDown(with: enter)
#expect(editor.string == before + "\n" + String(repeating: " ", count: depth * 2) + "- ")
}
editor.keyDown(with: enter)
#expect(editor.string == before + "\n")
reset("7. saved")
editor.keyDown(with: enter)
editor.breakUndoCoalescing()
#expect(editor.string == "7. saved\n8. ")
editor.undoManager?.undo()
#expect(editor.string == "7. saved")
editor.undoManager?.redo()
#expect(editor.string == "7. saved\n8. ")
let restored = try NotesStore(directory: directory)
let id = try #require(defaults.string(forKey: "selectedNote").flatMap(UUID.init(uuidString:)))
#expect(restored.notes.first { $0.id == id }?.contents.string == "7. saved\n8. ")
}