The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Extract Text From Files With Tree-Sitter In Neovim

TODO: Pull subtitle into page object code_start_default_section code_end_default_section

The output would be

pre_full_default_section

Very cool stuff

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Extract Text From Files With Tree-Sitter In Neovim

TODO: Convert this example to HTML

This pulls the code block container languages used 
in a neopolitan file from `buf_in`` and prints
them out to `buf_out``

-- code/
-- lua

local append_text = function(out_bufnr, lines)
  vim.api.nvim_buf_set_lines(
    out_bufnr, -1, -1, false, lines
  )
end

local truncate_text = function(out_bufnr)
  vim.api.nvim_buf_set_lines(
    out_bufnr, 0, -1, false, {}
  )
end

local embedded_code = vim.treesitter.query.parse(
  "neopolitan",
  [[ (code_section
      attr_bool: (
        attr_bool
          attr_bool_value: (attr_bool_value) @language))
]])

local get_root = function(in_bufnr)
  local parser = vim.treesitter.get_parser(in_bufnr, "neopolitan", {})
  local tree = parser:parse()[1]
  return tree:root()
end

local format_thing = function(in_bufnr, out_bufnr)
  if vim.bo[in_bufnr].filetype ~= "neopolitan" then
    vim.notify "can only be used in neopolitan files"
    return
  end

  local root = get_root(in_bufnr)

  for id, node in embedded_code:iter_captures(root, in_bufnr, 0, -1) do
    local capture_key = embedded_code.captures[id]
    if capture_key == "language" then
      local text_string = vim.treesitter.get_node_text(node, in_bufnr)
      append_text(out_bufnr, { text_string })
    end
  end
end


local buf_in = 5
local buf_out = 8

truncate_text(buf_out)
format_thing(buf_in, buf_out)

-- /code


Given this file

-- code/
-- neopolitan

-- title

tmp dev example

-- code
-- rust

fn main() {
  println!("here");
}

-- p

Some stuff

-- code
-- python

print("py")

-- p

etc...


-- /code


-- p 

The output would be

-- pre

rust
python


-- p 

Very cool stuff

-- ref
-- title: Magically format embedded languages in Neovim - TJ DeVries
-- url: https://www.youtube.com/watch?v=v3o9YaHBM4Q

This is the video where I got most of this code from



-- categories
-- Neovim 
-- Tree-Sitter 
-- Lua

-- metadata
-- date: 2023-10-20 17:22:51
-- id: 2x2plljn
-- site: aws
-- type: post
-- status: draft