shiki.nvim

I have just released a new Neovim plugin—shiki.nvim! Check out its demo on GitHub to see how it works. :-)

shiki.nvim automates the process I described in HTML Code Snippets with Syntax Highlighting. I have realized that most of the code I want to publish on the blog lives in my editor. I asked myself:

Why should it be any more effort than selecting the relevant part and running a command?

After all, it is quite a hassle to copy the code into a temporary file, provide the language it is written in, and run the script against the file. Especially, that the code is already in my editor and filetype is a thing1.

Learnings

Here is a quick rundown of things I have learned during shiki.nvim development.

stdpath()
A Neovim's built-in function. Can be accessed in Lua via vim.fn.stdpath(). I used it to get a path to Neovim's data directory. I needed that path to create a directory for running the highlight Node script in.
setreg()

setreg() came in clutch when putting things into the clipboard. I tried playing with let @+ = "..." as system clipboard uses + register. However, I ended up with nothing due to quoting shenanigans.

vim.fn.setreg() made it straightforward. With Neovim handling the clipboard I don't have to worry about system-specific solutions.

Calling Node from Lua

I learned about a cwd option to vim.system. This allowed me to run commands exactly where I wanted!

Other than that this wasn't really that hard. Just a bit of trial and error to get things like trailing blank line sorted out. You can see the outcome in node.lua.

vim.iter

That was the first time I have used vim.iter. It has some useful functions for working with iterables in Lua. The one I used was merging tables with:

vim.iter({
  { "a", "b" },
  { "c" },
}):flatten():totable()
Line Indexing

I spent quite some time debugging why selected lines were off. It turns out that line numbers received by a user command are one-based. On the other hand, nvim_buf_get_lines() expects zero-based start and end index.

Make sure to check if you have the indexing under control!

Wrestling Quotes

Single quotes, double quotes, backticks... Supporting multiple lines or not. Being a beginning of a comment or being used within copied code.

I had to tinker quite a bit to get all of that right. And then some more, because I had an inline \n in file. There is not much of a learning from this. Maybe: know your quotes and whether they have a special behavior.

That's it! If you plan to make a use of shiki.nvim, then let me know. :-)

Footnotes

  1. filetype doesn't translate one-to-one to Shiki's lang argument. However, it is good enough for starters. It works with the languages I need it to work. If this becomes a problem, then I will thing about a filetype-to-lang mapping. ↩︎