• Stars
    star
    219
  • Rank 175,353 (Top 4 %)
  • Language
    Lua
  • License
    MIT License
  • Created 5 months ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automagical editing and creation of snippets.

nvim-scissors ✂️

badge

Automagical editing and creation of snippets.

add-new-snippet.mp4
edit-existing-snippet.mp4

Table of Contents

Features

  • Add new snippets, edit snippets, or delete snippets on the fly.
  • Syntax highlighting while you edit the snippet. Includes highlighting of tokens like $0 or ${2:foobar}.
  • Automagical conversion from buffer text to JSON string (quotes are escaped, etc.)
  • Intuitive UI for editing the snippet, dynamically adapting the number of prefixes.
  • Auto-reloading of the new/edited snippet (if using LuaSnip).
  • JSON-formatting and sorting of the snippet file after updating, using yq or jq. (Optional, but useful when version-controlling your snippet collection.)
  • Snippet/file selection via telescope or vim.ui.select.
  • Automatic bootstrapping of the snippet folder, if it is empty or missing a package.json.
  • Supports only VSCode-style snippets.

Tip

You can use snippet-converter.nvim to convert your snippets to the VSCode format.

Rationale

  • Regrettably, there are innumerable formats in which snippets can be saved. The closest thing to a standard is the VSCode snippet format. For portability, easier sharing, and to future-proof your snippet collection, it can make sense to save your snippets in that format.
  • Most notably, the VSCode format is used by plugins like friendly-snippets and supported by LuaSnip.
  • However, the snippets are stored as JSON files, which are a pain to modify manually. This plugin aims to alleviate that pain by automagically writing the JSON for you.

Installation

The plugin requires that your snippet are saved in the VSCode-style snippet format. If your snippet folder is empty, this plugin bootstraps a simple snippet folder for you.

For the specific requirements of the VSCode-style snippets, please see the FAQ section on the VSCode format.

-- lazy.nvim
{
	"chrisgrieser/nvim-scissors",
	dependencies = "nvim-telescope/telescope.nvim", -- optional
	opts = {
		snippetDir = "path/to/your/snippetFolder",
	} 
},

-- packer
use {
	"chrisgrieser/nvim-scissors",
	dependencies = "nvim-telescope/telescope.nvim", -- optional
	config = function()
		require("scissors").setup ({
			snippetDir = "path/to/your/snippetFolder",
		})
	end,
}

When telescope.nvim is installed, it is automatically used as picker. Otherwise, nvim-scissors falls back to vim.ui.select. (You can use dressing.nvim to re-direct vim.ui.select to fzf-lua, if you prefer it over telescope.)

If you are not using VSCode-style snippets already, here is how you load them with LuaSnip:

require("luasnip.loaders.from_vscode").lazy_load { paths = { "path/to/your/snippetFolder" } }

Note

This plugin is only for editing and creating snippets. It does not expand snippets, which is done by snippet engines like LuaSnip.

Usage

The plugin provides two commands, :ScissorsAddNewSnippet and :ScissorsEditSnippet. You can pass range to :ScissorsAddSnippet command to prefill snippet body (for example :'<,'>ScissorsAddSnippet or :3ScissorsAddSnippet).

The plugin also provides two lua functions addNewSnippet and editSnippet, which you can use to directly create keymaps:

vim.keymap.set("n", "<leader>se", function() require("scissors").editSnippet() end)

-- When used in visual mode prefills the selection as body.
vim.keymap.set({ "n", "x" }, "<leader>sa", function() require("scissors").addNewSnippet() end)

Tip

A quick method for creating a new snippet that is similar to an existing snippet is to search for a snippet via editSnippet, and then use the duplicateSnippet command (default keymap: <C-d>).

The popup intelligently adapts to changes in the prefix area: Each line represents one prefix, and creating or removing lines thus changes the number of prefixes. ("Prefix" is how trigger words are referred to in the VSCode format.)

Showcase prefix change

Configuration

The .setup() call is optional.

-- default settings
require("scissors").setup {
	snippetDir = vim.fn.stdpath("config") .. "/snippets",
	editSnippetPopup = {
		height = 0.4, -- relative to the window, number between 0 and 1
		width = 0.6,
		border = "rounded",
		keymaps = {
			cancel = "q",
			saveChanges = "<CR>", -- alternatively, can also use `:w`
			goBackToSearch = "<BS>",
			deleteSnippet = "<C-BS>",
			duplicateSnippet = "<C-d>",
			openInFile = "<C-o>",
			insertNextToken = "<C-t>", -- insert & normal mode
			jumpBetweenBodyAndPrefix = "<C-Tab>", -- insert & normal mode
		},
	},
	telescope = {
		-- By default, the query only searches snippet prefixes. Set this to
		-- `true` to also search the body of the snippets.
		alsoSearchSnippetBody = false,
	},
	-- `none` writes as a minified json file using `vim.encode.json`.
	-- `yq`/`jq` ensure formatted & sorted json files, which is relevant when
	-- you version control your snippets.
	jsonFormatter = "none", -- "yq"|"jq"|"none"
}

Tip

vim.fn.stdpath("config") returns the path to your nvim config.

Cookbook & FAQ

Example for the VSCode-style snippet format

This plugin requires that you have a valid VSCode snippet folder. In addition to saving the snippets in the required JSON format, there must also be a package.json at the root of the snippet folder, specifying which files are should be used for which languages.

Example file structure inside the snippetDir:

.
├── package.json
├── python.json
├── project-specific
│   └── nvim-lua.json
├── javascript.json
└── allFiletypes.json

Example package.json:

{
	"contributes": {
		"snippets": [
			{
				"language": "python",
				"path": "./python.json"
			},
			{
				"language": "lua",
				"path": "./project-specific/nvim-lua.json"
			},
			{
				"language": ["javascript", "typescript"],
				"path": "./javascript.json"
			},
			{
				"language": "all",
				"path": "./allFiletypes.json"
			}
		]
	},
	"name": "my-snippets"
}

Note

The special filetype all enables the snippets globally, regardless of filetype.

Example snippet file (here: nvim-lua.json):

{
  "autocmd (Filetype)": {
    "body": [
      "vim.api.nvim_create_autocmd(\"FileType\", {",
      "\tpattern = \"${1:ft}\",",
      "\tcallback = function()",
      "\t\t$0",
      "\tend,",
      "})"
    ],
    "prefix": "autocmd (Filetype)"
  },
  "file exists": {
    "body": "local fileExists = vim.loop.fs_stat(\"${1:filepath}\") ~= nil",
    "prefix": "file exists"
  },
}

For details, read the official VSCode snippet documentation:

Version Controlling Snippets: JSON-formatting

This plugin writes JSON files via vim.encode.json. That method saves the file in minified form, and does not have a deterministic order of dictionary keys.

Both, minification, and unstable key order, are of course problem if you version-control your snippet collection. To solve this problem, nvim-scissors can optionally unminify and sort the JSON files via yq or jq after updating a snippet. (Both are also available via mason.nvim.)

It is recommended to run yq/jq once on all files in your snippet collection, since the first time you edit a file, you would still get a large diff from the initial sorting. You can do so with yq using this command:

cd "/your/snippet/dir"
fd ".*\.json" | xargs -I {} yq --inplace --output-format=json "sort_keys(..)" {}

How to do the same with jq is left as an exercise to the reader.

Snippets on Visual Selection

With Luasnip, this is an opt-in feature, enabled via:

require("luasnip").setup {
	store_selection_keys = "<Tab>",
}

In your VSCode-style snippet, use the token $TM_SELECTED_TEXT at the location where you want the selection to be inserted. (It's roughly the equivalent of LS_SELECT_RAW in the Luasnip syntax.)

Then, in visual mode, press the key from store_selection_keys. The selection disappears, and you are put in insert mode. The next snippet you now trigger is going to have $TM_SELECTED_TEXT replaced with your selection.

friendly-snippets

Even though the snippets from the friendly-snippets repository are written in the VSCode-style format, editing them directly is not supported. The reason being that any changes made would be overwritten as soon as the friendly-snippets repository is updated (which happens fairly regularly), and there is little nvim-scissors can do about that.

What you can do, however, is to copy individual snippets files from the friendly-snippets repository into your own snippet folder, and edit them then.

Auto-triggered Snippets

While the VSCode snippet format does not support auto-triggered snippets, LuaSnip allows you to specify auto-triggering in the VSCode-style JSON files by adding the luasnip key.

nvim-scissors does not touch any keys other than prefix and body in the JSON files, so any additions via the luasnip key are preserved.

Tip

You can use the openInFile keymap to directory open JSON file at the snippet's location to make edits there easier.

Credits

About Me
In my day job, I am a sociologist studying the social mechanisms underlying the digital economy. For my PhD project, I investigate the governance of the app economy and how software ecosystems manage the tension between innovation and compatibility. If you are interested in this subject, feel free to get in touch.

Blog
I also occasionally blog about vim: Nano Tips for Vim

Profiles

Buy Me a Coffee at ko-fi.com

More Repositories

1

shimmering-obsidian

Alfred Workflow with dozens of features for controlling your Obsidian vault.
JavaScript
735
star
2

nvim-spider

Use the w, e, b motions like a spider. Move by subwords and skip insignificant punctuation.
Lua
427
star
3

shimmering-focus

Minimalistic Obsidian Theme for keyboard-centric users.
CSS
421
star
4

nvim-various-textobjs

Bundle of more than 30 new text objects for Neovim.
Lua
412
star
5

nvim-genghis

Convenience file operations for neovim, written in lua.
Lua
179
star
6

nvim-recorder

Enhance the usage of macros in Neovim.
Lua
168
star
7

nvim-early-retirement

Send buffers into early retirement by automatically closing them after x minutes of inactivity.
Lua
154
star
8

obsidian-smarter-md-hotkeys

A plugin for Obsidian providing hotkeys that select words and lines in a smart way before applying markup. Multiple cursors are supported as well.
TypeScript
131
star
9

alfred-bibtex-citation-picker

Citation picker & lightweight reference manager for BibTeX files, via Alfred.
JavaScript
127
star
10

nvim-origami

Fold with relentless elegance.
Lua
98
star
11

pandoc_alfred

Pandoc-Suite for Academic Writing in Markdown
JavaScript
96
star
12

nvim-tinygit

Lightweight and nimble git client for nvim.
Lua
93
star
13

nvim-kickstart-python

A launch point for your nvim configuration for Python
Lua
84
star
14

obsidian-theme-design-utilities

Some Utilities and Quality-of-Life Features for Designers of Obsidian Themes
TypeScript
83
star
15

pdf-annotation-extractor-alfred

Alfred Workflow to extract annotations from PDF files.
JavaScript
71
star
16

nvim-chainsaw

Speed up log creation. Create various kinds of language-specific log statements, such as logs of variables, assertions, or time-measuring.
Lua
65
star
17

finder-vim-mode

Feature-rich mouseless control of macOS Finder, inspired by vim/ranger.
Makefile
62
star
18

nvim-rulebook

Add inline-comments to ignore rules, or lookup rule documentation online.
Lua
61
star
19

obsidian-divide-and-conquer

An Obsidian plugin that provides commands for bulk enabling/disabling of plugins. Useful for debugging when you have many plugins.
TypeScript
50
star
20

nvim-puppeteer

Automatically convert strings to f-strings or template strings and back.
Lua
48
star
21

.config

My personal dotfiles
Lua
41
star
22

nvim-alt-substitute

A substitute of vim's :substitute that uses lua patterns instead of vim regex. Supports incremental preview.
Lua
40
star
23

grappling-hook

Obsidian Plugin for blazingly fast file switching. For those who find the Quick Switcher still too slow.
TypeScript
39
star
24

new-tab-default-page

Obsidian plugin to open a note of your choice when creating a new tab, like in the browser.
TypeScript
39
star
25

zsh-magic-dashboard

Pressing "enter" on an empty buffer displays an information-rich and pretty dashboard.
Shell
29
star
26

cmp-nerdfont

nvim-cmp source for nerdfont icons
Lua
29
star
27

alfred-neovim-utilities

Search neovim plugins and online :help via Alfred
JavaScript
26
star
28

twitter-workspace-for-drafts

Various capabilities for composing tweets in the Drafts app.
22
star
29

nvim-dr-lsp

Status line component showing the number of LSP definition and reference of the token under the cursor.
Lua
22
star
30

obsidian-sembr

Obsidian Plugin for Semantic Line Breaks
TypeScript
21
star
31

cmp_yanky

cmp-source for clipboard history from yanky.nvim
Lua
20
star
32

obsidian-footnote-indicator

Indicates the presence of footnotes in the gutter and the Status bar
Shell
19
star
33

obsidian-quadro

Obsidian Plugin for social-scientific Qualitative Data Analysis (QDA). An open alternative to MAXQDA and atlas.ti, using Markdown to store data and research codes.
TypeScript
18
star
34

alfred-reddit-browser

Browse your favorite subreddits (and hackernews) via Alfred.
JavaScript
17
star
35

nvim-pseudometa-plugin-template

A template for new nvim plugins
Shell
16
star
36

alfred-atop

System Monitoring and Process Management via Alfred
JavaScript
15
star
37

alfred-docs-searches

Search more than two dozen official documentation sites via Alfred
JavaScript
14
star
38

pdf-summarizer-alfred

Get summaries of your PDFs via ChatPDF.
Shell
11
star
39

obsidian-extra-md-commands

Obsidian plugin that adds various commands, e.g. for __bold__ or <cite>.
TypeScript
11
star
40

wrench-knife

Collection of useful snippets for Hammerspoon
Lua
11
star
41

hyper-seek

Alfred workflow that shows inline search results, without a keyword.
JavaScript
10
star
42

obsidian-sidebar-toggler

Finer control of the Obsidian sidebars. To be used with an external window manager.
TypeScript
10
star
43

pseudometa-obsidian-plugin-template

A description for the plugin
Shell
9
star
44

pdf-annotation-extractor

Extracts Annotations from PDFs as well-formatted markdown
JavaScript
9
star
45

gitfred

Helpful GitHub Assistant for Alfred.
JavaScript
9
star
46

alfred-homebrew

Search, install, or uninstall homebrew packages conveniently via Alfred.
JavaScript
9
star
47

alfred-themes

A small collection of Alfred Themes I designed
8
star
48

obsidian-nothing

An Obsidian plugin that adds a no-op command.
Shell
8
star
49

dotfiles-old

pseudometa's dotfiles
TeX
7
star
50

obsidian-smarter-paste

Improvements for when you paste things into Obsidian
TypeScript
6
star
51

alfred-pass

Alfred Client for the pass-cli
JavaScript
6
star
52

alfred-steam-companion

Alfred Workflow that interacts with Steam. Launches games directly, creates aliases, uninstalls games, and searches the Steam Store
6
star
53

drafts-snooze

Combination of settings, draft actions and shortcuts to enable the snoozing of drafts.
5
star
54

alfred-read-later

Simple standalone read-later-app for Alfred. Saves the items in plaintext on your device.
JavaScript
5
star
55

portfolio-performance-alfred

Searches your watchlists in the Portfolio Performance App for securities. Select one to copy its Name, Symbol, ISIN, or WKN to the clipboard.
JavaScript
4
star
56

alfred-workflow-template

Shell
4
star
57

alfred-writing-assistant

Autocorrection and synonym suggestions for the word under the cursor. Rephrasing of the selected text. All with one key press.
Shell
4
star
58

obsidian-task-statusbar

Obsidian plugin that displays the number of completed and total tasks in the status bar.
Shell
3
star
59

axelrod-prisoner-dilemma

Recreation of the prisoner's dilemma model from Axelrod's "Evolution of Cooperation" in Python
Python
2
star
60

obsidian-personal-plugin

Personal Obsidian plugin, containing features customized to my workflow.
TypeScript
2
star
61

tot-alfred

Tot.app Integration for Alfred.
JavaScript
2
star
62

apuz-gender-analyzer

Analysis of the genders of the authors at the German journal "Aus Politik und Zeitgeschichte" (APuZ)
Python
2
star
63

alfred-wikipedia-suggest

Get in-line Wikipedia search suggestions
JavaScript
2
star
64

quadro-example-vault

Example vault for Quadro, the QDA Plugin for Obsidian.
Makefile
2
star
65

name-gender-analyzer

Makefile
1
star
66

test-repo

This repo is currently only used for testing GitHub Release Actions
Shell
1
star