bootstrapping a text editor from cat with Lua

Kragen Javier Sitaker kragen at canonical.org
Thu Jun 2 01:34:35 EDT 2011


I thought it would be fun to try a text-editor bootstrapping exercise:
starting by writing a very simple text editor with cat, and gradually
making it more featureful, using the text editor to write itself.
After 45 minutes, this is what I ended up with, but the process
(recorded in the attached tar file) is probably slightly less boring
than the code, which is below.  Another 45 minutes would probably result
in an editor I would prefer over Notepad.  (Hmm, that bar is low enough
I might be tempted to try it...)

Starting with modern programming languages and fast machines make this
considerably less work than the MS-DOS screen editor for machine code
from a couple of months ago.

#!/usr/bin/lua

local filename = ...
assert(filename)
local infile = assert(io.open(filename, "r"))
local contents = infile:read("*all")

while 1 do 
  print(contents)
  io.stdout:write("> ")
  local command = io.stdin:read("*line")
  command = string.gsub(command, "\\n", "\n")
  command = string.gsub(command, "\\\\", "\\")
  local delimiter = string.sub(command, 1, 1)
  if delimiter == "." then
    break
  else
    local other_delimiter = string.find(command, delimiter, 2)
    local pattern = string.sub(command, 2, other_delimiter - 1)
    local substitute = string.sub(command, other_delimiter + 1)
    contents = string.gsub(contents, pattern, substitute, 1)
  end
end

local outfile = assert(io.open("outfile", "w"))
outfile:write(contents)
outfile:close()


-------------- next part --------------
A non-text attachment was scrubbed...
Name: bootedit.tar.gz
Type: application/octet-stream
Size: 5288 bytes
Desc: not available
Url : http://lists.canonical.org/pipermail/kragen-discuss/attachments/20110602/221a8af0/bootedit.tar.obj


More information about the Kragen-discuss mailing list