• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / Getting Started with LuaSnip

Getting Started with LuaSnip

Last updated on November 23, 2022 by Sal Ferrarello

This article assumes you are using Neovim (version 0.8.0 or higher) and packer.nvim to manage your plugins. Adding the following loads the LuaSnip plugin, creates a snippet for func, and maps Ctrl + p to expand the snippet and jump through the fields.

use({
  "L3MON4D3/LuaSnip",
  tag = "v1.*",
  config = function()
    local ls = require("luasnip")

    -- for "all" filetypes create snippet for "func"
    ls.add_snippets( "all", {
      ls.parser.parse_snippet(
        'func',
        'function ${1}(${2}) \n{\n\t${3}\n}'),
    })

    -- Map "Ctrl + p" (in insert mode)
    -- to expand snippet and jump through fields.
    vim.keymap.set(
    'i',
    '<c-p>',
    function()
      if ls.expand_or_jumpable() then
        ls.expand_or_jump()
      end
    end
    )
  end
})

Once you’ve added this packer use block, you can run :PackerSync.

Check LuaSnip is Running

If LuaSnip is setup an running correctly, you should now be able to run the command

:LuaSnipListAvailable

You should have one Snip available with the name func and the output should look like this.

{
  all = { {
      description = { "func" },
      name = "func",
      regTrig = false,
      trigger = "func",
      wordTrig = true
    } }
}

How to Use

Open a file, enter insert mode and type

func

while still in insert mode press Ctrl + p.

This should expand func into

function () 
{

}

and place the cursor between “function” and “()”, where we would define the function name.

After typing in a function name (e.g. myFunction), press Ctrl + p again and you’ll jump to in between the parentheses (""), where we would define the parameters for the function. Press Ctrl + p again and you’ll jump into the body of the function.

https://salferrarello.com/wp-content/uploads/2022/11/luasnip-example.mp4
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Computing, Dev Tips, Programming, Solution Tagged With: lua, neovim, vim, vimplugin

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in