Skip to content

Instantly share code, notes, and snippets.

@tangentstorm
Last active May 10, 2024 14:22
Show Gist options
  • Save tangentstorm/cfe595e3650615dcdee4a6c9542bca88 to your computer and use it in GitHub Desktop.
Save tangentstorm/cfe595e3650615dcdee4a6c9542bca88 to your computer and use it in GitHub Desktop.
A tiny editor in J
NB. Core logic for a tiny editor in J.
NB. No select/copy/paste (in this gist), but it does support multiple cursors.
NB. This started as the code for editing a single line of text, but I'm now
NB. using three copies simultaneously: one for a single token, one for
NB. boxed tokens on a line, and one for boxed lines in a buffer.
coclass 'ed'
init =: {{
B =: '' NB. the buffer to edit.
C =: 0 NB. cursor position(s)
W =: 64 NB. width/max length
E =: ' ' NB. empty element (temp used when appending a value at the end)
R =: 1 NB. redraw flag
}}
NB. `ed =: buf conew 'ed'` winds up calling `create buf`
NB. buf is often '' to edit a string) or (0$a:) (for boxes)
NB. `{.@(0&$)` gives a default value for any type.
create =: {{ E=: {.@(0&$) B=:y [ init'' }}
NB. buffer editing commands: (insert, backspace, delete, go to end of line, go beginning, swap)
ins =: {{ R=:1[ B=:(C+&#B) {. y (<:C=:>:(+i.@#)C) } (1+C e.~ i.#b)#b=.B,E }}"0
bsp =: {{ R=:1[ C=:C-1+i.#C[B=:}:b#~-.1|.C e.~i.#b=.B,E }}
del =: {{ R=:1[ C=:C-i.#C[B=:}:b#~-.C e.~i.#b=.B,E}}
eol =: {{ R=:1[ C=:C+(#B)->./C }}
bol =: {{ R=:1[ C=:C-<./C }}
swp =: {{ R=:1[ B=: a (C-1) } b (C-2) } B [ a=. (C-2) { B [ b=. (C-1) { B }}
NB. (add your own key bindings and rendering routine...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment