ng_html.lua (2000B)
1 -- TODO(tms) 06.09.22: Handle single line template string 2 local ok, template_query = pcall(vim.treesitter.query.parse, 'dart', [[ 3 (annotation 4 (arguments 5 (named_argument 6 (label (identifier) @_identifier) 7 (string_literal) @template 8 ) 9 ) 10 (#eq? @_identifier "template") 11 (#offset! @template 0 3 0 -3) 12 ) 13 ]]) 14 15 if not ok then 16 return 17 end 18 19 local function get_root(bufnr) 20 local parser = vim.treesitter.get_parser(bufnr, 'dart', {}) 21 local tree = parser:parse()[1] 22 return tree:root(); 23 end 24 25 local function prettier_html(text) 26 local split = vim.split(text, '\n') 27 local result = table.concat(vim.list_slice(split, 2, #split - 1), '\n') 28 local job = require('plenary.job'):new { 29 command = 'prettier', 30 args = { 31 '--plugin=/home/tms/.local/share/npm/lib/node_modules/prettier-plugin-organize-attributes/lib/index.js', 32 '--tab-width=4', 33 '--parser=html', 34 }, 35 writer = { result }, 36 } 37 38 return job:sync() 39 end 40 41 local function format_ng_html() 42 local bufnr = vim.api.nvim_get_current_buf() 43 44 if vim.bo[bufnr].filetype ~= 'dart' then 45 vim.notify 'can only be used in dart' 46 return 47 end 48 49 local root = get_root(bufnr) 50 51 local changes = {} 52 53 for id, node in template_query:iter_captures(root, bufnr, 0, -1) do 54 local name = template_query.captures[id] 55 if name == 'template' then 56 local range = { node:range() } 57 if range[1] ~= range[3] then 58 local formatted = prettier_html(vim.treesitter.get_node_text(node, bufnr)) 59 60 table.insert(changes, 1, { start = range[1] + 1, final = range[3], formatted = formatted }) 61 end 62 end 63 end 64 65 for _, change in ipairs(changes) do 66 vim.api.nvim_buf_set_lines(bufnr, change.start, change.final, false, change.formatted) 67 end 68 end 69 70 vim.api.nvim_create_user_command('NgHtmlFormat', format_ng_html, {}) 71 72 -- local group = vim.api.nvim_create_augroup('ng-html-format', {}) 73 -- vim.api.nvim_create_autocmd('BufWritePre', { group = group, pattern = '*.dart', callback = format_ng_html })