aboutsummaryrefslogtreecommitdiff
path: root/lua/muwiki/templates.lua
blob: c8dcd132ddcf9de67564d3ce83ce176e018bd396 (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
local config = require('muwiki.config')
local fs = require('muwiki.fs')

local M = {}

local function process_template(template, title)
  local date_fmt = config.options.date_fmt or '%Y-%m-%d'
  local date = os.date(date_fmt)
  local result = template:gsub('${title}', title):gsub('${date}', date)

  if not result:match('\n$') then
    result = result .. '\n'
  end

  return result
end

function M.init_file(bufnr, filepath)
  if fs.file_exists(filepath) then
    return
  end

  local filename = vim.fs.basename(filepath)

  if config.options.use_template then
    local title = filename:gsub('%.md$', ''):gsub('_', ' ')
    local content = process_template(config.options.template, title)
    local lines = vim.split(content, '\n', { plain = true })
    vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
  end

  vim.notify(string.format('%s (unsaved)', filename), vim.log.levels.INFO)
end

return M