You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

343 lines
9.5 KiB

2 years ago
local q = require "vim.treesitter.query"
local ts_utils = require("nvim-treesitter.ts_utils")
local tprint = require("setup.utils").tprint
local M = {}
M.config_values = {
server = 'http://localhost:7700',
dateformat = '%Y%m%d%H%M-',
prefix = os.getenv("HOME") .. "/notes/",
replace_pattern = {
[1] = { ['@'] = '_AT_' },
[2] = { ['[.]'] = '_DOT_' },
[3] = { ['[%$]'] = '_DOLLAR_' },
[4] = { ['%~'] = '_TILDE_' },
[5] = { ['[%|]'] = '_PIPE_' },
[6] = { ['[^a-zA-Z0-9-]'] = '_' },
[7] = { ['__+'] = '_' },
[8] = { ['^_'] = '' },
[9] = { ['_$'] = '' },
},
}
local function hexdecode(hex)
return (hex:gsub("%x%x", function(digits) return string.char(tonumber(digits, 16)) end))
end
local function hexencode(str)
return (string.upper(str:gsub(".", function(char) return string.format("%2x", char:byte()) end)))
end
local function dirLookup(dir)
local files = {}
local p = io.popen('find "' .. dir .. '" -type f') --Open directory look for files, save data in p. By giving '-type f' as parameter, it returns all files.
if p then
for file in p:lines() do --Loop through all files
if file:match('.*norg$') then
table.insert(files, file)
end
end
end
return files
end
local function isempty(s)
return s == nil or s == ''
end
local createfilename = function(suffix)
local name = vim.fn.input("Please enter a title: ")
if string.len(name) == 0 then
print(" ")
print("Title missing: request ignored!")
return
end
local date = os.date(M.config_values.dateformat)
for index, pv in ipairs(M.config_values.replace_pattern) do
for key, value in pairs(pv) do
if name.find(name, key) then
name = string.gsub(name, key, value)
end
end
end
return M.config_values.prefix .. date .. name .. suffix, date, name
end
function M.newNeorgNote()
local name, date, title = createfilename(".norg")
local template = {
"* " .. string.gsub(title or "", "_", " "),
" ",
}
vim.cmd(":e" .. name)
vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, template)
vim.cmd(":Neorg inject-metadata")
vim.cmd('startinsert!')
end
function M.newMarkdownNote()
local name, date, title = createfilename(".md")
local template = {
"---",
"title: " .. date .. title,
"description: ",
"authors:",
" - nige",
"categories:",
"project: ",
"created: " .. os.date('%Y-%m-%d'),
"version: na",
"---",
"",
"# " .. string.gsub(title or "", "_", " "),
"",
"",
}
vim.cmd(":e" .. name)
vim.api.nvim_buf_set_text(0, 0, 0, 0, 0, template)
vim.cmd('startinsert!')
end
function M.createWorknote()
local date = os.date('%Y-%m-%d %H:%M')
vim.cmd(':normal o')
local pos = vim.api.nvim_win_get_cursor(0)[2]
local line = vim.api.nvim_get_current_line()
local nline = line:sub(0, pos) .. '- Note tagen on /' .. date .. "/: " .. line:sub(pos + 1)
vim.api.nvim_set_current_line(nline)
vim.cmd(':normal $')
vim.api.nvim_set_mode = 'i'
vim.cmd('startinsert!')
end
--------------------------------------------------------------------------------
local index = "notes"
local fillqflist = function(items, query)
local title = "Meilisearch - index: '" .. index .. "'"
if type(query) ~= "nil" then
title = title .. ", query: '" .. query .. "'"
end
vim.fn.setqflist(
{},
' ', -- 'a' to add item(s) to an existing list
{
title = title,
id = 999,
items = items
}
)
end
function M.search()
local query = vim.fn.input("Meilisearch: ")
local curl = require "plenary.curl"
local json = require('json')
local prefix = M.config_values.prefix
local hits = {}
-- print("----" .. query)
local res = curl.get(M.config_values.server .. "/indexes/notes/search", {
accept = "application/json",
query = {
q = query,
showMatchesPosition = "true"
}
})
if res then
local tab = json.parse(res.body)
if tab and type(tab['hits']) ~= "nil" then
for i, v in ipairs(tab['hits']) do
local hit = {
text = "",
pattern = query,
filename = prefix .. v['title'],
-- filename = prefix .. hexdecode(v['id']),
}
--print("id: '" .. hexdecode(v['id']) .. "'")
table.insert(hits, hit)
end
else
print("No data in table")
end
fillqflist(hits, query)
vim.cmd("copen")
end
end
-------------------------------------------------------------------------------
local function i(value)
print(vim.inspect(value))
end
local removeLines = function(str, lines)
local multistring = str
for ii = 1, lines, 1 do
multistring = multistring:gsub("^[^\n]*\n", "")
end
return multistring
end
local keywords = {
["title"] = false,
["description"] = false,
["authors"] = true,
["categories"] = true,
["project"] = false,
["created"] = false,
["version"] = false
}
local contains = function(array, val)
for k, v in pairs(array) do
if k == val then
return true, v
end
end
return false, false
end
local function splitValue(s, delimiter)
local result = {};
for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do
table.insert(result, match);
end
return result;
end
local function trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
local function trimTable(t)
local newTable = {}
for key, value in pairs(t) do
if type(value) == "string" then
newTable[key] = trim(value)
end
end
return newTable
end
local split = function(lines)
local metadata = {}
for line in lines:gmatch("[^\n]*\n?") do
local key = string.match(line, "^[^:]+:")
if type(key) ~= "nil" then
key = string.sub(key, 1, key:len() - 1)
local isContained, isArray = contains(keywords, key:lower())
if isContained then
local value = string.match(line, ":.*$")
if type(value) == "string" then
value = string.match(value, "[^: ]+.*$")
value = string.gsub(value, "\n", "")
if isArray then
value = splitValue(value, ",")
value = trimTable(value)
end
else
value = ""
if isArray then
value = { "" }
end
end
metadata[key] = value
end
end
end
return metadata
end
function M.upsertNote(bufnr)
if isempty(bufnr) then
bufnr = vim.api.nvim_get_current_buf()
end
-- local language_tree = vim.treesitter.get_parser(bufnr, 'norg')
local language_tree = vim.treesitter.get_parser(bufnr)
local syntax_tree = language_tree:parse()
local root = syntax_tree[1]:root()
local query = vim.treesitter.parse_query('norg', [[
(ranged_tag
name: (tag_name) @name (#eq? @name "document.meta")
content: (ranged_tag_content) @content
(ranged_tag_end) @end (#offset! @end)
)
]])
local header_lines = 0
local note
for s, captures, metadata in query:iter_matches(root, bufnr) do
local headerText = q.get_node_text(captures[2], bufnr)
note = split(headerText)
local text = q.get_node_text(captures[2], bufnr)
print('######### s')
tprint(s)
print('######### captures')
tprint(captures)
print('######### metadata')
tprint(metadata)
print('#########')
header_lines = metadata['ranged_verbatim_tag'][1][1]
end
-- if header_lines then
-- note["headerlines"] = header_lines
-- end
note["id"] = hexencode(string.gsub(vim.api.nvim_buf_get_name(bufnr), M.config_values.prefix, ""))
note["body"] = removeLines(q.get_node_text(root, bufnr), header_lines)
--i(note)
local curl = require "plenary.curl"
local json = require('json')
local prefix = "/Users/nige/notes/"
local hits = {}
local header = {}
header = { header = "\"Content-Type\" = \"application/json\"" }
i(curl.post(M.config_values.server .. "/indexes/notes/documents",
{ raw = { "-H", "Content-Type: application/json" }, body = json.stringify(note) }
))
return tonumber(bufnr)
end
M.updateAll = function()
local files = dirLookup(M.config_values.prefix)
for key, value in pairs(files) do
if value:match(".*norg") then
vim.cmd("e " .. value)
local bufnr = M.upsertNote()
--vim.cmd("bw")
--print("number:" .. bufnr .. type(bufnr))
--[[ pcall(vim.api.nvim_buf_delete, bufnr {}) ]]
end
end
end
--M.yaml = function()
-- print ("START")
-- local yaml_string = [[
--title
-- list
-- - item 1
-- - item 2
-- - item 3
-- key: value
-- ]]
-- print ("load require")
-- local yaml = require("lyaml")
-- print ("load table")
-- local tbl = yaml.load(yaml_string)
-- print ("print values")
-- print(tbl.title.list)
-- print(tbl.title.key)
--end
return M