local api = vim.api
local autocmd = api.nvim_create_autocmd
local augroup = api.nvim_create_augroup
local opt = vim.opt
local o = vim.o
local g = vim.g
local fn = vim.fn

autocmd("BufWritePre", {
  desc = "Autocreate a dir when saving a file",
  group = augroup("auto_create_dir", { clear = true }),
  callback = function(event)
    if event.match:match("^%w%w+:[\\/][\\/]") then
      return
    end
    local file = vim.uv.fs_realpath(event.match) or event.match
    fn.mkdir(fn.fnamemodify(file, ":p:h"), "p")
  end,
})

autocmd("BufReadPost", {
  desc = "Auto jump to last position",
  group = augroup("auto-last-position", { clear = true }),
  callback = function(args)
    local position = api.nvim_buf_get_mark(args.buf, [["]])
    local winid = fn.bufwinid(args.buf)
    pcall(api.nvim_win_set_cursor, winid, position)
  end,
})
