nano-ui-0.2.0.0: lib/NanoUI/Widgets/TextEditor.hs
-- | The editing core every text field shares: a document, a selection and an
-- undo history, changed only by 'TextCommand's. Keys and menu rows map onto
-- commands, and an app can run the same commands on a field.
module NanoUI.Widgets.TextEditor
( -- * Commands
TextCommand (..)
, TextMotion (..)
-- * Editors
, Editor (..)
, EditorMode (..)
, singleLineMode
, multiLineMode
, editorFromBuffer
, editorSelection
, hasSelection
, runCommand
, runCommandIO
-- * Key bindings
, inputTextCommands
, keyCommand
-- * History
, EditHistory (..)
, EditGroup (..)
, StoredEdit (..)
, EditKind (..)
, emptyHistory
, sealHistory
, canUndo
, canRedo
) where
import Control.Monad (unless, void, when)
import Data.Char (isControl, isMark, isSpace, toLower)
import Data.Text qualified as T
import Data.Text.Short qualified as TS
import NanoUI.Internal.Context (Context (..))
import NanoUI.Internal.TextEditor.Types
import NanoUI.Internal.Input (Input (..), Key (..), Modifiers (..), chordModifiers, inputKeysElem, isCommandKey, modJump, modMacCommand, modPrimary, noModifiers, onMac)
import NanoUI.Widgets.TextBuffer (Cursor (..), TextBuffer, TextEdit (..))
import NanoUI.Widgets.TextCommand (TextCommand (..), TextMotion (..))
import NanoUI.Widgets.TextBuffer qualified as TB
-- | Editable, copyable text without newline insertion.
singleLineMode :: EditorMode
singleLineMode = EditorMode {modeMultiLine = False, modeEditable = True, modeCopyable = True}
-- | Editable, copyable text with multiline commands enabled.
multiLineMode :: EditorMode
multiLineMode = singleLineMode {modeMultiLine = True}
-- | A document with its selection (the cursor is the buffer's, the anchor
-- the other end) and history.
data Editor = Editor
{ editorBuffer :: !TextBuffer
, editorAnchor :: !Cursor
, editorHistory :: !EditHistory
}
deriving (Show)
-- | Start an editor with no selection or history at the buffer's current cursor.
editorFromBuffer :: TextBuffer -> Editor
editorFromBuffer buf = Editor buf (TB.getCursor buf) emptyHistory
-- | @(anchor, cursor)@.
editorSelection :: Editor -> (Cursor, Cursor)
editorSelection ed = (editorAnchor ed, TB.getCursor (editorBuffer ed))
-- | Whether the selection anchor differs from the buffer cursor.
hasSelection :: Editor -> Bool
hasSelection ed = editorAnchor ed /= TB.getCursor (editorBuffer ed)
--------------------------------------------------------------------------------
-- History
--------------------------------------------------------------------------------
-- | No undo/redo steps and no open edit group.
emptyHistory :: EditHistory
emptyHistory = EditHistory [] [] 0 False
-- | Start the next edit in a group of its own.
sealHistory :: EditHistory -> EditHistory
sealHistory h = h {historyOpen = False}
-- | Whether at least one edit group can be undone.
canUndo :: EditHistory -> Bool
canUndo = not . null . historyUndo
-- | Whether at least one undone group can be reapplied.
canRedo :: EditHistory -> Bool
canRedo = not . null . historyRedo
-- | Undo steps kept per field. Older steps are dropped in batches.
maxHistoryDepth :: Int
maxHistoryDepth = 500
-- | Maximum individual edits merged into one undo group.
maxGroupEdits :: Int
maxGroupEdits = 256
-- | Approximate UTF-8 byte budget for stored undo history per field.
maxHistoryBytes :: Int
maxHistoryBytes = 4 * 1024 * 1024
editBytes :: StoredEdit -> Int
editBytes (StoredEdit _ rm ins) = TS.length rm + TS.length ins
groupBytes :: EditGroup -> Int
groupBytes g = foldl' (\acc e -> acc + editBytes e) 0 (groupEdits g)
-- | Trim undo groups to both 'maxHistoryDepth' and 'maxHistoryBytes', always
-- retaining the most recent group so a single large edit can still be undone.
trimUndoGroups :: [EditGroup] -> ([EditGroup], Int)
trimUndoGroups [] = ([], 0)
trimUndoGroups (newest : rest) =
let (keptRest, n) = go (groupBytes newest) 1 rest
kept = newest : keptRest
in length kept `seq` (kept, n)
where
go !_ !n [] = ([], n)
go !bytes !n (g : gs)
| n >= maxHistoryDepth || bytes + gb > maxHistoryBytes = ([], n)
| otherwise = let (tailGs, totalN) = go (bytes + gb) (n + 1) gs in (g : tailGs, totalN)
where
gb = groupBytes g
-- | Record an edit. Typing joins the group before it while the selection is
-- where that group left it, until a new word starts; consecutive deletes
-- join the same way. Anything else starts a group. Recording clears redo.
record :: EditKind -> (Cursor, Cursor) -> TextEdit -> (Cursor, Cursor) -> EditHistory -> EditHistory
record kind before edit after (EditHistory undos _ depth open) =
case undos of
g : rest
| joins g ->
EditHistory (g {groupEdits = stored : groupEdits g, groupAfter = after} : rest) [] depth True
_ ->
let depth' = depth + 1
group = EditGroup kind [stored] before after
in if depth' > maxHistoryDepth + 50 || editBytes stored > 65536
then
let (kept, n) = trimUndoGroups (group : undos)
in EditHistory kept [] n True
else EditHistory (group : undos) [] depth' True
where
-- Built now, so the list keeps the compact copies and not the edit,
-- whose texts are slices of the whole line.
!stored = StoredEdit (editAt edit) (TS.fromText (editRemoved edit)) (TS.fromText (editInserted edit))
joins g =
open
&& kind /= EditOther
&& groupKind g == kind
&& groupAfter g == before
&& null (drop (maxGroupEdits - 1) (groupEdits g))
&& (kind /= EditTyping || not (startsWord g))
-- A letter typed after a space starts a new undo step.
startsWord g = case (groupEdits g, T.uncons (editInserted edit)) of
(StoredEdit _ _ prevInserted : _, Just (c, _)) -> not (isSpace c) && maybe False (isSpace . snd) (TS.unsnoc prevInserted)
_ -> False
--------------------------------------------------------------------------------
-- Commands
--------------------------------------------------------------------------------
-- | Run a command that needs no clipboard. 'Cut', 'Copy' and 'Paste' do
-- nothing here; 'runCommandIO' runs them.
runCommand :: EditorMode -> TextCommand -> Editor -> Editor
runCommand mode cmd ed@(Editor buf anchor hist) =
case cmd of
InsertText raw
| modeEditable mode ->
let txt = singleLine raw
in replaceSelection (if T.length txt == 1 && txt /= "\n" then EditTyping else EditOther) txt
Delete motion
| modeEditable mode ->
if hasSelection ed
then replaceSelection EditDeleting T.empty
else edit EditDeleting (TB.replaceEdit T.empty cursor (motionTarget motion) buf)
Move motion False
-- Left and Right without Shift collapse a selection onto its start
-- and end, as every platform's text field does.
| hasSelection ed, motion == CharLeft || motion == CharRight ->
let end = (if motion == CharLeft then min else max) anchor cursor
in Editor (TB.withCursor end buf) end (sealHistory hist)
Move motion extend ->
let moved = moveBuffer motion
in Editor moved (if extend then anchor else TB.getCursor moved) (sealHistory hist)
SelectAll -> runCommand mode (Select (Cursor 0 0) (TB.documentEnd buf)) ed
Select a c ->
Editor (TB.withCursor (TB.snapToCluster buf c) buf) (TB.snapToCluster buf a) (sealHistory hist)
Replace a b txt
| modeEditable mode -> edit EditOther (TB.replaceEdit (singleLine txt) a b buf)
ReplaceAll txt -> runCommand mode (Replace (Cursor 0 0) (TB.documentEnd buf) txt) ed
Undo
| g : rest <- historyUndo hist ->
restore (groupBefore g) (foldl' (\b e -> TB.applyEdit (TB.invertEdit (replayed e)) b) buf (groupEdits g)) $
hist {historyUndo = rest, historyRedo = g : historyRedo hist, historyDepth = historyDepth hist - 1}
Redo
| g : rest <- historyRedo hist ->
restore (groupAfter g) (foldr (TB.applyEdit . replayed) buf (groupEdits g)) $
hist {historyUndo = g : historyUndo hist, historyRedo = rest, historyDepth = historyDepth hist + 1}
_ -> ed
where
cursor = TB.getCursor buf
restore (a, c) buf' h = Editor (TB.withCursor c buf') a h {historyOpen = False}
replayed (StoredEdit at removed inserted) = TextEdit at (TS.toText removed) (TS.toText inserted)
singleLine = (if modeMultiLine mode then id else T.filter (/= '\n')) . TB.insertableText
replaceSelection kind txt = edit kind (TB.replaceEdit txt anchor cursor buf)
-- An edit that changes nothing records no step, but typing over a
-- selection with the same text still leaves the caret after it.
edit kind e
| editRemoved e == editInserted e =
if T.null (editInserted e)
then ed
else let end = TB.getCursor (TB.applyEdit e buf) in Editor (TB.withCursor end buf) end hist
| otherwise =
let buf' = TB.applyEdit e buf
end = TB.getCursor buf'
in Editor buf' end (record kind (anchor, cursor) e (end, end) hist)
motionTarget = \case
-- Deleting to the end of a line from its end takes the line break, so
-- Ctrl+K keeps making progress.
LineEnd | T.length (TB.lineAt (cursorRow cursor) buf) == cursorCol cursor -> TB.getCursor (TB.moveRight buf)
-- Backspace takes a combining mark off the letter it sits on, as text
-- fields do, so a mistyped vowel sign or accent costs only itself. A
-- variation selector or an emoji keycap still goes with its character.
CharLeft
| Just (_, c) <- T.unsnoc (T.take (cursorCol cursor) (TB.lineAt (cursorRow cursor) buf))
, isMark c && c /= '\x20E3' && not (c >= '\xFE00' && c <= '\xFE0F') && not (c >= '\xE0100' && c <= '\xE01EF') ->
cursor {cursorCol = cursorCol cursor - 1}
motion -> TB.getCursor (moveBuffer motion)
moveBuffer = \case
CharLeft -> TB.moveLeft buf
CharRight -> TB.moveRight buf
WordLeft -> TB.moveWordLeft buf
WordRight -> TB.moveWordRight buf
LineStart -> TB.moveToBOL buf
LineEnd -> TB.moveToEOL buf
LineUp -> if modeMultiLine mode then TB.moveUp buf else buf
LineDown -> if modeMultiLine mode then TB.moveDown buf else buf
DocumentStart -> TB.moveToTop buf
DocumentEnd -> TB.moveToBottom buf
-- | 'runCommand', with the clipboard commands going through the context's
-- clipboard.
runCommandIO :: Context -> EditorMode -> TextCommand -> Editor -> IO Editor
runCommandIO ctx mode cmd ed =
case cmd of
Copy -> ed <$ copySelection
Cut
| modeEditable mode && modeCopyable mode
, hasSelection ed || not (modeMultiLine mode) -> do
copySelection
pure (runCommand mode (Delete CharRight) (if hasSelection ed then ed else runCommand mode SelectAll ed))
Paste
| modeEditable mode ->
maybe ed (\txt -> runCommand mode (InsertText txt) ed) <$> ctxClipboardGet ctx
_ -> pure (runCommand mode cmd ed)
where
-- Copy without a selection takes the whole field.
copySelection = when (modeCopyable mode) $ do
let (a, c) = editorSelection ed
buf = editorBuffer ed
txt = if a /= c then TB.selectedText a c buf else TB.toText buf
unless (T.null txt) $ void (ctxClipboardSet ctx txt)
-- | The command a key runs, following iced's bindings. 'modJump' (Option on
-- macOS, Ctrl elsewhere) makes motions and deletions work by word, and
-- Home/End in a multi-line field go to the document's ends. Command on
-- macOS, or Ctrl+Shift with Backspace/Delete elsewhere, goes to the line's
-- ends. Shift extends the selection. With 'modPrimary': A select all, C/X/V
-- copy/cut/paste, Z undo, Shift+Z or Y redo. On macOS, Ctrl alone gives the
-- Emacs keys: A/E line start/end, B/F move, H/D delete, K/U delete to line
-- end/start.
keyCommand :: EditorMode -> Modifiers -> Key -> Maybe TextCommand
keyCommand mode mods key =
case key of
KeyBackspace -> Just (Delete (widen LineStart WordLeft CharLeft))
KeyDelete -> Just (Delete (widen LineEnd WordRight CharRight))
KeyLeft -> move (reach LineStart WordLeft CharLeft)
KeyRight -> move (reach LineEnd WordRight CharRight)
KeyHome -> move (if jump && multi then DocumentStart else LineStart)
KeyEnd -> move (if jump && multi then DocumentEnd else LineEnd)
-- Leave Ctrl/Alt with Enter or a vertical arrow to shortcuts.
KeyUp | multi && not chorded -> move LineUp
KeyDown | multi && not chorded -> move LineDown
KeyEnter | multi && not chorded -> Just (InsertText "\n")
KeyChar c
| onMac && mods == noModifiers {modCtrl = True} -> emacsCommand c
| chordModifiers mods -> chordCommand mods c
_ -> Nothing
where
multi = modeMultiLine mode
jump = modJump mods
chorded = modCtrl mods || modAlt mods || modSuper mods
-- Extent of an arrow or deletion; 'widen' adds Ctrl+Shift deletions to
-- the line's ends off macOS.
reach line word char
| modMacCommand mods = line
| jump = word
| otherwise = char
widen line word char
| modPrimary mods && modShift mods = line
| otherwise = reach line word char
move m = Just (Move m (modShift mods))
-- | This frame's typing and keys as commands, typed characters first.
-- Characters typed under modifiers that make their key a command
-- ('isCommandKey': Ctrl, or Alt alone, outside macOS) are dropped, since
-- those keystrokes arrive as key commands or go to shortcuts. Ctrl+Alt is
-- AltGr on many layouts, and Option types on macOS, so their characters are
-- typed normally. X11 and Wayland report AltGr as Alt alone, so Alt alone
-- drops only its key's own character: the @f@ of Alt+F, but not the \@ of
-- AltGr+Q on a German layout.
inputTextCommands :: EditorMode -> Input -> [TextCommand]
inputTextCommands mode inp =
let typed = T.filter keepChar (inputChars inp)
in [InsertText typed | not (T.null typed)] ++ keys
where
mods = inputModifiers inp
keepChar c =
not (isControl c) && not (isCommandKey mods (KeyChar c) && (modCtrl mods || modSuper mods || ownKey c))
-- The key's press can end the frame before its text, so the key is
-- looked for among those held or released.
ownKey c = any (inputKeysElem (KeyChar (toLower c))) [inputKeysHeld inp, inputKeysReleased inp]
keys = foldr (\k rest -> maybe rest (: rest) (keyCommand mode mods k)) [] (inputKeys inp)
chordCommand :: Modifiers -> Char -> Maybe TextCommand
chordCommand mods c =
case toLower c of
'a' -> Just SelectAll
'c' -> Just Copy
'x' -> Just Cut
'v' -> Just Paste
'z' | modShift mods -> Just Redo
'z' -> Just Undo
'y' -> Just Redo
_ -> Nothing
-- | Emacs-style Ctrl bindings, used on macOS.
emacsCommand :: Char -> Maybe TextCommand
emacsCommand = \case
'a' -> Just (Move LineStart False)
'e' -> Just (Move LineEnd False)
'b' -> Just (Move CharLeft False)
'f' -> Just (Move CharRight False)
'h' -> Just (Delete CharLeft)
'd' -> Just (Delete CharRight)
'k' -> Just (Delete LineEnd)
'u' -> Just (Delete LineStart)
_ -> Nothing