about summary refs log tree commit diff
path: root/.local/bin/rofi-notes
blob: 876bc66c5eaadb0e06a90e7d557895772bafafcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env lua

local HOME   = os.getenv("HOME")
local NOTES  = HOME .. "/Documents/Notes"
local TERM   = "foot -a=floating_foot"
local EDITOR = "nvim"

local MODE   = arg[1] -- nil | "--delete" | "-d"

local function rofi(prompt, lines)
  local cmd = string.format(
    'printf "%s" | rofi -dmenu -i -p "%s"',
    table.concat(lines, "\n"),
    prompt
  )
  local handle = io.popen(cmd)
  local selection = handle:read("*a")
  handle:close()
  selection = selection:gsub("%s+$", "")
  if selection == "" then return nil end
  return selection
end

local function list_notes()
  local display = {}
  local lookup  = {}

  local cmd     = string.format('find "%s" -type f', NOTES)
  local pipe    = assert(io.popen(cmd, "r"))

  for fullPath in pipe:lines() do
    local relPath  = fullPath:gsub("^" .. NOTES .. "/", "")
    local noteName = relPath:gsub("%.[^./]*$", "")

    table.insert(display, noteName)
    lookup[noteName] = fullPath
  end

  pipe:close()
  return display, lookup
end

local function normalize_path(input)
  input = input:gsub("^/", "")
  if not input:match("%.md$") then
    input = input .. ".md"
  end
  return NOTES .. "/" .. input
end

local function ensure_parent_dir(path)
  local dir = path:match("(.+)/[^/]+$")
  if dir then
    os.execute(string.format('mkdir -p "%s"', dir))
  end
end

local function open_in_nvim(path)
  local cmd = string.format(
    '%s -e %s "%s"',
    TERM,
    EDITOR,
    path
  )
  os.execute(cmd)
end

local function delete_note(path, name)
  local confirm = rofi("Delete " .. name .. "?", { "No", "Yes" })
  if confirm == "Yes" then
    os.execute(string.format('rm -- "%s"', path))
  end
end

-- ---- main ----

local notes, paths = list_notes()

if MODE == "--delete" or MODE == "-d" then
  local choice = rofi(" ", notes)
  if not choice then os.exit(0) end

  local path = paths[choice]
  if path then
    delete_note(path, choice)
  end

  os.exit(0)
end

-- default: open / create
local choice = rofi(" ", notes)
if not choice then os.exit(0) end

local path = paths[choice]
if not path then
  path = normalize_path(choice)
  ensure_parent_dir(path)
end

open_in_nvim(path)