Writing a text editor in prolog

So, just for funs and learning, I started following a build your own text editor tutorial using swi prolog… And I must say that I am really enjoying this !

So I was wondering if anyone has ever attempted to write a command line program in prolog ?

Here are some random notes about my experience:

  • the tutorial spends a lot of time putting the terminal in raw mode. Well, in swi-prolog, there is a predicate for that :slight_smile: with_tty_raw/1. Same with getting the size of the terminal window tty_size/2.
  • almost all of my predicates are actually DCGs: a dcg to parse input keys from the user (things like escape sequences), a dcg to render the buffer to the screen
  • I use the new library macros to compile deterministic dcg goal. For example, I use macros to insert escape sequences by expanding the corresponding dcg goal.
  • I use the library settings to store my editor settings and … global state :slight_smile: This has the interesting side effet that when restarting the editor, I get back to the exact same state as before ^^

As a life long vimmer, I think I had my own little Emacs moment when I realized I could modify the code of the editor in my new editor and then bind a key to the predicate prolog/0 to get back to a prolog top level. Then, I can call make/0 to compile the code of the editor. When quitting the top level, the changes of the editor code is automatically picked up by the running editor instance !

Lastly, I store the whole buffer in a list of lines, each line being a list of codes… Working with list means that I can easily use nth1/3 and nth1/4 to index and modify the buffer. However, I have no idea if this strategy will scale for anything more than very small files.
Does anyone know of a datastructure more suitable for this use case ?

If anyone wants to see the very ugly code I wrote: kilogic

8 Likes