-- Text editor: plain text and rich text (RTF) documents, several open at
-- once as tabs. Plain text keeps its line ends and byte order mark; a
-- file that isn't UTF-8 is read as Windows-1252 and saved as UTF-8.
-- Rich text is c8.text's rich mode, read and written by rtf.lua beside
-- this file: fonts, sizes, colours, bold, italic, underline, strike.
-- Plain text can be previewed as Markdown (md.lua) beside it, or in its
-- place when the window is narrow.
local c8 = require "c8"
local rtf = require "rtf"
local md = require "md"
local ID = "org.cont8nuum.TextEditor"
local NAME = "Text editor"
-- What a rich document's text is in unless it says otherwise
local FAMILY = "Selawik"
local SIZE = 11 -- points
local SIZES = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 28, 36, 48, 72 }
local COLORS = {
{ "Automatic" }, { "Black", 0x000000 }, { "Grey", 0x7a7a7a },
{ "Dark red", 0x9b1c1c }, { "Red", 0xe51400 }, { "Orange", 0xf09609 },
{ "Gold", 0xc39b00 }, { "Green", 0x339933 }, { "Teal", 0x00aba9 },
{ "Blue", 0x1ba1e2 }, { "Dark blue", 0x0050ef },
{ "Purple", 0xa200ff }, { "Magenta", 0xd80073 },
}
local settings = c8.load("text-editor") or {}
local function setting(key, default)
if settings[key] == nil then
return default
end
return settings[key]
end
local win, bar, preview_cmd
local tabs, tab_scroll, pages, status, mode_holder
local toolbar, font_combo, size_combo, bold, italic, underline, strike
local color_button
local findbar, find_entry, replace_row, replace_entry, match_case
local docs, current = {}, nil
local families = { FAMILY }
local next_id, narrow = 1, false
local message, message_timer
local function basename(path)
return path:match("([^/]+)$") or path
end
local function px(points)
return points * 96 / 72
end
local function uri_to_path(uri)
if uri:sub(1, 1) == "/" then
return uri
end
local path = uri:match("^file://[^/]*(/.*)$")
if not path then
return nil
end
return (path:gsub("%%(%x%x)", function(h)
return string.char(tonumber(h, 16))
end))
end
local function is_markdown(name)
local ext = name:lower():match("%.(%w+)$")
return ext == "md" or ext == "markdown" or ext == "mdown" or ext == "mkd"
end
-- Changed since it was saved: typed in, or turned into another kind
-- (which c8.text's modified doesn't hear)
local function unsaved(doc)
return doc.dirty or doc.view:modified()
end
local function title_of(doc)
return (unsaved(doc) and "• " or "") .. doc.name
end
-- Status and title
-- What kind of document: plain text, plain text with its Markdown
-- preview, or rich text
local function mode_of(doc)
return doc.rich and "rich" or doc.preview and "markdown" or "plain"
end
local MODES = { "plain", "markdown", "rich" }
local MODE_NAMES = { plain = "Plain text", markdown = "Markdown",
rich = "Rich text (RTF)" }
local mode_shown
local set_mode
-- The status bar's link that says what kind it is and changes it: a
-- link's label can't change, so a new one each time
local function show_mode()
local m = mode_of(current)
if m == mode_shown or not mode_holder then
return
end
mode_shown = m
mode_holder:clear()
local link
link = c8.link { label = MODE_NAMES[m] .. " â–¾",
tooltip = "Change what kind of document this is",
on_click = function()
local now = current and mode_of(current)
local items = {}
for i, k in ipairs(MODES) do
items[i] = { MODE_NAMES[k], radio = true, checked = k == now,
shortcut = k == "markdown" and "Ctrl+E" or nil }
end
win:menu { at = link, above = true, items = items,
done = function(i)
if i and current then
set_mode(current, MODES[i])
end
end }
end }
mode_holder:add(link)
end
local function show_status()
if not current then
return
end
local line, col = current.view:position()
show_mode()
local parts = { string.format("Ln %d, Col %d", line or 1, col or 1) }
if not current.rich then
parts[#parts + 1] = current.cp1252 and "Windows-1252, saved as UTF-8"
or "UTF-8"
if current.crlf then
parts[#parts + 1] = "Windows line ends"
end
end
if message then
parts[#parts + 1] = message
end
status:set(table.concat(parts, " · "))
end
local function say(text)
message = text
if message_timer then
message_timer:cancel()
end
message_timer = c8.after(5, function()
message, message_timer = nil, nil
show_status()
end)
show_status()
end
local function show_title()
if win and win.open and current then
win:set_title(title_of(current) .. " – " .. NAME)
end
end
-- Tabs, drawn on a canvas that scrolls sideways when they don't fit
local TAB_H = 40
local PLUS_W = 48
local tab_ox, tab_oy = 0, 0
local function tab_width()
return narrow and 150 or 200
end
local function size_tabs()
tabs.width = #docs * tab_width() + PLUS_W
tabs:redraw()
end
local function draw_tabs(g, x, y, w, h)
tab_ox, tab_oy = x, y
local tw = tab_width()
for i, d in ipairs(docs) do
local tx = x + (i - 1) * tw
local on = d == current
if on then
g:rect(tx, y, tw - 2, h, g.accent)
else
g:rect(tx, y, tw - 2, h, g.fg, 0.06)
end
local fg = on and 0xffffff or g.fg
g:text(title_of(d), tx + 12, y + 10,
{ width = tw - 48, lines = 1, color = fg })
g:text("✕", tx + tw - 30, y + 10, { color = fg, alpha = 0.8 })
end
g:text("+", x + #docs * tw + 16, y + 6, { size = 22 })
end
local switch, close_doc, new_doc, open_path
local function tab_event(_, ev)
if ev.type ~= "press" then
return false
end
local lx = ev.x - tab_ox
local tw = tab_width()
local i = math.floor(lx / tw) + 1
if i > #docs then
if lx < #docs * tw + PLUS_W then
new_doc(false)
end
return true
end
local d = docs[i]
if ev.button == "other" or lx - (i - 1) * tw > tw - 40 then
close_doc(d)
elseif ev.button == "right" then
win:menu { x = ev.x, y = ev.y, items = { "Close", "Close the others" },
done = function(choice)
if choice == 1 then
close_doc(d)
elseif choice == 2 then
local others = {}
for _, o in ipairs(docs) do
if o ~= d then
others[#others + 1] = o
end
end
local function step(k)
if others[k] then
close_doc(others[k], function() step(k + 1) end)
end
end
step(1)
end
end }
else
switch(d)
end
return true
end
-- The formatting bar, for rich documents
local function index_of(list, value)
for i, v in ipairs(list) do
if v == value then
return i
end
end
end
local function show_toolbar()
local rich = current and current.rich
toolbar.hidden = not rich
if not rich then
return
end
local f = current.view:format()
local family = f.family or FAMILY
if not index_of(families, family) then
families[#families + 1] = family
table.sort(families)
font_combo:items(families)
end
font_combo:set(index_of(families, family))
size_combo:set(index_of(SIZES, f.size or SIZE) or 0)
bold:set(f.bold or false)
italic:set(f.italic or false)
underline:set(f.underline or false)
strike:set(f.strike or false)
end
local function apply(fmt)
if current and current.rich then
current.view:format(fmt)
current.view:focus()
show_toolbar()
end
end
local function flip(name)
if current and current.rich then
local f = current.view:format()
apply { [name] = not f[name] }
end
end
local function color_menu()
local items = {}
for i, c in ipairs(COLORS) do
items[i] = c[1]
end
win:menu { at = color_button, items = items, done = function(i)
if i then
apply { color = COLORS[i][2] or false }
end
end }
end
-- Fonts the system has, for the font list (fontconfig's own tool)
local function load_families()
c8.run({ "fc-list", ":", "family" }, function(code, out)
if code ~= 0 or not out then
return
end
local seen = {}
for _, f in ipairs(families) do
seen[f] = true
end
for line in out:gmatch("[^\n]+") do
local name = line:match("^([^,]+)")
if name and not seen[name] and not name:match("^%.") then
seen[name] = true
families[#families + 1] = name
end
end
table.sort(families)
font_combo:items(families)
show_toolbar()
end)
end
-- Documents
local function font_for(doc)
-- Plain text is always monospace: columns line up, as code and
-- logs need
if doc.rich then
doc.view:font(FAMILY, px(SIZE))
else
doc.view:font("monospace", px(setting("size", 11)))
end
end
-- The Markdown preview
-- Which panes show: both side by side, or narrow one at a time (the
-- preview, while it's on)
local function show_panes(doc)
if doc.rich then
return
end
local on = doc.preview or false
doc.editor.hidden = on and narrow
doc.divider.hidden = not on or narrow
doc.preview_scroll.hidden = not on
end
-- Files a link opens here rather than in another app
local TEXT_FILES = { md = true, markdown = true, mdown = true, mkd = true,
txt = true, rtf = true, log = true, csv = true, ini = true, conf = true,
json = true, xml = true }
local function folder_of(doc)
return doc.path and doc.path:match("^(.*)/[^/]*$")
end
local function file_uri(path)
return "file://" .. path:gsub("[^%w/._~%-]", function(c)
return string.format("%%%02X", c:byte())
end)
end
-- A link in the preview: a heading in it, a file beside the document,
-- or anything else in its own app (the browser, mail)
local function follow(doc, uri)
if uri:sub(1, 1) == "#" then
local target = doc.anchors and doc.anchors[uri:sub(2):lower()]
if target then
local _, ty = target:rect()
local _, top = doc.preview_box:rect()
doc.preview_scroll:scroll_to(math.max(0, ty - top - 12))
else
say("There's no heading " .. uri)
end
return
end
if uri:match("^%a[%w+.%-]*:") and not uri:match("^file:") then
win:open_uri(uri)
return
end
local path = uri:gsub("^file://[^/]*", ""):gsub("[?#].*$", "")
:gsub("%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
if path:sub(1, 1) ~= "/" then
local folder = folder_of(doc)
if not folder then
win:message("Couldn't open " .. uri, "It's beside this document, "
.. "which hasn't been saved anywhere yet.")
return
end
path = folder .. "/" .. path
end
local f = io.open(path, "rb")
if not f then
win:message("Couldn't open " .. uri, "There's no such file.")
return
end
-- A folder opens too, but reading it fails (an empty file gives "")
local is_file = f:read(0) ~= nil or f:read("a") ~= nil
f:close()
local ext = basename(path):lower():match("%.(%w+)$")
if is_file and (ext == nil or TEXT_FILES[ext]) then
open_path(path)
else
win:open_uri(file_uri(path))
end
end
local function render(doc)
doc.render_timer = nil
if doc.rich or not doc.preview or not doc.preview_box.alive then
return
end
local _, top = doc.preview_scroll:offset()
doc.preview_box:clear()
doc.anchors = md.build(doc.preview_box, md.parse(doc.view:get()), {
c8 = c8, colors = doc.preview_box:colors(), family = FAMILY,
base = folder_of(doc),
on_link = function(uri) follow(doc, uri) end })
-- Where the reader was, once the new page has its height
if top and top > 0 then
c8.after(0, function()
doc.preview_scroll:scroll_to(top)
end)
end
end
-- Typing redraws it after a pause, not on every key
local function render_soon(doc, delay)
if doc.rich or not doc.preview then
return
end
if doc.render_timer then
doc.render_timer:cancel()
end
doc.render_timer = c8.after(delay or 0.3, function() render(doc) end)
end
local function show_preview_cmd()
if preview_cmd then
preview_cmd.hidden = not current or current.rich
preview_cmd:set(current and current.preview or false)
end
end
local function set_preview(doc, on)
if doc.rich then
return
end
doc.preview = on
show_panes(doc)
if on then
render_soon(doc, 0)
else
if doc.render_timer then
doc.render_timer:cancel()
doc.render_timer = nil
end
doc.preview_box:clear()
doc.view:focus()
end
if doc == current then
show_preview_cmd()
end
end
local function changed(doc)
render_soon(doc)
if doc == current then
show_status()
show_title()
show_toolbar()
end
tabs:redraw()
end
local function make_page(doc)
doc.view = c8.text { editable = true, wrap = setting("wrap", true),
rich = doc.rich, fill = true, expand = true,
on_change = function() changed(doc) end,
on_move = function()
if doc == current then
show_status()
show_toolbar()
end
end }
font_for(doc)
local paper = c8.column { fill = true, expand = true, doc.view }
if doc.rich then
-- A rich document is a white page, whatever the scheme: its
-- colours were chosen on white
paper:padding(48, 32, 48, 32)
paper:narrow_padding(16, 16, 16, 16)
doc.page = c8.scroll { expand = true, fill = true, hidden = true,
scheme = "light", background = 0xffffff, paper }
else
paper:padding(24, 12, 24, 12)
paper:narrow_padding(12, 8, 12, 8)
doc.editor = c8.scroll { expand = true, fill = true, paper }
doc.preview_box = c8.column { fill = true, spacing = 14,
padding = { 32, 20, 32, 32 }, narrow_padding = { 12, 8, 12, 16 } }
doc.preview_scroll = c8.scroll { expand = true, fill = true,
hidden = true, doc.preview_box }
doc.divider = c8.separator { vertical = true, fill = true,
hidden = true }
doc.page = c8.row { expand = true, fill = true, hidden = true,
doc.editor, doc.divider, doc.preview_scroll }
end
pages:add(doc.page)
if doc.preview then
show_panes(doc)
render_soon(doc, 0)
end
end
-- Fills a document's view from what was read
local function fill(doc, content)
if doc.rich then
doc.view:set("")
for _, run in ipairs(content) do
doc.view:append(run.text, run)
end
else
doc.view:set(content)
end
doc.view:modified(false)
doc.view:select(1, 0)
end
-- A document turned rich or plain keeps its text (not its undo)
local function remake(doc, rich)
local text = doc.view:get()
local old = doc.page
doc.rich = rich
if rich then
doc.preview = false
end
make_page(doc)
if rich then
fill(doc, { { text = text } })
else
fill(doc, text)
end
old:destroy()
if doc == current then
doc.page.hidden = false
doc.view:focus()
show_toolbar()
show_status()
show_preview_cmd()
end
end
-- Turns a document into another kind; it keeps its text
function set_mode(doc, m)
if mode_of(doc) == m then
return
end
local function done()
doc.dirty = true
changed(doc)
end
if m == "rich" then
set_preview(doc, false)
remake(doc, true)
done()
elseif doc.rich then
win:dialog { title = "Turn this into plain text?",
message = "Plain text keeps no formatting: the fonts, sizes, "
.. "colours, bold and italics will be gone.",
buttons = { "Turn into plain text", "Cancel" },
done = function(choice)
if choice == 1 then
remake(doc, false)
set_preview(doc, m == "markdown")
done()
end
end }
else
-- Only the preview: the file is the same
set_preview(doc, m == "markdown")
show_status()
end
end
local function tile(doc)
local text = doc.view:get():gsub("%s+", " ")
c8.tile.update(ID, { template = "text", heading = doc.name,
text1 = text:sub(1, 200) })
end
function switch(doc)
current = doc
for _, d in ipairs(docs) do
d.page.hidden = d ~= doc
end
show_title()
show_toolbar()
show_status()
show_preview_cmd()
size_tabs()
-- The tab in sight, with one before it where there is one
local tw = tab_width()
local left = ((index_of(docs, doc) or 1) - 1) * tw
local ox = tab_scroll:offset() or 0
if left < ox or left + tw > ox + (win.width or 900) then
tab_scroll:scroll_to_x(math.max(0, left - tw))
end
doc.view:focus()
end
local untitled = 0
function new_doc(rich)
untitled = untitled + 1
local doc = { id = next_id, rich = rich,
name = untitled == 1 and "Untitled" or ("Untitled " .. untitled) }
next_id = next_id + 1
make_page(doc)
docs[#docs + 1] = doc
switch(doc)
return doc
end
-- An untitled document nobody has typed in yet, which a file opened
-- takes the place of
local function blank(doc)
return doc and not doc.path and doc.view:get() == "" and
not unsaved(doc)
end
local function read(path)
local f, err = io.open(path, "rb")
if not f then
return nil, err
end
local data = f:read("a")
f:close()
if not data then
return nil, "It couldn't be read."
end
if data:match("^%s*{\\rtf") then
local runs, why = rtf.read(data)
if not runs then
return nil, why
end
return { rich = true, content = runs }
end
if data:find("\0", 1, true) then
return nil, "It isn't text: it looks like a program or a picture."
end
local doc = { rich = false }
if data:sub(1, 3) == "\239\187\191" then
doc.bom = true
data = data:sub(4)
end
if not utf8.len(data) then
doc.cp1252 = true
data = rtf.decode_1252(data)
end
if data:find("\r\n", 1, true) then
doc.crlf = true
data = data:gsub("\r\n", "\n")
end
doc.content = data
return doc
end
function open_path(path)
for _, d in ipairs(docs) do
if d.path == path then
switch(d)
return
end
end
local got, why = read(path)
if not got then
win:message("Couldn't open " .. basename(path), why or "")
return
end
local replace = blank(current) and current
local doc = { id = next_id, path = path, name = basename(path),
rich = got.rich, crlf = got.crlf, bom = got.bom, cp1252 = got.cp1252 }
doc.preview = not got.rich and is_markdown(path) and
setting("preview", true)
next_id = next_id + 1
make_page(doc)
fill(doc, got.content)
docs[#docs + 1] = doc
if replace then
table.remove(docs, index_of(docs, replace))
replace.page:destroy()
end
switch(doc)
tile(doc)
end
local function open_uri(uri)
local path = uri_to_path(uri)
if not path then
win:message("Couldn't open that", "Only files on this PC can be "
.. "opened here, not " .. uri)
return
end
open_path(path)
end
local function pick_open()
win:open_file { title = "Open", multiple = true, filters = {
{ name = "Text documents", patterns =
"*.txt;*.rtf;*.md;*.markdown;*.log;*.csv;*.ini;*.conf;*.json;*.xml" },
{ name = "Markdown", patterns = "*.md;*.markdown" },
{ name = "Rich text (RTF)", patterns = "*.rtf" },
{ name = "All files", patterns = "*" },
},
done = function(uris)
for _, uri in ipairs(uris or {}) do
open_uri(uri)
end
end }
end
-- Saving
local function encode(doc)
if doc.rich then
return rtf.write(doc.view:runs(), FAMILY, SIZE)
end
local data = doc.view:get()
if doc.crlf then
data = data:gsub("\n", "\r\n")
end
if doc.bom then
data = "\239\187\191" .. data
end
return data
end
local function write(doc, path)
local f, err = io.open(path, "wb")
if not f then
return false, err
end
local ok, werr = f:write(encode(doc))
local closed, cerr = f:close()
if not ok or not closed then
return false, werr or cerr
end
return true
end
local save_as
local function save_to(doc, path, done)
done = done or function() end
local want_rich = path:lower():match("%.rtf$") ~= nil
local function go()
local ok, err = write(doc, path)
if not ok then
win:message("Couldn't save " .. basename(path), err or "")
done(false)
return
end
doc.path, doc.name = path, basename(path)
doc.cp1252 = nil
doc.dirty = false
doc.view:modified(false)
changed(doc)
say("Saved")
tile(doc)
done(true)
end
if doc.rich and not want_rich then
win:dialog { title = "Save as plain text?",
message = "Plain text keeps no formatting: the fonts, sizes, "
.. "colours, bold and italics will be gone.",
buttons = { "Save as plain text", "Cancel" },
done = function(choice)
if choice == 1 then
remake(doc, false)
go()
else
done(false)
end
end }
elseif want_rich and not doc.rich then
remake(doc, true)
go()
else
go()
end
end
-- Whether a file's name suits the document's kind
local function fits(doc, path)
return doc.rich == (path:lower():match("%.rtf$") ~= nil)
end
function save_as(doc, done)
local plain = { name = "Plain text", patterns = "*.txt" }
local markdown = { name = "Markdown", patterns = "*.md" }
local rich = { name = "Rich text (RTF)", patterns = "*.rtf" }
local ending = doc.rich and ".rtf" or doc.preview and ".md" or ".txt"
local name = doc.path and basename(doc.path) or (doc.name .. ending)
if doc.path and not fits(doc, doc.path) then
-- Turned into the other kind: the same name, the new ending
name = name:gsub("%.[^.]*$", "") .. ending
end
local started = win:save_file { title = "Save as", name = name,
filters = doc.rich and { rich, plain, markdown } or doc.preview and
{ markdown, plain, rich } or { plain, markdown, rich },
done = function(uris)
local path = uris and uris[1] and uri_to_path(uris[1])
if path then
save_to(doc, path, done)
elseif done then
done(false)
end
end }
if not started then
win:message("Couldn't save", "There's no file picker to choose "
.. "where: xdg-desktop-portal isn't running.")
end
end
local function save(doc, done)
-- A .txt turned rich (or an .rtf turned plain) isn't written over
if doc.path and fits(doc, doc.path) then
save_to(doc, doc.path, done)
else
save_as(doc, done)
end
end
-- Asks about unsaved changes; go(true) when the document can go
local function ask_save(doc, go)
if not unsaved(doc) then
go(true)
return
end
switch(doc)
win:dialog { title = "Save changes to " .. doc.name .. "?",
buttons = { "Save", "Don't save", "Cancel" },
done = function(choice)
if choice == 1 then
save(doc, function(ok)
if ok then
go(true)
end
end)
elseif choice == 2 then
go(true)
end
end }
end
function close_doc(doc, after)
ask_save(doc, function()
local i = index_of(docs, doc)
if not i then
return
end
table.remove(docs, i)
doc.page:destroy()
if #docs == 0 then
untitled = 0
new_doc(false)
elseif doc == current then
switch(docs[math.min(i, #docs)])
else
size_tabs()
end
if after then
after()
end
end)
end
-- Asked one at a time, then the window closes
local function close_all()
for _, d in ipairs(docs) do
if unsaved(d) then
ask_save(d, function()
d.view:modified(false)
d.dirty = false
close_all()
end)
return
end
end
win:close()
end
-- Find and replace
local function show_find(with_replace)
if current and current.preview and narrow then
set_preview(current, false)
end
findbar.hidden = false
replace_row.hidden = not with_replace
if current then
-- What's selected is what to look for
local a, b = current.view:selection()
if b >= a and b - a < 200 then
local picked = current.view:get():sub(a, b)
if not picked:find("\n", 1, true) then
find_entry:set(picked)
end
end
end
find_entry:focus()
end
local function hide_find()
findbar.hidden = true
if current then
current.view:focus()
end
end
local function find_next(backwards)
local needle = find_entry:get()
if not current or needle == "" then
return
end
if not current.view:find(needle, backwards, match_case:get()) then
say("Can't find \"" .. needle .. "\"")
end
end
local function selected_matches(needle)
local a, b = current.view:selection()
local picked = current.view:get():sub(a, b)
if match_case:get() then
return picked == needle
end
return picked:lower() == needle:lower()
end
local function replace_one()
local needle = find_entry:get()
if not current or needle == "" then
return
end
if selected_matches(needle) then
current.view:insert(replace_entry:get())
end
find_next(false)
end
local function replace_all()
local needle = find_entry:get()
if not current or needle == "" then
return
end
local n = current.view:replace_all(needle, replace_entry:get(),
match_case:get())
say(n == 0 and ("Can't find \"" .. needle .. "\"") or
n == 1 and "Replaced 1" or ("Replaced " .. n))
end
-- The window
local function build()
tabs = c8.canvas { height = TAB_H, width = 400, draw = draw_tabs,
on_event = tab_event }
tab_scroll = c8.scroll { horizontal = true, vertical = false,
height = TAB_H, fill = true, tabs }
local names = {}
for i, s in ipairs(SIZES) do
names[i] = tostring(s)
end
font_combo = c8.combo { items = families, selected = 1, width = 200,
on_change = function(_, n) apply { family = families[n] } end }
size_combo = c8.combo { items = names, selected = 4, width = 80,
on_change = function(_, n) apply { size = SIZES[n] } end }
local function toggle(label, tip, name)
return c8.toggle_button { label = label, tooltip = tip,
on_change = function(_, on) apply { [name] = on } end }
end
bold = toggle("B", "Bold (Ctrl+B)", "bold")
italic = toggle("I", "Italic (Ctrl+I)", "italic")
underline = toggle("U", "Underline (Ctrl+U)", "underline")
strike = toggle("S", "Strikethrough", "strike")
color_button = c8.button { label = "Colour", on_click = color_menu }
toolbar = c8.row { spacing = 8, wrap = true, padding = { 24, 8, 24, 8 },
narrow_padding = { 12, 6, 12, 6 }, hidden = true,
font_combo, size_combo, bold, italic, underline, strike,
color_button }
-- enter_only: on_enter would also run when Tab leaves the box
find_entry = c8.entry { placeholder = "Find", min_width = 160,
expand = true, enter_only = true,
on_enter = function() find_next(false) end }
replace_entry = c8.entry { placeholder = "Replace with",
min_width = 160, expand = true, enter_only = true,
on_enter = replace_one }
match_case = c8.checkbox { label = "Match case" }
replace_row = c8.row { spacing = 8, wrap = true, replace_entry,
c8.button { label = "Replace", on_click = replace_one },
c8.button { label = "Replace all", on_click = replace_all } }
findbar = c8.column { spacing = 8, hidden = true,
padding = { 24, 8, 24, 8 }, narrow_padding = { 12, 6, 12, 6 },
c8.row { spacing = 8, wrap = true, find_entry,
c8.button { label = "Previous",
on_click = function() find_next(true) end },
c8.button { label = "Next", primary = true,
on_click = function() find_next(false) end },
c8.button { label = "Done", on_click = hide_find } },
replace_row,
match_case }
pages = c8.column { expand = true, fill = true }
status = c8.label { text = "", style = "caption", color = "secondary" }
mode_holder = c8.row {}
return c8.column { fill = true,
tab_scroll, toolbar, findbar, pages,
c8.row { padding = { 24, 4, 24, 6 }, narrow_padding = { 12, 2, 12, 4 },
spacing = 16, wrap = true, mode_holder,
status } }
end
local function make_appbar()
bar = win:appbar()
bar:add { icon = "tab-new", label = "New", on_click = function()
new_doc(false)
end }
bar:add { icon = "document-new", label = "New rich text",
on_click = function() new_doc(true) end }
bar:add { icon = "document-open", label = "Open", on_click = pick_open }
bar:add { icon = "document-save", label = "Save", on_click = function()
if current then
save(current)
end
end }
bar:add { icon = "document-save-as", label = "Save as",
on_click = function()
if current then
save_as(current)
end
end }
-- toggle = false: a command that stays down while the preview shows
preview_cmd = bar:add { icon = "view-reveal", label = "Preview",
right = true, toggle = false, on_click = function()
if current then
set_preview(current, not current.preview)
end
end }
show_preview_cmd()
bar:add { icon = "edit-find", label = "Find", right = true,
on_click = function() show_find(false) end }
bar:add { icon = "edit-find-replace", label = "Replace", right = true,
on_click = function() show_find(true) end }
end
local keys = {
n = function(ev) new_doc(ev.shift) end,
o = pick_open,
s = function(ev)
if current then
if ev.shift then
save_as(current)
else
save(current)
end
end
end,
w = function() if current then close_doc(current) end end,
f = function() show_find(false) end,
h = function() show_find(true) end,
e = function()
if current and not current.rich then
set_preview(current, not current.preview)
end
end,
b = function() flip("bold") end,
i = function() flip("italic") end,
u = function() flip("underline") end,
}
local function step_tab(by)
local i = index_of(docs, current) or 1
switch(docs[(i - 1 + by) % #docs + 1])
end
local function on_key(_, ev)
if ev.ctrl and (ev.key == "Tab" or ev.key == "ISO_Left_Tab") then
step_tab(ev.shift and -1 or 1)
return true
end
if ev.ctrl and not ev.alt then
local fn = keys[ev.key:lower()]
if fn then
fn(ev)
return true
end
return false
end
if ev.key == "Escape" and not findbar.hidden then
hide_find()
return true
elseif ev.key == "F3" then
find_next(ev.shift)
return true
end
return false
end
local function keep()
c8.save("text-editor", settings)
end
c8.app {
id = ID,
open = function(files)
if not (win and win.open) then
win = c8.window { title = NAME, width = 1000, height = 720,
build(),
on_key = on_key,
on_resize = function(_, _, _, now_narrow)
if now_narrow ~= narrow then
narrow = now_narrow
size_tabs()
for _, d in ipairs(docs) do
show_panes(d)
end
end
end,
can_close = function()
for _, d in ipairs(docs) do
if unsaved(d) then
close_all()
return false
end
end
return true
end }
make_appbar()
narrow = win.narrow or false
load_families()
end
for _, uri in ipairs(files or {}) do
open_uri(uri)
end
if #docs == 0 then
new_doc(false)
end
win:present()
end,
search = function(query)
local found, q = {}, query:lower()
if q == "" then
return found
end
for _, d in ipairs(docs) do
local text = d.view:get()
local start, line = 1, 1
while start <= #text do
local stop = text:find("\n", start, true) or #text + 1
local here = text:sub(start, stop - 1)
local at = here:lower():find(q, 1, true)
if at then
found[#found + 1] = { id = d.id .. ":" .. (start + at - 1),
title = here:gsub("^%s+", ""):sub(1, 120),
subtitle = d.name .. ", line " .. line,
icon = "text-x-generic" }
if #found >= 50 then
return found
end
end
start, line = stop + 1, line + 1
end
end
return found
end,
result = function(id, query)
local doc_id, at = id:match("^(%d+):(%d+)$")
for _, d in ipairs(docs) do
if d.id == tonumber(doc_id) then
switch(d)
at = tonumber(at)
d.view:select(at, at + #query - 1)
end
end
end,
settings = {
{ id = "options", label = "Options", build = function(page)
page:toggle { id = "wrap", label = "Word wrap",
on = setting("wrap", true), on_change = function(on)
settings.wrap = on
keep()
for _, d in ipairs(docs) do
d.view:wrap(on)
end
end }
page:heading "Plain text"
page:slider { id = "size", label = "Text size (points)",
min = 8, max = 28, step = 1, value = setting("size", 11),
on_change = function(v)
settings.size = math.floor(v + 0.5)
keep()
for _, d in ipairs(docs) do
font_for(d)
end
end }
page:paragraph("Rich text documents keep the fonts and sizes "
.. "they were written in.")
page:heading "Markdown"
page:toggle { id = "preview", label = "Preview Markdown files "
.. "when they open", on = setting("preview", true),
on_change = function(on)
settings.preview = on
keep()
end }
page:paragraph("Ctrl+E shows or hides the preview of any plain "
.. "text document.")
end },
},
}