Repository Public
1// SP Notes iOS2// File: Editor/EditorController+Input.swift3// Description: Input ergonomics of the editor: Markdown shortcuts typed at the start of a paragraph (`#`, `##`, `###`, `-`, `*`,4// `1.`, `[]`, `[ ]`, `>`, ``` and `---`), each undoable in one step that brings the typed characters back, and the5// hooks of the slash menu. Nothing fires inside a code block.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import UIKit1112/// What a Markdown prefix typed at the start of a paragraph turns the paragraph into.13enum MarkdownShortcut: Equatable {14 case heading(Int), list(ListKind), quote, code(language: String?), rule1516 /// The shortcut for `prefix` (the text between the start of the paragraph and the caret) when a space is typed after it.17 static func onSpace(after prefix: String) -> MarkdownShortcut? {18 switch prefix {19 case "#": .heading(1)20 case "##": .heading(2)21 case "###": .heading(3)22 case "-", "*": .list(.bullet)23 case "1.": .list(.ordered)24 case "[]", "[ ]": .list(.task)25 case ">": .quote26 case "```": .code(language: nil)27 default: nil28 }29 }3031 /// The shortcut for a whole paragraph when Return is typed at its end: `---` → rule, ```` ```lang ```` → code block.32 static func onReturn(paragraph text: String) -> MarkdownShortcut? {33 if text == "---" { return .rule }34 guard text.hasPrefix("```") else { return nil }35 let language = String(text.dropFirst(3))36 guard language.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "+" || $0 == "#" || $0 == "-" }) else { return nil }37 return .code(language: language.isEmpty ? nil : language.lowercased())38 }39}4041extension EditorController {42 /// The text of the paragraph before the caret, when the caret is in a plain top-level-typed paragraph where shortcuts apply.43 private func shortcutPrefix(at location: Int) -> (paragraph: NSRange, style: LineStyle, prefix: String)? {44 let paragraph = paragraphRange(at: location)45 let style = style(at: paragraph.location)46 guard AttributedCodec.isTextual(style), style.type == NodeType.paragraph, location >= paragraph.location, location - paragraph.location <= 16 else { return nil }47 let before = NSRange(location: paragraph.location, length: location - paragraph.location)48 var plain = true49 if before.length > 0 { storage.enumerateAttribute(.attachment, in: before, options: []) { value, _, stop in if value != nil { plain = false; stop.pointee = true } } }50 guard plain else { return nil }51 return (paragraph, style, (storage.string as NSString).substring(with: before))52 }5354 private func allows(_ shortcut: MarkdownShortcut, in style: LineStyle) -> Bool {55 switch shortcut {56 // the first paragraph of a list item stays a paragraph (schema): no heading, code block or rule there57 case .heading, .code, .rule: style.innermostItem == nil58 case .list: style.innermostItem == nil59 case .quote: style.quoteDepth == 0 && style.innermostItem == nil60 }61 }6263 /// Called before a typed edit is applied. Returns true when the edit was consumed by a shortcut or by the slash menu.64 func handleInputAssist(range: NSRange, text: String) -> Bool {65 // slash menu: Return runs the highlighted command66 if slash.isActive, text == "\n" { if slash.commit() { return true } }67 guard range.length == 0 else { return false }68 if text == "/" {69 if slash.canBegin(at: range.location) { slash.pendingAnchor = range.location }70 return false71 }72 guard markdownShortcutsEnabled else { return false }73 if text == " ", let context = shortcutPrefix(at: range.location), let shortcut = MarkdownShortcut.onSpace(after: context.prefix), allows(shortcut, in: context.style) {74 apply(shortcut, removing: NSRange(location: context.paragraph.location, length: (context.prefix as NSString).length))75 return true76 }77 if text == "-", let context = shortcutPrefix(at: range.location), context.prefix == "--", context.paragraph.length == 3, allows(.rule, in: context.style) {78 apply(.rule, removing: NSRange(location: context.paragraph.location, length: 2))79 return true80 }81 if text == "\n", let context = shortcutPrefix(at: range.location), range.location == NSMaxRange(context.paragraph) - 1,82 let shortcut = MarkdownShortcut.onReturn(paragraph: context.prefix), allows(shortcut, in: context.style) {83 apply(shortcut, removing: NSRange(location: context.paragraph.location, length: (context.prefix as NSString).length))84 return true85 }86 return false87 }8889 /// Removes the typed prefix and applies the block change. Both are registered in the same undo group (one event): one ⌘Z90 /// restores the paragraph and the characters that were typed.91 private func apply(_ shortcut: MarkdownShortcut, removing prefix: NSRange) {92 let undo = textView.undoManager93 undo?.beginUndoGrouping()94 defer { undo?.endUndoGrouping() }95 if prefix.length > 0 {96 replace(prefix, with: NSAttributedString(), selectAfter: NSRange(location: prefix.location, length: 0), actionName: String(localized: "Raccourci Markdown"))97 }98 textView.selectedRange = clampSelection(NSRange(location: prefix.location, length: 0))99 switch shortcut {100 case .heading(let level): setBlockType("heading", level: level)101 case .list(let kind): toggleList(kind)102 case .quote: toggleBlockquote()103 case .code(let language):104 setBlockType("codeBlock")105 if let language { setCodeLanguage(language) }106 case .rule: insertBlockAtom(PMNode.horizontalRule())107 }108 undo?.setActionName(String(localized: "Raccourci Markdown"))109 Haptics.selection()110 }111112 /// Colours the large code blocks skipped while typing, after a pause.113 func scheduleDeferredCodeColouring() {114 guard !styler.pendingCode.isEmpty else { return }115 codeColourWork?.cancel()116 let work = DispatchWorkItem { [weak self] in MainActor.assumeIsolated { self?.colourPendingCodeNow() } }117 codeColourWork = work118 DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: work)119 }120121 func colourPendingCodeNow() {122 codeColourWork?.cancel()123 codeColourWork = nil124 guard !styler.pendingCode.isEmpty else { return }125 isLoading = true126 storage.beginEditing()127 for range in styler.colourPendingCode(storage) { storage.edited(.editedAttributes, range: range, changeInLength: 0) }128 storage.endEditing()129 isLoading = false130 }131}132