Neovim plugin: LuaSnip

Example snippets in Lua

We'll explore different examples from the simplest to the more complex snippets made with Lua. The following code blocks will assume the environment with the default value from luasnip.config.snip_env.

The plugin source code also has a comprehensive set of examples in the Examples/ folder. It also has a wiki containing multiple example snippets showcasing the various nodes.

Simple word trigger

The simplest snippet possible. This will simply replace hello with world.

s("hello", t "world")

Exploring other nodes, we could replace the text node with a function node.

s("hello", f(function ()
    return "world"
end))

Patterned trigger

A simple snippet that will answer you back when triggered.

This snippet makes use of:

s(
  { trig = "hello (%a+)", regTrig = true },
  f(function (_, snip)
      return string.format("hey there, %s", snip.captures[1])
  end)
)

Choosing between Asciidoctor admonition blocks

We can easily create a snippet for multiple choices. In Asciidoctor, we have admonition blocks that are formatted similarly.

Here's one way to define such snippet...

s(
  "admo",
  fmt([[
    {}: {}
  ]], {
    c(1, {
        t "NOTE",
        t "TIP",
        t "IMPORTANT",
        t "CAUTION",
        t "WARNING",
    }),
    i(0),
  })
)

Dynamic Asciidoctor header with optional automatic TOC

Here is a snippet for Asciidoc documents for creating headers. As an example, h6 should print the appropriate header level.

It should follow some restrictions for this snippet.

This snippet makes use of dynamic node to change the node between a choice node for the first heading level and a blank text node for the rest.

function min_asciidoc_header_level(level)
  math.min(level, 6)
end

s(
  { trig = "h(%d)", regTrig = true },
  fmt([[
      {} {}
      {}
      {}
    ]], {
      f(function(_, snip)
          local level = min_asciidoc_header(snip.captures[1])
          return string.rep("=", level)
      end),
      i(1, "CHAPTER"),
      d(2, function(_, snip)
          local nodes = {}
          table.insert(nodes, t "")

          local level = min_asciidoc_header(snip.captures[1])

          if level == 1 then
            table.insert(nodes, t ":toc:")
          end

          local parent = c(1, nodes)
          if level > 1 then
            parent = t ""
          end

          return sn(nil, parent)
      end, {}),
      i(0),
  })
)