Mini Surround
Mini Surround
==============================================================================
Features:
- Actions (all of them are dot-repeatable out of the box and respect
|[count]|) with configurable keymappings:
- Add surrounding with `sa` (in visual mode or on motion).
- Delete surrounding with `sd`.
- Replace surrounding with `sr`.
- Find surrounding with `sf` or `sF` (move cursor right or left).
- Highlight surrounding with `sh`.
- Change number of neighbor lines with `sn` (see |MiniSurround-algorithm|).
- Configurable search methods to find not only covering but possibly next,
previous, or nearest surrounding. See more in |MiniSurround.config|.
# Setup ~
# Example usage ~
Regular mappings:
- `saiw)` - add (`sa`) for inner word (`iw`) parenthesis (`)`).
- `saiw?[[<CR>]]<CR>` - add (`sa`) for inner word (`iw`) interactive
surrounding (`?`): `[[` for left and `]]` for right.
- `2sdf` - delete (`sd`) second (`2`) surrounding function call (`f`).
- `sr)tdiv<CR>` - replace (`sr`) surrounding parenthesis (`)`) with tag
(`t`) with identifier 'div' (`div<CR>` in command line prompt).
- `sff` - find right (`sf`) part of surrounding function call (`f`).
- `sh}` - highlight (`sh`) for a brief period of time surrounding curly
brackets (`}`).
# Comparisons ~
- 'tpope/vim-surround':
- 'vim-surround' has completely different, with other focus set of
default mappings, while 'mini.surround' has a more coherent set.
- 'mini.surround' supports dot-repeat, customized search path (see
|MiniSurround.config|), customized specifications (see
|MiniSurround-surround-specification|) allowing usage of tree-sitter
queries (see |MiniSurround.gen_spec.input.treesitter()|),
highlighting and finding surrounding, "last"/"next" extended
mappings. While 'vim-surround' does not.
- 'machakann/vim-sandwich':
- Both have same keybindings for common actions (add, delete, replace).
- Otherwise same differences as with 'tpop/vim-surround' (except
dot-repeat because 'vim-sandwich' supports it).
- 'kylechui/nvim-surround':
- 'nvim-surround' is designed after 'tpope/vim-surround' with same
default mappings and logic, while 'mini.surround' has mappings
similar to 'machakann/vim-sandwich'.
- 'mini.surround' has more flexible customization of input surrounding
(with composed patterns, region pair(s), search methods).
- 'mini.surround' supports |[count]| in both input and output
surrounding (see |MiniSurround-count|) while 'nvim-surround' doesn't.
- 'mini.surround' supports "last"/"next" extended mappings.
- |mini.ai|:
- Both use similar logic for finding target: textobject in 'mini.ai'
and surrounding pair in 'mini.surround'. While 'mini.ai' uses
extraction pattern for separate `a` and `i` textobjects,
'mini.surround' uses it to select left and right surroundings
(basically a difference between `a` and `i` textobjects).
- Some builtin specifications are slightly different:
- Quotes in 'mini.ai' are balanced, in 'mini.surround' they are not.
- The 'mini.surround' doesn't have argument surrounding.
- Default behavior in 'mini.ai' selects one of the edges into `a`
textobject, while 'mini.surround' - both.
# Highlight groups ~
# Disabling ~
------------------------------------------------------------------------------
*MiniSurround-surround-builtin*
Builtin surroundings ~
This table describes all builtin surroundings along with what they
represent. Explanation:
- `Key` represents the surrounding identifier: single character which should
be typed after action mappings (see |MiniSurround.config.mappings|).
- `Name` is a description of surrounding.
- `Example line` contains a string for which examples are constructed. The
`*` denotes the cursor position over `a` character.
- `Delete` shows the result of typing `sd` followed by surrounding identifier.
It aims to demonstrate "input" surrounding which is also used in replace
with `sr` (surrounding id is typed first), highlight with `sh`, find with
`sf` and `sF`.
- `Replace` shows the result of typing `sr!` followed by surrounding
identifier (with possible follow up from user). It aims to demonstrate
"output" surrounding which is also used in adding with `sa` (followed by
textobject/motion or in Visual mode).
Example: typing `sd)` with cursor on `*` (covers `a` character) changes line
`!( *a (bb) )!` into `! aa (bb) !`. Typing `sr!)` changes same initial line
into `(( aa (bb) ))`.
>
|Key| Name | Example line | Delete | Replace |
|---|---------------|---------------|-------------|-----------------|
| ( | Balanced () | !( *a (bb) )! | !aa (bb)! | ( ( aa (bb) ) ) |
| [ | Balanced [] | ![ *a [bb] ]! | !aa [bb]! | [ [ aa [bb] ] ] |
| { | Balanced {} | !{ *a {bb} }! | !aa {bb}! | { { aa {bb} } } |
| < | Balanced <> | !< *a <bb> >! | !aa <bb>! | < < aa <bb> > > |
|---|---------------|---------------|-------------|-----------------|
| ) | Balanced () | !( *a (bb) )! | ! aa (bb) ! | (( aa (bb) )) |
| ] | Balanced [] | ![ *a [bb] ]! | ! aa [bb] ! | [[ aa [bb] ]] |
| } | Balanced {} | !{ *a {bb} }! | ! aa {bb} ! | {{ aa {bb} }} |
| > | Balanced <> | !< *a <bb> >! | ! aa <bb> ! | << aa <bb> >> |
| b | Alias for | !( *a {bb} )! | ! aa {bb} ! | (( aa {bb} )) |
| | ), ], or } | | | |
|---|---------------|---------------|-------------|-----------------|
| q | Alias for | !'aa'*a'aa'! | !'aaaaaa'! | "'aa'aa'aa'" |
| | ", ', or ` | | | |
|---|---------------|---------------|-------------|-----------------|
| ? | User prompt | !e * o! | ! a ! | ee a oo |
| |(typed e and o)| | | |
|---|---------------|---------------|-------------|-----------------|
| t | Tag | !<x>*</x>! | !a! | <y><x>a</x></y> |
| | | | | (typed y) |
|---|---------------|---------------|-------------|-----------------|
| f | Function call | !f(*a, bb)! | !aa, bb! | g(f(*a, bb)) |
| | | | | (typed g) |
|---|---------------|---------------|-------------|-----------------|
| | Default | !_a*a_! | !aaa! | __aaa__ |
| | (typed _) | | | |
|---|---------------|---------------|-------------|-----------------|
<
Notes:
- All examples assume default `config.search_method`.
- Open brackets differ from close brackets by how they treat inner edge
whitespace: open includes it left and right parts, close does not.
- Output value of `b` alias is same as `)`. For `q` alias - same as `"`.
- Default surrounding is activated for all characters which are not
configured surrounding identifiers. Note: due to special handling of
underlying `x.-x` Lua pattern (see |MiniSurround-search-algorithm|), it
doesn't really support non-trivial `[count]` for "cover" search method.
------------------------------------------------------------------------------
*MiniSurround-glossary*
Note: this is similar to |MiniAi-glossary|.
------------------------------------------------------------------------------
*MiniSurround-surround-specification*
Surround specification is a table with keys:
- <input> - defines how to find and extract surrounding for "input"
operations (like `delete`). See more in 'Input surrounding' setction.
- <output> - defines what to add on left and right for "output" operations
(like `add`). See more in 'Output surrounding' section.
function()
local left_edge = vim.pesc(vim.fn.input('Function name: '))
return { string.format('%s+%%b()', left_edge), '^.-%(().*()%)$' }
end
<
- Single region pair (see |MiniSurround-glossary|). Useful to allow
full control over surrounding. Will be taken as is. Example of
returning first and last lines of a buffer: >
function()
local n_lines = vim.fn.line('$')
return {
left = {
from = { line = 1, col = 1 },
to = { line = 1, col = vim.fn.getline(1):len() },
},
right = {
from = { line = n_lines, col = 1 },
to = { line = n_lines, col = vim.fn.getline(n_lines):len() },
},
}
end
<
- Array of region pairs. Useful for incorporating other instruments,
like treesitter (see |MiniSurround.gen_spec.treesitter()|). The
best region pair will be picked in the same manner as with composed
pattern (respecting options `n_lines`, `search_method`, etc.) using
output region (from start of left region to end of right region).
Example using edges of "best" line with display width more than 80: >
function()
local make_line_region_pair = function(n)
local left = { line = n, col = 1 }
local right = { line = n, col = vim.fn.getline(n):len() }
return {
left = { from = left, to = left },
right = { from = right, to = right },
}
end
local res = {}
for i = 1, vim.fn.line('$') do
if vim.fn.getline(i):len() > 80 then
table.insert(res, make_line_region_pair(i))
end
end
return res
end
<
- If there is a callable instead of assumed string pattern, it is expected
to have signature `(line, init)` and behave like `pattern:find()`.
It should return two numbers representing span in `line` next after
or at `init` (`nil` if there is no such span).
!IMPORTANT NOTE!: it means that output's `from` shouldn't be strictly
to the left of `init` (it will lead to infinite loop). Not allowed as
last item (as it should be pattern with captures).
Example of matching only balanced parenthesis with big enough width: >
{
'%b()',
function(s, init)
if init > 1 or s:len() < 5 then return end
return 1, s:len()
end,
'^.().*().$'
}
<
More examples:
- See |MiniSurround.gen_spec| for function wrappers to create commonly used
surrounding specifications.
- Pair of balanced brackets from set (used for builtin `b` identifier):
`{ { '%b()', '%b[]', '%b{}' }, '^.().*().$' }`
# Output surrounding ~
A table with <left> (plain text string) and <right> (plain text string)
fields. Strings can contain new lines character `\n` to add multiline parts.
Examples:
- Lua block string: `{ left = '[[', right = ']]' }`
- Brackets on separate lines (indentation is not preserved):
`{ left = '(\n', right = '\n)' }`
------------------------------------------------------------------------------
*MiniSurround-count*
Count with actions
------------------------------------------------------------------------------
*MiniSurround-search-algorithm*
Search algorithm design
Notes:
- Iteration over all matched spans is done in depth-first fashion with
respect to nested pattern.
- It is guaranteed that span is compared only once.
- For the sake of increasing functionality, during iteration over all
matching spans, some Lua patterns in composed pattern are handled
specially.
- `%bxx` (`xx` is two identical characters). It denotes balanced pair
of identical characters and results into "paired" matches. For
example, `%b""` for `"aa" "bb"` would match `"aa"` and `"bb"`, but
not middle `" "`.
- `x.-y` (`x` and `y` are different strings). It results only in matches with
smallest width. For example, `e.-o` for `e e o o` will result only in
middle `e o`. Note: it has some implications for when parts have
quantifiers (like `+`, etc.), which usually can be resolved with
frontier pattern `%f[]`.
------------------------------------------------------------------------------
*MiniSurround.setup()*
`MiniSurround.setup`({config})
Module setup
Parameters ~
{config} `(table|nil)` Module config table. See |MiniSurround.config|.
Usage ~
`require('mini.surround').setup({})` (replace `{}` with your `config` table)
------------------------------------------------------------------------------
*MiniSurround.config*
`MiniSurround.config`
Module config
Default values:
>
MiniSurround.config = {
-- Add custom surroundings to be used on top of builtin ones. For more
-- information with examples, see `:h MiniSurround.config`.
custom_surroundings = nil,
-- How to search for surrounding (first inside current line, then inside
-- neighborhood). One of 'cover', 'cover_or_next', 'cover_or_prev',
-- 'cover_or_nearest', 'next', 'prev', 'nearest'. For more details,
-- see `:h MiniSurround.config`.
search_method = 'cover',
## Custom surroundings ~
General recommendations:
- In `config.custom_surroundings` only some data can be defined (like only
`output`). Other fields will be taken from builtin surroundings.
- Function returning surround info at <input> or <output> fields of
specification is helpful when user input is needed (like asking for
function name). Use |input()| or |MiniSurround.user_input()|. Return
`nil` to stop any current surround operation.
-- Create custom surrounding for Lua's block string `[[...]]`. Use this inside
-- autocommand or 'after/ftplugin/lua.lua' file.
vim.b.minisurround_config = {
custom_surroundings = {
s = {
input = { '%[%[().-()%]%]' },
output = { left = '[[', right = ']]' },
},
},
}
<
## Respect selection type ~
Note: search is first performed on the reference region lines and only
after failure - on the whole neighborhood defined by `config.n_lines`. This
means that with `config.search_method` not equal to `'cover'`, "previous"
or "next" surrounding will end up as search result if they are found on
first stage although covering match might be found in bigger, whole
neighborhood. This design is based on observation that most of the time
operation is done within reference region lines (usually cursor line).
Here is an example of how replacing `)` with `]` surrounding is done based
on a value of `'config.search_method'` when cursor is inside `bbb` word:
- `'cover'`: `(a) bbb (c)` -> `(a) bbb (c)` (with message)
- `'cover_or_next'`: `(a) bbb (c)` -> `(a) bbb [c]`
- `'cover_or_prev'`: `(a) bbb (c)` -> `[a] bbb (c)`
- `'cover_or_nearest'`: depends on cursor position.
For first and second `b` - as in `cover_or_prev` (as previous match is
nearer), for third - as in `cover_or_next` (as next match is nearer).
- `'next'`: `(a) bbb (c)` -> `(a) bbb [c]`. Same outcome for `(bbb)`.
- `'prev'`: `(a) bbb (c)` -> `[a] bbb (c)`. Same outcome for `(bbb)`.
- `'nearest'`: depends on cursor position (same as in `'cover_or_nearest'`).
## Search suffixes ~
Notes:
- It creates new mappings only for actions involving surrounding search:
delete, replace, find (right and left), highlight.
- All new mappings behave the same way as if `config.search_method` is set
to certain search method. They are dot-repeatable, respect |[count]|, etc.
- Supply empty string to disable creation of corresponding set of mappings.
Example with default values (`n` for `suffix_next`, `l` for `suffix_last`)
and initial line `(aa) (bb) (cc)`.
- Typing `sdn)` with cursor inside `(aa)` results into `(aa) bb (cc)`.
- Typing `sdl)` with cursor inside `(cc)` results into `(aa) bb (cc)`.
- Typing `2srn)]` with cursor inside `(aa)` results into `(aa) (bb) [cc]`.
------------------------------------------------------------------------------
*MiniSurround.add()*
`MiniSurround.add`({mode})
Add surrounding
Parameters ~
{mode} `(string)` Mapping mode (normal by default).
------------------------------------------------------------------------------
*MiniSurround.delete()*
`MiniSurround.delete`()
Delete surrounding
------------------------------------------------------------------------------
*MiniSurround.replace()*
`MiniSurround.replace`()
Replace surrounding
------------------------------------------------------------------------------
*MiniSurround.find()*
`MiniSurround.find`()
Find surrounding
------------------------------------------------------------------------------
*MiniSurround.highlight()*
`MiniSurround.highlight`()
Highlight surrounding
------------------------------------------------------------------------------
*MiniSurround.update_n_lines()*
`MiniSurround.update_n_lines`()
Update `MiniSurround.config.n_lines`
------------------------------------------------------------------------------
*MiniSurround.user_input()*
`MiniSurround.user_input`({prompt}, {text})
Ask user for input
This is mainly a wrapper for |input()| which allows empty string as input,
cancelling with `<Esc>` and `<C-c>`, and slightly modifies prompt. Use it
to ask for input inside function custom surrounding (see |MiniSurround.config|).
------------------------------------------------------------------------------
*MiniSurround.gen_spec*
`MiniSurround.gen_spec`
Generate common surrounding specifications
This is a table with two sets of generator functions: <input> and <output>
(currently empty). Each is a table with values being function generating
corresponding surrounding specification.
Example: >
local ts_input = require('mini.surround').gen_spec.input.treesitter
require('mini.surround').setup({
custom_surroundings = {
-- Use tree-sitter to search for function call
f = {
input = ts_input({ outer = '@call.outer', inner = '@call.inner' })
},
}
})
See also ~
|MiniAi.gen_spec|
------------------------------------------------------------------------------
*MiniSurround.gen_spec.input.treesitter()*
`MiniSurround.gen_spec.input.treesitter`({captures}, {opts})
Treesitter specification for input surrounding
In order for this to work, apart from working treesitter parser for desired
language, user should have a reachable language-specific 'textobjects'
query (see |vim.treesitter.query.get()| or |get_query()|, depending on your
Neovim version).
The most straightforward way for this is to have 'textobjects.scm' query
file with treesitter captures stored in some recognized path. This is
primarily designed to be compatible with plugin
'nvim-treesitter/nvim-treesitter-textobjects', but can be used without it.
Parameters ~
{captures} `(table)` Captures for outer and inner parts of region pair:
table with <outer> and <inner> fields with captures for outer
(`[left.form; right.to]`) and inner (`(left.to; right.from)` both edges
exclusive, i.e. they won't be a part of surrounding) regions. Each value
should be a string capture starting with `'@'`.
{opts} `(table|nil)` Options. Possible values:
- <use_nvim_treesitter> - whether to try to use 'nvim-treesitter' plugin
(if present) to do the query. It implements more advanced behavior at
cost of increased execution time. Provides more coherent experience if
'nvim-treesitter-textobjects' queries are used. Default: `true`.
Return ~
`(function)` Function which returns array of current buffer region pairs
representing differences between outer and inner captures.
See also ~
|MiniSurround-surround-specification| for how this type of
surrounding specification is processed.
|get_query()| for how query is fetched in case of no 'nvim-treesitter'.
|Query:iter_captures()| for how all query captures are iterated in case of
no 'nvim-treesitter'.
|MiniAi.gen_spec.treesitter()| for similar 'mini.ai' generator.
vim:tw=78:ts=8:noet:ft=help:norl: