retrovim 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/.conda/retrovim.yaml +259 -0
  2. package/.conda/terax.icns +0 -0
  3. package/.conda/terax.ico +0 -0
  4. package/.conda/terax.png +0 -0
  5. package/.github/workflows/release.yml +95 -0
  6. package/.gitmodules +3 -0
  7. package/.npm/kanata_touchcursor.js +28 -0
  8. package/.npm/nvim.js +26 -0
  9. package/.npm/yazi.js +26 -0
  10. package/.npm/zsh.js +17 -0
  11. package/.pip/kanata_touchcursor/__init__.py +28 -0
  12. package/.pip/nvim/__init__.py +31 -0
  13. package/.pip/yazi/__init__.py +31 -0
  14. package/.pip/zsh/__init__.py +22 -0
  15. package/CHANGELOG.md +26 -0
  16. package/LICENSE +674 -0
  17. package/README.md +336 -0
  18. package/kanata/touchcursor.kbd +164 -0
  19. package/nvim/init.lua +813 -0
  20. package/nvim/plugins/mini.nvim/.github/DISCUSSION_TEMPLATE/q-a.yml +72 -0
  21. package/nvim/plugins/mini.nvim/.github/ISSUE_TEMPLATE/bug-report.yml +136 -0
  22. package/nvim/plugins/mini.nvim/.github/ISSUE_TEMPLATE/config.yml +5 -0
  23. package/nvim/plugins/mini.nvim/.github/ISSUE_TEMPLATE/feature-request.yml +75 -0
  24. package/nvim/plugins/mini.nvim/.github/PULL_REQUEST_TEMPLATE.md +2 -0
  25. package/nvim/plugins/mini.nvim/.github/workflows/quality-control.yml +150 -0
  26. package/nvim/plugins/mini.nvim/.pre-commit-config.yaml +20 -0
  27. package/nvim/plugins/mini.nvim/.stylua.toml +7 -0
  28. package/nvim/plugins/mini.nvim/.styluaignore +1 -0
  29. package/nvim/plugins/mini.nvim/CHANGELOG.md +1894 -0
  30. package/nvim/plugins/mini.nvim/CODE_OF_CONDUCT.md +132 -0
  31. package/nvim/plugins/mini.nvim/CONTRIBUTING.md +331 -0
  32. package/nvim/plugins/mini.nvim/LICENSE +21 -0
  33. package/nvim/plugins/mini.nvim/MAINTAINING.md +330 -0
  34. package/nvim/plugins/mini.nvim/Makefile +51 -0
  35. package/nvim/plugins/mini.nvim/README.md +261 -0
  36. package/nvim/plugins/mini.nvim/TESTING.md +1011 -0
  37. package/nvim/plugins/mini.nvim/benchmarks/starter/README.md +35 -0
  38. package/nvim/plugins/mini.nvim/benchmarks/starter/benchmark.sh +56 -0
  39. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_dashboard-alpha.lua +21 -0
  40. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_dashboard-original.lua +17 -0
  41. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_dashboard-starter.lua +18 -0
  42. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_empty.lua +4 -0
  43. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_starter-default.lua +7 -0
  44. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_startify-alpha.lua +10 -0
  45. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_startify-original.lua +7 -0
  46. package/nvim/plugins/mini.nvim/benchmarks/starter/init-files/init_startify-starter.lua +20 -0
  47. package/nvim/plugins/mini.nvim/benchmarks/starter/install.sh +10 -0
  48. package/nvim/plugins/mini.nvim/benchmarks/starter/make_summary.py +68 -0
  49. package/nvim/plugins/mini.nvim/benchmarks/starter/startup-summary.md +10 -0
  50. package/nvim/plugins/mini.nvim/colors/miniautumn.lua +55 -0
  51. package/nvim/plugins/mini.nvim/colors/minicyan.lua +95 -0
  52. package/nvim/plugins/mini.nvim/colors/minischeme.lua +95 -0
  53. package/nvim/plugins/mini.nvim/colors/minispring.lua +53 -0
  54. package/nvim/plugins/mini.nvim/colors/minisummer.lua +49 -0
  55. package/nvim/plugins/mini.nvim/colors/miniwinter.lua +51 -0
  56. package/nvim/plugins/mini.nvim/colors/randomhue.lua +16 -0
  57. package/nvim/plugins/mini.nvim/doc/mini-ai.txt +889 -0
  58. package/nvim/plugins/mini.nvim/doc/mini-align.txt +923 -0
  59. package/nvim/plugins/mini.nvim/doc/mini-animate.txt +937 -0
  60. package/nvim/plugins/mini.nvim/doc/mini-base16.txt +285 -0
  61. package/nvim/plugins/mini.nvim/doc/mini-basics.txt +359 -0
  62. package/nvim/plugins/mini.nvim/doc/mini-bracketed.txt +622 -0
  63. package/nvim/plugins/mini.nvim/doc/mini-bufremove.txt +123 -0
  64. package/nvim/plugins/mini.nvim/doc/mini-clue.txt +760 -0
  65. package/nvim/plugins/mini.nvim/doc/mini-cmdline.txt +392 -0
  66. package/nvim/plugins/mini.nvim/doc/mini-colors.txt +880 -0
  67. package/nvim/plugins/mini.nvim/doc/mini-comment.txt +230 -0
  68. package/nvim/plugins/mini.nvim/doc/mini-completion.txt +477 -0
  69. package/nvim/plugins/mini.nvim/doc/mini-cursorword.txt +105 -0
  70. package/nvim/plugins/mini.nvim/doc/mini-deps.txt +590 -0
  71. package/nvim/plugins/mini.nvim/doc/mini-diff.txt +661 -0
  72. package/nvim/plugins/mini.nvim/doc/mini-doc.txt +434 -0
  73. package/nvim/plugins/mini.nvim/doc/mini-extra.txt +856 -0
  74. package/nvim/plugins/mini.nvim/doc/mini-files.txt +1018 -0
  75. package/nvim/plugins/mini.nvim/doc/mini-fuzzy.txt +160 -0
  76. package/nvim/plugins/mini.nvim/doc/mini-git.txt +425 -0
  77. package/nvim/plugins/mini.nvim/doc/mini-hipatterns.txt +489 -0
  78. package/nvim/plugins/mini.nvim/doc/mini-hues.txt +420 -0
  79. package/nvim/plugins/mini.nvim/doc/mini-icons.txt +508 -0
  80. package/nvim/plugins/mini.nvim/doc/mini-indentscope.txt +485 -0
  81. package/nvim/plugins/mini.nvim/doc/mini-input.txt +932 -0
  82. package/nvim/plugins/mini.nvim/doc/mini-jump.txt +202 -0
  83. package/nvim/plugins/mini.nvim/doc/mini-jump2d.txt +525 -0
  84. package/nvim/plugins/mini.nvim/doc/mini-keymap.txt +449 -0
  85. package/nvim/plugins/mini.nvim/doc/mini-map.txt +717 -0
  86. package/nvim/plugins/mini.nvim/doc/mini-misc.txt +431 -0
  87. package/nvim/plugins/mini.nvim/doc/mini-move.txt +181 -0
  88. package/nvim/plugins/mini.nvim/doc/mini-notify.txt +434 -0
  89. package/nvim/plugins/mini.nvim/doc/mini-nvim.txt +431 -0
  90. package/nvim/plugins/mini.nvim/doc/mini-operators.txt +472 -0
  91. package/nvim/plugins/mini.nvim/doc/mini-pairs.txt +346 -0
  92. package/nvim/plugins/mini.nvim/doc/mini-pick.txt +1535 -0
  93. package/nvim/plugins/mini.nvim/doc/mini-sessions.txt +239 -0
  94. package/nvim/plugins/mini.nvim/doc/mini-snippets.txt +1291 -0
  95. package/nvim/plugins/mini.nvim/doc/mini-splitjoin.txt +536 -0
  96. package/nvim/plugins/mini.nvim/doc/mini-starter.txt +618 -0
  97. package/nvim/plugins/mini.nvim/doc/mini-statusline.txt +361 -0
  98. package/nvim/plugins/mini.nvim/doc/mini-surround.txt +863 -0
  99. package/nvim/plugins/mini.nvim/doc/mini-tabline.txt +151 -0
  100. package/nvim/plugins/mini.nvim/doc/mini-test.txt +966 -0
  101. package/nvim/plugins/mini.nvim/doc/mini-trailspace.txt +91 -0
  102. package/nvim/plugins/mini.nvim/doc/mini-visits.txt +937 -0
  103. package/nvim/plugins/mini.nvim/logo.png +0 -0
  104. package/nvim/plugins/mini.nvim/lua/mini/ai.lua +2244 -0
  105. package/nvim/plugins/mini.nvim/lua/mini/align.lua +2076 -0
  106. package/nvim/plugins/mini.nvim/lua/mini/animate.lua +2127 -0
  107. package/nvim/plugins/mini.nvim/lua/mini/base16.lua +1752 -0
  108. package/nvim/plugins/mini.nvim/lua/mini/basics.lua +772 -0
  109. package/nvim/plugins/mini.nvim/lua/mini/bracketed.lua +2013 -0
  110. package/nvim/plugins/mini.nvim/lua/mini/bufremove.lua +283 -0
  111. package/nvim/plugins/mini.nvim/lua/mini/clue.lua +2096 -0
  112. package/nvim/plugins/mini.nvim/lua/mini/cmdline.lua +1182 -0
  113. package/nvim/plugins/mini.nvim/lua/mini/colors.lua +2483 -0
  114. package/nvim/plugins/mini.nvim/lua/mini/comment.lua +586 -0
  115. package/nvim/plugins/mini.nvim/lua/mini/completion.lua +2094 -0
  116. package/nvim/plugins/mini.nvim/lua/mini/cursorword.lua +311 -0
  117. package/nvim/plugins/mini.nvim/lua/mini/deps.lua +1660 -0
  118. package/nvim/plugins/mini.nvim/lua/mini/diff.lua +1938 -0
  119. package/nvim/plugins/mini.nvim/lua/mini/doc.lua +1371 -0
  120. package/nvim/plugins/mini.nvim/lua/mini/extra.lua +2290 -0
  121. package/nvim/plugins/mini.nvim/lua/mini/files.lua +3145 -0
  122. package/nvim/plugins/mini.nvim/lua/mini/fuzzy.lua +356 -0
  123. package/nvim/plugins/mini.nvim/lua/mini/git.lua +1737 -0
  124. package/nvim/plugins/mini.nvim/lua/mini/hipatterns.lua +1042 -0
  125. package/nvim/plugins/mini.nvim/lua/mini/hues.lua +2088 -0
  126. package/nvim/plugins/mini.nvim/lua/mini/icons.lua +2254 -0
  127. package/nvim/plugins/mini.nvim/lua/mini/indentscope.lua +1158 -0
  128. package/nvim/plugins/mini.nvim/lua/mini/init.lua +427 -0
  129. package/nvim/plugins/mini.nvim/lua/mini/input.lua +2183 -0
  130. package/nvim/plugins/mini.nvim/lua/mini/jump.lua +609 -0
  131. package/nvim/plugins/mini.nvim/lua/mini/jump2d.lua +1244 -0
  132. package/nvim/plugins/mini.nvim/lua/mini/keymap.lua +880 -0
  133. package/nvim/plugins/mini.nvim/lua/mini/map.lua +1709 -0
  134. package/nvim/plugins/mini.nvim/lua/mini/misc.lua +969 -0
  135. package/nvim/plugins/mini.nvim/lua/mini/move.lua +509 -0
  136. package/nvim/plugins/mini.nvim/lua/mini/notify.lua +938 -0
  137. package/nvim/plugins/mini.nvim/lua/mini/operators.lua +1349 -0
  138. package/nvim/plugins/mini.nvim/lua/mini/pairs.lua +657 -0
  139. package/nvim/plugins/mini.nvim/lua/mini/pick.lua +3876 -0
  140. package/nvim/plugins/mini.nvim/lua/mini/sessions.lua +689 -0
  141. package/nvim/plugins/mini.nvim/lua/mini/snippets.lua +2828 -0
  142. package/nvim/plugins/mini.nvim/lua/mini/splitjoin.lua +1132 -0
  143. package/nvim/plugins/mini.nvim/lua/mini/starter.lua +1599 -0
  144. package/nvim/plugins/mini.nvim/lua/mini/statusline.lua +686 -0
  145. package/nvim/plugins/mini.nvim/lua/mini/surround.lua +2388 -0
  146. package/nvim/plugins/mini.nvim/lua/mini/tabline.lua +564 -0
  147. package/nvim/plugins/mini.nvim/lua/mini/test.lua +2516 -0
  148. package/nvim/plugins/mini.nvim/lua/mini/trailspace.lua +215 -0
  149. package/nvim/plugins/mini.nvim/lua/mini/visits.lua +1577 -0
  150. package/nvim/plugins/mini.nvim/readmes/mini-ai.md +190 -0
  151. package/nvim/plugins/mini.nvim/readmes/mini-align.md +203 -0
  152. package/nvim/plugins/mini.nvim/readmes/mini-animate.md +214 -0
  153. package/nvim/plugins/mini.nvim/readmes/mini-base16.md +198 -0
  154. package/nvim/plugins/mini.nvim/readmes/mini-basics.md +184 -0
  155. package/nvim/plugins/mini.nvim/readmes/mini-bracketed.md +193 -0
  156. package/nvim/plugins/mini.nvim/readmes/mini-bufremove.md +139 -0
  157. package/nvim/plugins/mini.nvim/readmes/mini-clue.md +260 -0
  158. package/nvim/plugins/mini.nvim/readmes/mini-cmdline.md +183 -0
  159. package/nvim/plugins/mini.nvim/readmes/mini-colors.md +169 -0
  160. package/nvim/plugins/mini.nvim/readmes/mini-comment.md +183 -0
  161. package/nvim/plugins/mini.nvim/readmes/mini-completion.md +217 -0
  162. package/nvim/plugins/mini.nvim/readmes/mini-cursorword.md +137 -0
  163. package/nvim/plugins/mini.nvim/readmes/mini-deps.md +271 -0
  164. package/nvim/plugins/mini.nvim/readmes/mini-diff.md +289 -0
  165. package/nvim/plugins/mini.nvim/readmes/mini-doc.md +198 -0
  166. package/nvim/plugins/mini.nvim/readmes/mini-extra.md +158 -0
  167. package/nvim/plugins/mini.nvim/readmes/mini-files.md +247 -0
  168. package/nvim/plugins/mini.nvim/readmes/mini-fuzzy.md +134 -0
  169. package/nvim/plugins/mini.nvim/readmes/mini-git.md +168 -0
  170. package/nvim/plugins/mini.nvim/readmes/mini-hipatterns.md +176 -0
  171. package/nvim/plugins/mini.nvim/readmes/mini-hues.md +285 -0
  172. package/nvim/plugins/mini.nvim/readmes/mini-icons.md +183 -0
  173. package/nvim/plugins/mini.nvim/readmes/mini-indentscope.md +191 -0
  174. package/nvim/plugins/mini.nvim/readmes/mini-input.md +163 -0
  175. package/nvim/plugins/mini.nvim/readmes/mini-jump.md +161 -0
  176. package/nvim/plugins/mini.nvim/readmes/mini-jump2d.md +197 -0
  177. package/nvim/plugins/mini.nvim/readmes/mini-keymap.md +205 -0
  178. package/nvim/plugins/mini.nvim/readmes/mini-map.md +191 -0
  179. package/nvim/plugins/mini.nvim/readmes/mini-misc.md +145 -0
  180. package/nvim/plugins/mini.nvim/readmes/mini-move.md +163 -0
  181. package/nvim/plugins/mini.nvim/readmes/mini-notify.md +175 -0
  182. package/nvim/plugins/mini.nvim/readmes/mini-operators.md +193 -0
  183. package/nvim/plugins/mini.nvim/readmes/mini-pairs.md +158 -0
  184. package/nvim/plugins/mini.nvim/readmes/mini-pick.md +340 -0
  185. package/nvim/plugins/mini.nvim/readmes/mini-sessions.md +164 -0
  186. package/nvim/plugins/mini.nvim/readmes/mini-snippets.md +373 -0
  187. package/nvim/plugins/mini.nvim/readmes/mini-splitjoin.md +194 -0
  188. package/nvim/plugins/mini.nvim/readmes/mini-starter.md +176 -0
  189. package/nvim/plugins/mini.nvim/readmes/mini-statusline.md +155 -0
  190. package/nvim/plugins/mini.nvim/readmes/mini-surround.md +190 -0
  191. package/nvim/plugins/mini.nvim/readmes/mini-tabline.md +156 -0
  192. package/nvim/plugins/mini.nvim/readmes/mini-test.md +175 -0
  193. package/nvim/plugins/mini.nvim/readmes/mini-trailspace.md +137 -0
  194. package/nvim/plugins/mini.nvim/readmes/mini-visits.md +243 -0
  195. package/nvim/plugins/mini.nvim/scripts/dual_log.sh +13 -0
  196. package/nvim/plugins/mini.nvim/scripts/dual_push.sh +15 -0
  197. package/nvim/plugins/mini.nvim/scripts/dual_release.sh +102 -0
  198. package/nvim/plugins/mini.nvim/scripts/dual_sync.sh +115 -0
  199. package/nvim/plugins/mini.nvim/scripts/init-deps-example.lua +59 -0
  200. package/nvim/plugins/mini.nvim/scripts/lint-filename-length.sh +16 -0
  201. package/nvim/plugins/mini.nvim/scripts/lintcommit-ci.sh +18 -0
  202. package/nvim/plugins/mini.nvim/scripts/lintcommit.lua +393 -0
  203. package/nvim/plugins/mini.nvim/scripts/minidoc.lua +57 -0
  204. package/nvim/plugins/mini.nvim/scripts/minimal_init.lua +28 -0
  205. package/nvim/plugins/mini.nvim/scripts/minitest.lua +4 -0
  206. package/package.json +16 -0
  207. package/pyproject.toml +43 -0
  208. package/yazi/init.lua +12 -0
  209. package/yazi/keymap.toml +114 -0
  210. package/yazi/lesskey +5 -0
  211. package/yazi/plugins/bookmarks.yazi/main.lua +86 -0
  212. package/yazi/plugins/cd-git-root.yazi/main.lua +31 -0
  213. package/yazi/plugins/smart-enter.yazi/main.lua +11 -0
  214. package/yazi/theme.toml +26 -0
  215. package/yazi/yazi.toml +15 -0
  216. package/zsh/.zshrc +145 -0
  217. package/zsh/starship.toml +20 -0
  218. package/zsh/zsh-patina.toml +2 -0
@@ -0,0 +1,2388 @@
1
+ --- *mini.surround* Surround actions
2
+ ---
3
+ --- MIT License Copyright (c) 2021 Evgeni Chasnovski
4
+
5
+ --- Fast and feature-rich surrounding. Can be configured to have experience
6
+ --- similar to [tpope/vim-surround](https://github.com/tpope/vim-surround)
7
+ --- (see |MiniSurround-vim-surround-config|).
8
+ ---
9
+ --- Features:
10
+ --- - Actions (text editing actions are dot-repeatable out of the box and
11
+ --- respect |[count]|) with configurable mappings:
12
+ --- - Add surrounding with `sa` (in visual mode or on motion).
13
+ --- - Delete surrounding with `sd`.
14
+ --- - Replace surrounding with `sr`.
15
+ --- - Find surrounding with `sf` or `sF` (move cursor right or left).
16
+ --- - Highlight surrounding with `sh`.
17
+ ---
18
+ --- - Surrounding is identified by a single character as both "input" (in
19
+ --- `delete` and `replace` start, `find`, and `highlight`) and "output" (in
20
+ --- `add` and `replace` end):
21
+ --- - `f` - function call (string of alphanumeric symbols or `_` or `.`
22
+ --- followed by balanced `()`). In "input" finds function call, in
23
+ --- "output" prompts user to enter function name.
24
+ --- - `t` - tag. In "input" finds tag with same identifier, in "output"
25
+ --- prompts user to enter tag name with possible attributes.
26
+ --- - All symbols in brackets `()`, `[]`, `{}`, `<>`. In "input" represents
27
+ --- balanced brackets (open - with whitespace pad, close - without), in
28
+ --- "output" - left and right parts of brackets.
29
+ --- - `?` - interactive. Prompts user to enter left and right parts.
30
+ --- - All other single character identifiers (supported by |getcharstr()|)
31
+ --- represent surrounding with identical left and right parts.
32
+ ---
33
+ --- - Configurable search methods to find not only covering but possibly next,
34
+ --- previous, or nearest surrounding. See more in |MiniSurround.config|.
35
+ ---
36
+ --- - All actions involving finding surrounding (delete, replace, find,
37
+ --- highlight) can be used with suffix that changes search method to find
38
+ --- previous/last. See more in |MiniSurround.config|.
39
+ ---
40
+ --- Known issues which won't be resolved:
41
+ --- - Search for surrounding is done using Lua patterns (regex-like approach).
42
+ --- So certain amount of false positives should be expected.
43
+ ---
44
+ --- - When searching for "input" surrounding, there is no distinction if it is
45
+ --- inside string or comment. So in this case there will be not proper match
46
+ --- for a function call: `f(a = ")", b = 1)`.
47
+ ---
48
+ --- - Tags are searched using regex-like methods, so issues are inevitable.
49
+ --- Overall it is pretty good, but certain cases won't work. Like self-nested
50
+ --- tags won't match correctly on both ends: `<a><a></a></a>`.
51
+ ---
52
+ --- # Setup ~
53
+ ---
54
+ --- This module needs a setup with `require('mini.surround').setup({})`
55
+ --- (replace `{}` with your `config` table). It will create global Lua table
56
+ --- `MiniSurround` which you can use for scripting or manually (with
57
+ --- `:lua MiniSurround.*`).
58
+ ---
59
+ --- See |MiniSurround.config| for `config` structure and default values.
60
+ ---
61
+ --- You can override runtime config settings locally to buffer inside
62
+ --- `vim.b.minisurround_config` which should have same structure as
63
+ --- `MiniSurround.config`. See |mini.nvim-buffer-local-config| for more details.
64
+ ---
65
+ --- To stop module from showing non-error feedback, set `config.silent = true`.
66
+ ---
67
+ --- # Example usage ~
68
+ ---
69
+ --- Regular mappings:
70
+ --- - `saiw)` - add (`sa`) for inner word (`iw`) parenthesis (`)`).
71
+ --- - `saiw?[[<CR>]]<CR>` - add (`sa`) for inner word (`iw`) interactive
72
+ --- surrounding (`?`): `[[` for left and `]]` for right.
73
+ --- - `2sdf` - delete (`sd`) second (`2`) surrounding function call (`f`).
74
+ --- - `sr)tdiv<CR>` - replace (`sr`) surrounding parenthesis (`)`) with tag
75
+ --- (`t`) with identifier `div` (`div<CR>` in command line prompt).
76
+ --- - `sff` - find right (`sf`) part of surrounding function call (`f`).
77
+ --- - `sh}` - highlight (`sh`) for a brief period of time surrounding curly
78
+ --- brackets (`}`).
79
+ ---
80
+ --- Extended mappings (temporary force "prev"/"next" search methods):
81
+ --- - `sdnf` - delete (`sd`) next (`n`) function call (`f`).
82
+ --- - `srlf(` - replace (`sr`) last (`l`) function call (`f`) with padded
83
+ --- bracket (`(`).
84
+ --- - `2sfnt` - find (`sf`) second (`2`) next (`n`) tag (`t`).
85
+ --- - `2shl}` - highlight (`sh`) last (`l`) second (`2`) curly bracket (`}`).
86
+ ---
87
+ --- # Comparisons ~
88
+ ---
89
+ --- - [tpope/vim-surround](https://github.com/tpope/vim-surround):
90
+ --- - `vim-surround` has completely different, with other focus set of
91
+ --- default mappings, while |mini.surround| has a more coherent set.
92
+ --- - |mini.surround| supports dot-repeat, customized search path (see
93
+ --- |MiniSurround.config|), customized specifications (see
94
+ --- |MiniSurround-surrounding-specification|) allowing usage of tree-sitter
95
+ --- queries (see |MiniSurround.gen_spec.input.treesitter()|),
96
+ --- highlighting and finding surrounding, "last"/"next" extended
97
+ --- mappings. While `vim-surround` does not.
98
+ --- - [machakann/vim-sandwich](https://github.com/machakann/vim-sandwich):
99
+ --- - Both have same keybindings for common actions (add, delete, replace).
100
+ --- - Otherwise same differences as with `tpope/vim-surround` (except
101
+ --- dot-repeat because `vim-sandwich` supports it).
102
+ --- - [kylechui/nvim-surround](https://github.com/kylechui/nvim-surround):
103
+ --- - `nvim-surround` is designed after `tpope/vim-surround` with same
104
+ --- default mappings and logic, while |mini.surround| has mappings
105
+ --- similar to `machakann/vim-sandwich`.
106
+ --- - |mini.surround| has more flexible customization of input surrounding
107
+ --- (with composed patterns, region pair(s), search methods).
108
+ --- - |mini.surround| supports |[count]| in both input and output
109
+ --- surrounding (see |MiniSurround-count-with-actions|) while
110
+ --- `nvim-surround` doesn't.
111
+ --- - |mini.surround| supports "last"/"next" extended mappings.
112
+ --- - |mini.ai|:
113
+ --- - Both use similar logic for finding target: textobject in |mini.ai|
114
+ --- and surrounding pair in |mini.surround|. While |mini.ai| uses
115
+ --- extraction pattern for separate `a` and `i` textobjects,
116
+ --- |mini.surround| uses it to select left and right surroundings
117
+ --- (basically a difference between `a` and `i` textobjects).
118
+ --- - Some builtin specifications are slightly different:
119
+ --- - Quotes in |mini.ai| are balanced, in |mini.surround| they are not.
120
+ --- - The |mini.surround| doesn't have argument surrounding.
121
+ --- - Default behavior in |mini.ai| selects one of the edges into `a`
122
+ --- textobject, while |mini.surround| - both.
123
+ ---
124
+ --- # Highlight groups ~
125
+ --- *MiniSurround-hl-groups*
126
+ ---
127
+ --- - `MiniSurround` - highlighting of requested surrounding.
128
+ ---
129
+ --- To change any highlight group, set it directly with |nvim_set_hl()|.
130
+ ---
131
+ --- # Disabling ~
132
+ ---
133
+ --- To disable, set `vim.g.minisurround_disable` (globally) or
134
+ --- `vim.b.minisurround_disable` (for a buffer) to `true`. Considering high
135
+ --- number of different scenarios and customization intentions, writing exact
136
+ --- rules for disabling module's functionality is left to user. See
137
+ --- |mini.nvim-disabling-recipes| for common recipes.
138
+ ---@tag MiniSurround
139
+
140
+ --- This table describes all builtin surroundings along with what they
141
+ --- represent. Explanation:
142
+ --- - `Key` represents the surrounding identifier: single character which should
143
+ --- be typed after action mappings (see "Mappings" in |MiniSurround.config|).
144
+ --- - `Name` is a description of surrounding.
145
+ --- - `Example line` contains a string for which examples are constructed. The
146
+ --- `*` denotes the cursor position over `a` character.
147
+ --- - `Delete` shows the result of typing `sd` followed by surrounding identifier.
148
+ --- It aims to demonstrate "input" surrounding which is also used in replace
149
+ --- with `sr` (surrounding id is typed first), highlight with `sh`, find with
150
+ --- `sf` and `sF`.
151
+ --- - `Replace` shows the result of typing `sr!` followed by surrounding
152
+ --- identifier (with possible follow up from user). It aims to demonstrate
153
+ --- "output" surrounding which is also used in adding with `sa` (followed by
154
+ --- textobject/motion or in Visual mode).
155
+ ---
156
+ --- Example: typing `sd)` with cursor on `*` (covers `a` character) changes line
157
+ --- `!( *a (bb) )!` into `! aa (bb) !`. Typing `sr!)` changes same initial line
158
+ --- into `(( aa (bb) ))`.
159
+ --- >
160
+ --- ┌───┬───────────────┬───────────────┬─────────────┬─────────────────┐
161
+ --- │Key│ Name │ Example line │ Delete │ Replace │
162
+ --- ├───┴───────────────┴───────────────┴─────────────┴─────────────────┤
163
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
164
+ --- │ ( │ Balanced () │ !( *a (bb) )! │ !aa (bb)! │ ( ( aa (bb) ) ) │
165
+ --- │ [ │ Balanced [] │ ![ *a [bb] ]! │ !aa [bb]! │ [ [ aa [bb] ] ] │
166
+ --- │ { │ Balanced {} │ !{ *a {bb} }! │ !aa {bb}! │ { { aa {bb} } } │
167
+ --- │ < │ Balanced <> │ !< *a <bb> >! │ !aa <bb>! │ < < aa <bb> > > │
168
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
169
+ --- │ ) │ Balanced () │ !( *a (bb) )! │ ! aa (bb) ! │ (( aa (bb) )) │
170
+ --- │ ] │ Balanced [] │ ![ *a [bb] ]! │ ! aa [bb] ! │ [[ aa [bb] ]] │
171
+ --- │ } │ Balanced {} │ !{ *a {bb} }! │ ! aa {bb} ! │ {{ aa {bb} }} │
172
+ --- │ > │ Balanced <> │ !< *a <bb> >! │ ! aa <bb> ! │ << aa <bb> >> │
173
+ --- │ b │ Alias for │ !( *a {bb} )! │ ! aa {bb} ! │ (( aa {bb} )) │
174
+ --- │ │ ), ], or } │ │ │ │
175
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
176
+ --- │ q │ Alias for │ !'aa'*a'aa'! │ !'aaaaaa'! │ "'aa'aa'aa'" │
177
+ --- │ │ ", ', or ` │ │ │ │
178
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
179
+ --- │ ? │ User prompt │ !e * o! │ ! a ! │ ee a oo │
180
+ --- │ │(typed e and o)│ │ │ │
181
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
182
+ --- │ t │ Tag │ !<x>*</x>! │ !a! │ <y><x>a</x></y> │
183
+ --- │ │ │ │ │ (typed y) │
184
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
185
+ --- │ f │ Function call │ !f(*a, bb)! │ !aa, bb! │ g(f(*a, bb)) │
186
+ --- │ │ │ │ │ (typed g) │
187
+ --- ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┤
188
+ --- │ │ Default │ !_a*a_! │ !aaa! │ __aaa__ │
189
+ --- │ │ (typed _) │ │ │ │
190
+ --- └┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┘
191
+ --- <
192
+ --- Notes:
193
+ --- - All examples assume default `config.search_method`.
194
+ --- - Open brackets differ from close brackets by how they treat inner edge
195
+ --- whitespace: open includes it left and right parts, close does not.
196
+ --- - Output value of `b` alias is same as `)`. For `q` alias - same as `"`.
197
+ --- - Default surrounding is activated for all characters which are not
198
+ --- configured surrounding identifiers. Notes:
199
+ --- - Due to special handling of underlying `x.-x` Lua pattern
200
+ --- (see |MiniSurround-search-algorithm|), it doesn't really support
201
+ --- non-trivial `[count]` for "cover" search method.
202
+ --- - When cursor is exactly on the identifier character while there are
203
+ --- two matching candidates on both left and right, the one resulting in
204
+ --- region with smaller width is preferred.
205
+ ---@tag MiniSurround-builtin-surroundings
206
+
207
+ --- Note: this is similar to |MiniAi-glossary|.
208
+ ---
209
+ --- REGION ~
210
+ --- Table representing region in a buffer. Fields: <from> and <to> for
211
+ --- inclusive start and end positions (<to> might be `nil` to describe empty
212
+ --- region). Each position is also a table with line <line> and column <col>
213
+ --- (both start at 1). Examples: >lua
214
+ ---
215
+ --- { from = { line = 1, col = 1 }, to = { line = 2, col = 1 } }
216
+ ---
217
+ --- -- Empty region
218
+ --- { from = { line = 10, col = 10 } }
219
+ --- <
220
+ --- REGION PAIR ~
221
+ --- Table representing regions for left and right surroundings. Fields: <left>
222
+ --- and <right> with regions. Example: >lua
223
+ ---
224
+ --- {
225
+ --- left = { from = { line = 1, col = 1 }, to = { line = 1, col = 1 } },
226
+ --- right = { from = { line = 1, col = 3 } },
227
+ --- }
228
+ --- <
229
+ --- PATTERN ~
230
+ --- String describing Lua pattern.
231
+ ---
232
+ --- SPAN ~
233
+ --- Interval inside a string (end-exclusive). Like [1, 5). Equal `from` and `to` edges
234
+ --- describe empty span at that point.
235
+ ---
236
+ --- Span `A = [a1, a2)` covers `B = [b1, b2)` if every element of `B` is within
237
+ --- `A` (`a1 <= b < a2`). It also is described as "B is nested inside A".
238
+ ---
239
+ --- NESTED PATTERN ~
240
+ --- Array of patterns aimed to describe nested spans.
241
+ ---
242
+ --- SPAN MATCHES NESTED PATTERN ~
243
+ --- If there is a sequence of consecutively nested spans each matching
244
+ --- corresponding pattern within substring of previous span (or input string
245
+ --- for first span). Example: >lua
246
+ ---
247
+ --- -- Nested patterns for balanced `()` with inner space
248
+ --- { '%b()', '^. .* .$' }
249
+ ---
250
+ --- -- Example input string (with columns underneath for easier reading):
251
+ --- "( ( () ( ) ) )"
252
+ --- -- 12345678901234
253
+ --- <
254
+ --- Here are all matching spans [1, 15) and [3, 13). Both [5, 7) and [8, 10)
255
+ --- match first pattern but not second. All other combinations of `(` and `)`
256
+ --- don't match first pattern (not balanced).
257
+ ---
258
+ --- COMPOSED PATTERN ~
259
+ --- Array with each element describing possible pattern (or array of them) at
260
+ --- that place. Composed pattern basically defines all possible combinations of
261
+ --- nested pattern (their cartesian product). Examples:
262
+ ---
263
+ --- 1. Either balanced `()` or balanced `[]` but both with inner edge space: >lua
264
+ ---
265
+ --- -- Composed pattern
266
+ --- { { '%b()', '%b[]' }, '^. .* .$' }
267
+ ---
268
+ --- -- Composed pattern expanded into equivalent array of nested patterns
269
+ --- { '%b()', '^. .* .$' } -- and
270
+ --- { '%b[]', '^. .* .$' }
271
+ --- <
272
+ --- 2. Either "balanced `()` with inner edge space" or "balanced `[]` with no
273
+ --- inner edge space", both with 5 or more characters: >lua
274
+ ---
275
+ --- -- Composed pattern
276
+ --- { { { '%b()', '^. .* .$' }, { '%b[]', '^.[^ ].*[^ ].$' } }, '.....' }
277
+ ---
278
+ --- -- Composed pattern expanded into equivalent array of nested patterns
279
+ --- { '%b()', '^. .* .$', '.....' } -- and
280
+ --- { '%b[]', '^.[^ ].*[^ ].$', '.....' }
281
+ --- <
282
+ --- SPAN MATCHES COMPOSED PATTERN ~
283
+ --- If it matches at least one nested pattern from expanded composed pattern.
284
+ ---@tag MiniSurround-glossary
285
+
286
+ --- Surround specification is a table with keys:
287
+ --- - <input> - defines how to find and extract surrounding for "input"
288
+ --- operations (like `delete`). See more in "Input surrounding" section.
289
+ --- - <output> - defines what to add on left and right for "output" operations
290
+ --- (like `add`). See more in "Output surrounding" section.
291
+ ---
292
+ --- Example of surround info for builtin `)` identifier: >lua
293
+ ---
294
+ --- {
295
+ --- input = { '%b()', '^.().*().$' },
296
+ --- output = { left = '(', right = ')' }
297
+ --- }
298
+ --- <
299
+ --- # Input surrounding ~
300
+ ---
301
+ --- Specification for input surrounding has a structure of composed pattern
302
+ --- (see |MiniSurround-glossary|) with two differences:
303
+ --- - Last pattern(s) should have two or four empty capture groups denoting
304
+ --- how the last string should be processed to extract surrounding parts:
305
+ --- - Two captures represent left part from start of string to first
306
+ --- capture and right part - from second capture to end of string.
307
+ --- Example: `a()b()c` defines left surrounding as `a`, right - `c`.
308
+ --- - Four captures define left part inside captures 1 and 2, right part -
309
+ --- inside captures 3 and 4. Example: `a()()b()c()` defines left part as
310
+ --- empty, right part as `c`.
311
+ --- - Allows callable objects (see |vim.is_callable()|) in certain places
312
+ --- (enables more complex surroundings in exchange of increase in configuration
313
+ --- complexity and computations):
314
+ --- - If specification itself is a callable, it will be called without
315
+ --- arguments and should return one of:
316
+ --- - Composed pattern. Useful for implementing user input. Example of
317
+ --- simplified variant of input surrounding for function call with
318
+ --- name taken from user prompt: >lua
319
+ ---
320
+ --- function()
321
+ --- local left_edge = vim.pesc(vim.fn.input('Function name: '))
322
+ --- return { left_edge .. '%b()', '^.-%(().*()%)$' }
323
+ --- end
324
+ --- <
325
+ --- - Single region pair (see |MiniSurround-glossary|). Useful to allow
326
+ --- full control over surrounding. Will be taken as is. Example of
327
+ --- returning first and last lines of a buffer: >lua
328
+ ---
329
+ --- function()
330
+ --- local n_lines = vim.fn.line('$')
331
+ --- return {
332
+ --- left = {
333
+ --- from = { line = 1, col = 1 },
334
+ --- to = { line = 1, col = vim.fn.getline(1):len() }
335
+ --- },
336
+ --- right = {
337
+ --- from = { line = n_lines, col = 1 },
338
+ --- to = { line = n_lines, col = vim.fn.getline(n_lines):len() }
339
+ --- },
340
+ --- }
341
+ --- end
342
+ --- <
343
+ --- - Array of region pairs. Useful for incorporating other instruments,
344
+ --- like treesitter (see |MiniSurround.gen_spec.input.treesitter()|). The
345
+ --- best region pair will be picked in the same manner as with composed
346
+ --- pattern (respecting options `n_lines`, `search_method`, etc.) using
347
+ --- output region (from start of left region to end of right region).
348
+ --- Example using edges of "best" line with display width more than 80: >lua
349
+ ---
350
+ --- function()
351
+ --- local make_line_region_pair = function(n)
352
+ --- local left = { line = n, col = 1 }
353
+ --- local right = { line = n, col = vim.fn.getline(n):len() }
354
+ --- return {
355
+ --- left = { from = left, to = left },
356
+ --- right = { from = right, to = right },
357
+ --- }
358
+ --- end
359
+ ---
360
+ --- local res = {}
361
+ --- for i = 1, vim.fn.line('$') do
362
+ --- if vim.fn.getline(i):len() > 80 then
363
+ --- table.insert(res, make_line_region_pair(i))
364
+ --- end
365
+ --- end
366
+ --- return res
367
+ --- end
368
+ --- <
369
+ --- - If there is a callable instead of assumed string pattern, it is expected
370
+ --- to have signature `(line, init)` and behave like `pattern:find()`.
371
+ --- It should return two numbers representing span in `line` next after
372
+ --- or at `init` (`nil` if there is no such span).
373
+ --- !IMPORTANT NOTE!: it means that output's `from` shouldn't be strictly
374
+ --- to the left of `init` (it will lead to infinite loop). Not allowed as
375
+ --- last item (as it should be pattern with captures).
376
+ --- Example of matching only balanced parenthesis with big enough width: >lua
377
+ ---
378
+ --- {
379
+ --- '%b()',
380
+ --- function(s, init)
381
+ --- if init > 1 or s:len() < 5 then return end
382
+ --- return 1, s:len()
383
+ --- end,
384
+ --- '^.().*().$'
385
+ --- }
386
+ --- <
387
+ --- More examples: >lua
388
+ ---
389
+ --- -- Pair of balanced brackets from set (used for builtin `b` identifier)
390
+ --- { { '%b()', '%b[]', '%b{}' }, '^.().*().$' }
391
+ ---
392
+ --- -- Lua block string
393
+ --- { '%[%[().-()%]%]' }
394
+ --- <
395
+ --- See |MiniSurround.gen_spec| for function wrappers to create commonly used
396
+ --- surrounding specifications.
397
+ ---
398
+ --- # Output surrounding ~
399
+ ---
400
+ --- Specification for output can be either a table with <left> and <right> fields,
401
+ --- or a callable returning such table (will be called with no arguments).
402
+ --- Strings can contain new lines character "\n" to add multiline parts.
403
+ ---
404
+ --- Examples: >lua
405
+ ---
406
+ --- -- Lua block string
407
+ --- { left = '[[', right = ']]' }
408
+ ---
409
+ --- -- Brackets on separate lines (indentation is not preserved)
410
+ --- { left = '(\n', right = '\n)' }
411
+ ---
412
+ --- -- Function call
413
+ --- function()
414
+ --- local function_name = MiniSurround.user_input('Function name')
415
+ --- return { left = function_name .. '(', right = ')' }
416
+ --- end
417
+ --- <
418
+ ---@tag MiniSurround-surrounding-specification
419
+
420
+ --- |[count]| is supported by all actions in the following ways:
421
+ ---
422
+ --- - In add, two types of `[count]` is supported in Normal mode:
423
+ --- `[count1]sa[count2][textobject]`. The `[count1]` defines how many times
424
+ --- left and right parts of output surrounding will be repeated and `[count2]` is
425
+ --- used for textobject.
426
+ --- In Visual mode `[count]` is treated as `[count1]`.
427
+ --- Example: `2sa3aw)` and `v3aw2sa)` will result into textobject `3aw` being
428
+ --- surrounded by `((` and `))`.
429
+ ---
430
+ --- - In delete/replace/find/highlight `[count]` means "find n-th surrounding
431
+ --- and execute operator on it".
432
+ --- Example: `2sd)` on line `(a(b(c)b)a)` with cursor on `c` will result into
433
+ --- `(ab(c)ba)` (and not in `(abcba)` if it would have meant "delete n times").
434
+ ---@tag MiniSurround-count-with-actions
435
+
436
+ --- Search for the input surrounding relies on these principles:
437
+ --- - Input surrounding specification is constructed based on surrounding
438
+ --- identifier (see |MiniSurround-surrounding-specification|).
439
+ --- - General search is done by converting some 2d buffer region (neighborhood
440
+ --- of reference region) into 1d string (each line is appended with `\n`).
441
+ --- Then search for a best span matching specification is done inside string
442
+ --- (see |MiniSurround-glossary|). After that, span is converted back into 2d
443
+ --- region. Note: first search is done inside reference region lines, and
444
+ --- only after that - inside its neighborhood within `config.n_lines` (see
445
+ --- |MiniSurround.config|).
446
+ --- - The best matching span is chosen by iterating over all spans matching
447
+ --- surrounding specification and comparing them with "current best".
448
+ --- Comparison also depends on reference region (tighter covering is better,
449
+ --- otherwise closer is better) and search method (if span is even considered).
450
+ --- - Extract pair of spans (for left and right regions in region pair) based
451
+ --- on extraction pattern (last item in nested pattern).
452
+ --- - For |[count]| greater than 1, steps are repeated with current best match
453
+ --- becoming reference region. One such additional step is also done if final
454
+ --- region is equal to reference region.
455
+ ---
456
+ --- Notes:
457
+ --- - Iteration over all matched spans is done in depth-first fashion with
458
+ --- respect to nested pattern.
459
+ --- - It is guaranteed that span is compared only once.
460
+ --- - For the sake of increasing functionality, during iteration over all
461
+ --- matching spans, some Lua patterns in composed pattern are handled
462
+ --- specially.
463
+ --- - `%bxx` (`xx` is two identical characters). It denotes balanced pair
464
+ --- of identical characters and results into "paired" matches. For
465
+ --- example, `%b""` for `"aa" "bb"` would match `"aa"` and `"bb"`, but
466
+ --- not middle `" "`.
467
+ --- - `x.-y` (`x` and `y` are different strings). It results only in matches with
468
+ --- smallest width. For example, `e.-o` for `e e o o` will result only in
469
+ --- middle `e o`. Note: it has some implications for when parts have
470
+ --- quantifiers (like `+`, etc.), which usually can be resolved with
471
+ --- frontier pattern `%f[]`.
472
+ ---@tag MiniSurround-search-algorithm
473
+
474
+ -- Module definition ==========================================================
475
+ local MiniSurround = {}
476
+ local H = {}
477
+
478
+ --- Module setup
479
+ ---
480
+ ---@param config table|nil Module config table. See |MiniSurround.config|.
481
+ ---
482
+ ---@usage >lua
483
+ --- require('mini.surround').setup() -- use default config
484
+ --- -- OR
485
+ --- require('mini.surround').setup({}) -- replace {} with your config table
486
+ --- <
487
+ MiniSurround.setup = function(config)
488
+ -- TODO: Remove after Neovim=0.9 support is dropped
489
+ if vim.fn.has('nvim-0.10') == 0 then
490
+ vim.notify(
491
+ '(mini.surround) Neovim<0.10 is soft deprecated (module works but is not supported).'
492
+ .. " It will be deprecated after the next 'mini.nvim' release (module might not work)."
493
+ .. ' Please update your Neovim version.'
494
+ )
495
+ end
496
+
497
+ -- Export module
498
+ _G.MiniSurround = MiniSurround
499
+
500
+ -- Setup config
501
+ config = H.setup_config(config)
502
+
503
+ -- Apply config
504
+ H.apply_config(config)
505
+
506
+ -- Define behavior
507
+ H.create_autocommands()
508
+
509
+ -- Create default highlighting
510
+ H.create_default_hl()
511
+ end
512
+
513
+ --- Defaults ~
514
+ ---@eval return MiniDoc.afterlines_to_code(MiniDoc.current.eval_section)
515
+ ---@text # Mappings ~
516
+ ---
517
+ --- `config.mappings` defines what mappings are set up for particular actions.
518
+ --- By default it uses "prefix style" left hand side starting with "s" (for
519
+ --- "surround"): `sa` - "surround add", `sd` - "surround delete", etc.
520
+ ---
521
+ --- Note: if any of the mappings start with "s" (as is by default), it is mapped
522
+ --- to |<Nop>| to prevent accidental trigger of built-in |s| (can happen if there
523
+ --- is a long enough delay between pressing "s" and the next key). Use `cl` instead.
524
+ ---
525
+ --- # Custom surroundings ~
526
+ ---
527
+ --- User can define own surroundings by supplying `config.custom_surroundings`.
528
+ --- It should be a table with keys being single character surrounding
529
+ --- identifier (supported by |getcharstr()|) and values - surround specification
530
+ --- (see |MiniSurround-surrounding-specification|).
531
+ ---
532
+ --- General recommendations:
533
+ --- - In `config.custom_surroundings` only some data can be defined (like only
534
+ --- `output`). Other fields will be taken from builtin surroundings.
535
+ --- - Function returning surround info at <input> or <output> fields of
536
+ --- specification is helpful when user input is needed (like asking for
537
+ --- function name). Use |MiniSurround.user_input()| or |MiniInput.get()|.
538
+ --- Return `nil` to stop any current surround operation.
539
+ --- - Keys should use character representation which can be |getcharstr()| output.
540
+ --- For example, `'\r'` and not `'<CR>'`.
541
+ ---
542
+ --- Examples of using `config.custom_surroundings` (see more examples at
543
+ --- |MiniSurround.gen_spec|): >lua
544
+ ---
545
+ --- local surround = require('mini.surround')
546
+ --- surround.setup({
547
+ --- custom_surroundings = {
548
+ --- -- Make `)` insert parts with spaces. `input` pattern stays the same.
549
+ --- [')'] = { output = { left = '( ', right = ' )' } },
550
+ ---
551
+ --- -- Use function to compute surrounding info
552
+ --- ['*'] = {
553
+ --- input = function()
554
+ --- local n_star = MiniSurround.user_input('Number of * to find')
555
+ --- local many_star = string.rep('%*', tonumber(n_star) or 1)
556
+ --- return { many_star .. '().-()' .. many_star }
557
+ --- end,
558
+ --- output = function()
559
+ --- local n_star = MiniSurround.user_input('Number of * to output')
560
+ --- local many_star = string.rep('*', tonumber(n_star) or 1)
561
+ --- return { left = many_star, right = many_star }
562
+ --- end,
563
+ --- },
564
+ --- },
565
+ --- })
566
+ ---
567
+ --- -- Create custom surrounding for Lua's block string `[[...]]`
568
+ --- -- Use this inside autocommand or 'after/ftplugin/lua.lua' file
569
+ --- vim.b.minisurround_config = {
570
+ --- custom_surroundings = {
571
+ --- s = {
572
+ --- input = { '%[%[().-()%]%]' },
573
+ --- output = { left = '[[', right = ']]' },
574
+ --- },
575
+ --- },
576
+ --- }
577
+ --- <
578
+ --- # Respect selection type ~
579
+ ---
580
+ --- Boolean option `config.respect_selection_type` controls whether to respect
581
+ --- selection type when adding and deleting surrounding. When enabled:
582
+ --- - Linewise adding places surroundings on separate lines while indenting
583
+ --- surrounded lines ones.
584
+ --- - Deleting surroundings which look like they were the result of linewise
585
+ --- adding will act to revert it: delete lines with surroundings and dedent
586
+ --- surrounded lines ones.
587
+ --- - Blockwise adding places surroundings on whole edges, not only start and
588
+ --- end of selection. Note: it doesn't really work outside of text and in
589
+ --- presence of multibyte characters; and probably won't due to
590
+ --- implementation difficulties.
591
+ ---
592
+ --- # Search method ~
593
+ ---
594
+ --- Value of `config.search_method` defines how best match search is done.
595
+ --- Based on its value, one of the following matches will be selected:
596
+ --- - Covering match. Left/right edge is before/after left/right edge of
597
+ --- reference region.
598
+ --- - Previous match. Left/right edge is before left/right edge of reference
599
+ --- region.
600
+ --- - Next match. Left/right edge is after left/right edge of reference region.
601
+ --- - Nearest match. Whichever is closest among previous and next matches.
602
+ ---
603
+ --- Possible values are:
604
+ --- - `'cover'` (default) - use only covering match. Don't use either previous or
605
+ --- next; report that there is no surrounding found.
606
+ --- - `'cover_or_next'` - use covering match. If not found, use next.
607
+ --- - `'cover_or_prev'` - use covering match. If not found, use previous.
608
+ --- - `'cover_or_nearest'` - use covering match. If not found, use nearest.
609
+ --- - `'next'` - use next match.
610
+ --- - `'previous'` - use previous match.
611
+ --- - `'nearest'` - use nearest match.
612
+ ---
613
+ --- Note: search is first performed on the reference region lines and only
614
+ --- after failure - on the whole neighborhood defined by `config.n_lines`. This
615
+ --- means that with `config.search_method` not equal to `'cover'`, "previous"
616
+ --- or "next" surrounding will end up as search result if they are found on
617
+ --- first stage although covering match might be found in bigger, whole
618
+ --- neighborhood. This design is based on observation that most of the time
619
+ --- operation is done within reference region lines (usually cursor line).
620
+ ---
621
+ --- Here is an example of how replacing `)` with `]` surrounding is done based
622
+ --- on a value of `'config.search_method'` when cursor is inside `bbb` word:
623
+ --- - `'cover'`: `(a) bbb (c)` -> `(a) bbb (c)` (with message)
624
+ --- - `'cover_or_next'`: `(a) bbb (c)` -> `(a) bbb [c]`
625
+ --- - `'cover_or_prev'`: `(a) bbb (c)` -> `[a] bbb (c)`
626
+ --- - `'cover_or_nearest'`: depends on cursor position.
627
+ --- For first and second `b` - as in `cover_or_prev` (as previous match is
628
+ --- nearer), for third - as in `cover_or_next` (as next match is nearer).
629
+ --- - `'next'`: `(a) bbb (c)` -> `(a) bbb [c]`. Same outcome for `(bbb)`.
630
+ --- - `'prev'`: `(a) bbb (c)` -> `[a] bbb (c)`. Same outcome for `(bbb)`.
631
+ --- - `'nearest'`: depends on cursor position (same as in `'cover_or_nearest'`).
632
+ ---
633
+ --- # Search suffixes ~
634
+ ---
635
+ --- To provide more searching possibilities, |mini.surround| creates extended
636
+ --- mappings force "prev" and "next" methods for particular search. It does so
637
+ --- by appending mapping with certain suffix: `config.mappings.suffix_last` for
638
+ --- mappings which will use "prev" search method, `config.mappings.suffix_next`
639
+ --- - "next" search method.
640
+ ---
641
+ --- Notes:
642
+ --- - It creates new mappings only for actions involving surrounding search:
643
+ --- delete, replace, find (right and left), highlight.
644
+ --- - All new mappings behave the same way as if `config.search_method` is set
645
+ --- to certain search method. They preserve dot-repeat support, respect |[count]|.
646
+ --- - Supply empty string to disable creation of corresponding set of mappings.
647
+ ---
648
+ --- Example with default values (`n` for `suffix_next`, `l` for `suffix_last`)
649
+ --- and initial line `(aa) (bb) (cc)`.
650
+ --- - Typing `sdn)` with cursor inside `(aa)` results into `(aa) bb (cc)`.
651
+ --- - Typing `sdl)` with cursor inside `(cc)` results into `(aa) bb (cc)`.
652
+ --- - Typing `2srn)]` with cursor inside `(aa)` results into `(aa) (bb) [cc]`.
653
+ ---
654
+ --- # Setup similar to `tpope/vim-surround` ~
655
+ --- *MiniSurround-vim-surround-config*
656
+ ---
657
+ --- This module is primarily designed after `machakann/vim-sandwich`. To get
658
+ --- behavior closest to `tpope/vim-surround` (but not identical), use this setup: >lua
659
+ ---
660
+ --- require('mini.surround').setup({
661
+ --- mappings = {
662
+ --- add = 'ys',
663
+ --- delete = 'ds',
664
+ --- find = '',
665
+ --- find_left = '',
666
+ --- highlight = '',
667
+ --- replace = 'cs',
668
+ ---
669
+ --- -- Add this only if you don't want to use extended mappings
670
+ --- suffix_last = '',
671
+ --- suffix_next = '',
672
+ --- },
673
+ --- search_method = 'cover_or_next',
674
+ --- })
675
+ ---
676
+ --- -- Remap adding surrounding to Visual mode selection
677
+ --- vim.keymap.del('x', 'ys')
678
+ --- vim.keymap.set('x', 'S', [[:<C-u>lua MiniSurround.add('visual')<CR>]], { silent = true })
679
+ ---
680
+ --- -- Make special mapping for "add surrounding for line"
681
+ --- vim.keymap.set('n', 'yss', 'ys_', { remap = true })
682
+ --- <
683
+ MiniSurround.config = {
684
+ -- Add custom surroundings to be used on top of builtin ones. For more
685
+ -- information with examples, see `:h MiniSurround.config`.
686
+ custom_surroundings = nil,
687
+
688
+ -- Duration (in ms) of highlight when calling `MiniSurround.highlight()`
689
+ highlight_duration = 500,
690
+
691
+ -- Module mappings. Use `''` (empty string) to disable one.
692
+ mappings = {
693
+ add = 'sa', -- Add surrounding in Normal and Visual modes
694
+ delete = 'sd', -- Delete surrounding
695
+ find = 'sf', -- Find surrounding (to the right)
696
+ find_left = 'sF', -- Find surrounding (to the left)
697
+ highlight = 'sh', -- Highlight surrounding
698
+ replace = 'sr', -- Replace surrounding
699
+
700
+ suffix_last = 'l', -- Suffix to search with "prev" method
701
+ suffix_next = 'n', -- Suffix to search with "next" method
702
+ },
703
+
704
+ -- Number of lines within which surrounding is searched
705
+ n_lines = 20,
706
+
707
+ -- Whether to respect selection type:
708
+ -- - Place surroundings on separate lines in linewise mode.
709
+ -- - Place surroundings on each line in blockwise mode.
710
+ respect_selection_type = false,
711
+
712
+ -- How to search for surrounding (first inside current line, then inside
713
+ -- neighborhood). One of 'cover', 'cover_or_next', 'cover_or_prev',
714
+ -- 'cover_or_nearest', 'next', 'prev', 'nearest'. For more details,
715
+ -- see `:h MiniSurround.config`.
716
+ search_method = 'cover',
717
+
718
+ -- Whether to disable showing non-error feedback
719
+ -- This also affects (purely informational) helper messages shown after
720
+ -- idle time if user input is required.
721
+ silent = false,
722
+ }
723
+ --minidoc_afterlines_end
724
+
725
+ -- Module functionality =======================================================
726
+ --- Add surrounding
727
+ ---
728
+ --- No need to use it directly, everything is setup in |MiniSurround.setup()|.
729
+ ---
730
+ ---@param mode string Mapping mode (normal by default).
731
+ MiniSurround.add = function(mode)
732
+ -- Needed to disable in visual mode
733
+ if H.is_disabled() then return '<Esc>' end
734
+
735
+ -- Get marks' positions based on current mode
736
+ local marks = H.get_marks_pos(mode)
737
+
738
+ -- Get surround info. Try take from cache only in not visual mode (as there
739
+ -- is no intended dot-repeatability).
740
+ local surr_info
741
+ if mode == 'visual' then
742
+ surr_info = H.get_surround_spec('output', false)
743
+ else
744
+ surr_info = H.get_surround_spec('output', true)
745
+ end
746
+ if surr_info == nil then return '<Esc>' end
747
+
748
+ -- Extend parts based on provided `[count]` before operator (if this is not
749
+ -- from dot-repeat and was done already)
750
+ if not surr_info.did_count then
751
+ local count = H.cache.count or vim.v.count1
752
+ surr_info.left, surr_info.right = surr_info.left:rep(count), surr_info.right:rep(count)
753
+ surr_info.did_count = true
754
+ end
755
+
756
+ -- Add surrounding.
757
+ -- Possibly deal with linewise and blockwise addition separately
758
+ local respect_selection_type = H.get_config().respect_selection_type
759
+
760
+ if not respect_selection_type or marks.selection_type == 'charwise' then
761
+ -- Begin insert from right to not break column numbers
762
+ -- Insert after the right mark (`+ 1` is for that)
763
+ H.region_replace({ from = { line = marks.second.line, col = marks.second.col + 1 } }, surr_info.right)
764
+ H.region_replace({ from = marks.first }, surr_info.left)
765
+
766
+ -- Set cursor to be on the right of left surrounding
767
+ H.set_cursor(marks.first.line, marks.first.col + surr_info.left:len())
768
+
769
+ return
770
+ end
771
+
772
+ if marks.selection_type == 'linewise' then
773
+ local from_line, to_line = marks.first.line, marks.second.line
774
+
775
+ -- Save current range indent and indent surrounded lines
776
+ local init_indent = H.get_range_indent(from_line, to_line)
777
+ H.shift_indent('>', from_line, to_line)
778
+
779
+ -- Put cursor on the start of first surrounded line
780
+ H.set_cursor_nonblank(from_line)
781
+
782
+ -- Put surroundings on separate lines
783
+ vim.fn.append(to_line, init_indent .. surr_info.right)
784
+ vim.fn.append(from_line - 1, init_indent .. surr_info.left)
785
+
786
+ return
787
+ end
788
+
789
+ if marks.selection_type == 'blockwise' then
790
+ -- NOTE: this doesn't work with mix of multibyte and normal characters, as
791
+ -- well as outside of text lines.
792
+ local from_col, to_col = marks.first.col, marks.second.col
793
+ -- - Ensure that `to_col` is to the right of `from_col`. Can be not the
794
+ -- case if visual block was selected from "south-west" to "north-east".
795
+ from_col, to_col = math.min(from_col, to_col), math.max(from_col, to_col)
796
+
797
+ for i = marks.first.line, marks.second.line do
798
+ H.region_replace({ from = { line = i, col = to_col + 1 } }, surr_info.right)
799
+ H.region_replace({ from = { line = i, col = from_col } }, surr_info.left)
800
+ end
801
+
802
+ H.set_cursor(marks.first.line, from_col + surr_info.left:len())
803
+
804
+ return
805
+ end
806
+ end
807
+
808
+ --- Delete surrounding
809
+ ---
810
+ --- No need to use it directly, everything is setup in |MiniSurround.setup()|.
811
+ MiniSurround.delete = function()
812
+ -- Find input surrounding region
813
+ local surr = H.find_surrounding(H.get_surround_spec('input', true))
814
+ if surr == nil then return '<Esc>' end
815
+
816
+ -- Delete surrounding region. Begin with right to not break column numbers.
817
+ H.region_replace(surr.right, {})
818
+ H.region_replace(surr.left, {})
819
+
820
+ -- Set cursor to be on the right of deleted left surrounding
821
+ local from = surr.left.from
822
+ H.set_cursor(from.line, from.col)
823
+
824
+ -- Possibly tweak deletion of linewise surrounding. Should act as reverse to
825
+ -- linewise addition.
826
+ if not H.get_config().respect_selection_type then return end
827
+
828
+ local from_line, to_line = surr.left.from.line, surr.right.from.line
829
+ local is_linewise_delete = from_line < to_line and H.is_line_blank(from_line) and H.is_line_blank(to_line)
830
+ if is_linewise_delete then
831
+ -- Dedent surrounded lines
832
+ H.shift_indent('<', from_line, to_line)
833
+
834
+ -- Place cursor on first surrounded line
835
+ H.set_cursor_nonblank(from_line + 1)
836
+
837
+ -- Delete blank lines left after deleting surroundings
838
+ local buf_id = vim.api.nvim_get_current_buf()
839
+ vim.fn.deletebufline(buf_id, to_line)
840
+ vim.fn.deletebufline(buf_id, from_line)
841
+ end
842
+ end
843
+
844
+ --- Replace surrounding
845
+ ---
846
+ --- No need to use it directly, everything is setup in |MiniSurround.setup()|.
847
+ MiniSurround.replace = function()
848
+ -- Find input surrounding region
849
+ local surr = H.find_surrounding(H.get_surround_spec('input', true))
850
+ if surr == nil then return '<Esc>' end
851
+
852
+ -- Get output surround info
853
+ local new_surr_info = H.get_surround_spec('output', true)
854
+ if new_surr_info == nil then return '<Esc>' end
855
+
856
+ -- Replace by parts starting from right to not break column numbers
857
+ H.region_replace(surr.right, new_surr_info.right)
858
+ H.region_replace(surr.left, new_surr_info.left)
859
+
860
+ -- Set cursor to be on the right of left surrounding
861
+ local from = surr.left.from
862
+ H.set_cursor(from.line, from.col + new_surr_info.left:len())
863
+ end
864
+
865
+ --- Find surrounding
866
+ ---
867
+ --- No need to use it directly, everything is setup in |MiniSurround.setup()|.
868
+ MiniSurround.find = function()
869
+ -- Find surrounding region
870
+ local surr = H.find_surrounding(H.get_surround_spec('input', true))
871
+ if surr == nil then return end
872
+
873
+ -- Make array of unique positions to cycle through
874
+ local pos_array = H.surr_to_pos_array(surr)
875
+
876
+ -- Cycle cursor through positions
877
+ local dir = H.cache.direction or 'right'
878
+ H.cursor_cycle(pos_array, dir)
879
+
880
+ -- Open 'enough folds' to show cursor
881
+ vim.cmd('normal! zv')
882
+ end
883
+
884
+ --- Highlight surrounding
885
+ ---
886
+ --- No need to use it directly, everything is setup in |MiniSurround.setup()|.
887
+ MiniSurround.highlight = function()
888
+ -- Find surrounding region
889
+ local surr = H.find_surrounding(H.get_surround_spec('input', true))
890
+ if surr == nil then return end
891
+
892
+ -- Highlight surrounding region
893
+ local config = H.get_config()
894
+ local buf_id = vim.api.nvim_get_current_buf()
895
+
896
+ H.region_highlight(buf_id, surr.left)
897
+ H.region_highlight(buf_id, surr.right)
898
+
899
+ vim.defer_fn(function()
900
+ H.region_unhighlight(buf_id, surr.left)
901
+ H.region_unhighlight(buf_id, surr.right)
902
+ end, config.highlight_duration)
903
+ end
904
+
905
+ --- Update `MiniSurround.config.n_lines` from user input
906
+ ---
907
+ --- Mapping example: >lua
908
+ ---
909
+ --- vim.keymap.set('n', 'sn', '<Cmd>lua MiniSurround.update_n_lines()<CR>')
910
+ --- <
911
+ MiniSurround.update_n_lines = function()
912
+ local n_lines = MiniSurround.user_input('New number of neighbor lines', MiniSurround.config.n_lines)
913
+ MiniSurround.config.n_lines = math.floor(tonumber(n_lines) or MiniSurround.config.n_lines)
914
+ end
915
+
916
+ --- Ask user for input
917
+ ---
918
+ --- This is mainly a wrapper for |input()| which allows empty string as input,
919
+ --- cancelling with `<Esc>` and `<C-c>`, and slightly modifies prompt. Use it
920
+ --- to ask for input inside function custom surrounding (see |MiniSurround.config|).
921
+ MiniSurround.user_input = function(prompt, text)
922
+ prompt = '(mini.surround) ' .. prompt
923
+ if _G.MiniInput ~= nil then return MiniInput.get({ prompt = prompt, scope = 'cursor', init_keys = { text } }) end
924
+
925
+ -- Major issue with both `vim.fn.input()` is that the only way to distinguish
926
+ -- cancelling with `<Esc>` and entering empty string with immediate `<CR>` is
927
+ -- through `cancelreturn` option (see `:h input()`). In that case the return
928
+ -- of `cancelreturn` will mean actual cancel, which removes possibility of
929
+ -- using that string. Although doable with very obscure string, this is not
930
+ -- very clean.
931
+ -- Overcome this by adding temporary keystroke listener.
932
+ local was_cancelled = false
933
+ vim.on_key(function(key) was_cancelled = was_cancelled or key == '\27' or key == '\3' end, H.ns_id.input)
934
+
935
+ -- Ask for input. Use `pcall` to allow `<C-c>` to cancel user input
936
+ -- NOTE: it would be GREAT to make this work with `vim.ui.input()` but I
937
+ -- didn't find a way to make it work without major refactor of whole module.
938
+ -- The main issue is that `vim.ui.input()` is designed to perform action in
939
+ -- callback and current module design is to get output immediately. Although
940
+ -- naive approach of
941
+ -- `local res; vim.ui.input({...}, function(input) res = input end)`
942
+ -- works in default `vim.ui.input`, its reimplementations can return from it
943
+ -- immediately and proceed in main event loop. Couldn't find a relatively
944
+ -- simple way to stop execution of this current function until `ui.input()`'s
945
+ -- callback finished execution.
946
+ vim.cmd('echohl Question')
947
+ local ok, res = pcall(vim.fn.input, { prompt = prompt .. ': ', default = text or '' })
948
+ vim.cmd('echohl None | echo "" | redraw')
949
+
950
+ vim.on_key(nil, H.ns_id.input)
951
+ return (ok and not was_cancelled) and res or nil
952
+ end
953
+
954
+ --- Generate common surrounding specifications
955
+ ---
956
+ --- This is a table with two sets of generator functions: <input> and <output>
957
+ --- (currently empty). Each is a table with function values generating
958
+ --- corresponding surrounding specification.
959
+ ---
960
+ ---@seealso |MiniAi.gen_spec|
961
+ MiniSurround.gen_spec = { input = {}, output = {} }
962
+
963
+ --- Treesitter specification for input surrounding
964
+ ---
965
+ --- This is a specification in function form. When called with a pair of
966
+ --- treesitter captures, it returns a specification function outputting an
967
+ --- array of region pairs derived from <outer> and <inner> captures. It first
968
+ --- searches for all matched nodes of outer capture and then completes each one
969
+ --- with the biggest match of inner capture inside that node (if any). The result
970
+ --- region pair is a difference between regions of outer and inner captures.
971
+ ---
972
+ --- In order for this to work, apart from working treesitter parser for desired
973
+ --- language, user should have a reachable language-specific `'textobjects'`
974
+ --- query (see |vim.treesitter.query.get()|).
975
+ --- The most straightforward way for this is to have `textobjects.scm` query
976
+ --- file with treesitter captures stored in some recognized path. This is
977
+ --- primarily designed to be compatible with plugin
978
+ --- `nvim-treesitter/nvim-treesitter-textobjects`, but can be used without it.
979
+ ---
980
+ --- Two most common approaches for having a query file:
981
+ --- - Install `nvim-treesitter/nvim-treesitter-textobjects`. It has curated and
982
+ --- well maintained builtin query files for many languages with a standardized
983
+ --- capture names, like `call.outer`, `call.inner`, etc.
984
+ --- - Manually create file `after/queries/<language-name>/textobjects.scm` in
985
+ --- your |$XDG_CONFIG_HOME| directory. It should contain queries with
986
+ --- captures (later used to define surrounding parts). See |lua-treesitter-query|.
987
+ --- To verify that query file is reachable, run (example for "lua" language,
988
+ --- output should have at least an intended file): >vim
989
+ ---
990
+ --- :lua print(vim.inspect(vim.treesitter.query.get_files('lua','textobjects')))
991
+ --- <
992
+ --- Example configuration for function definition textobject with
993
+ --- `nvim-treesitter/nvim-treesitter-textobjects` captures: >lua
994
+ ---
995
+ --- local ts_input = require('mini.surround').gen_spec.input.treesitter
996
+ --- require('mini.surround').setup({
997
+ --- custom_surroundings = {
998
+ --- -- Use tree-sitter to search for function call
999
+ --- f = {
1000
+ --- input = ts_input({ outer = '@call.outer', inner = '@call.inner' })
1001
+ --- },
1002
+ --- }
1003
+ --- })
1004
+ --- <
1005
+ --- Notes:
1006
+ --- - Be sure that query files don't contain unknown |treesitter-directives|
1007
+ --- (like `#make-range!`, for example). Otherwise surrounding with such captures
1008
+ --- might not be found as |lua-treesitter-core| won't treat them as captures.
1009
+ --- Verify with `:=vim.treesitter.query.get('lang', 'textobjects')` and see
1010
+ --- if the target capture is recognized as one.
1011
+ --- - It uses buffer's |filetype| to determine query language.
1012
+ --- - It first searches the language under cursor for matches. If no matches are
1013
+ --- found, it falls back to searching parent languages (up to the buffer's root
1014
+ --- language). If no matches are found again, it falls back to recursively
1015
+ --- searching all children languages (from the language under cursor). If no
1016
+ --- matches again - report no matches.
1017
+ --- - On large files it is slower than pattern-based textobjects. Still very
1018
+ --- fast though (one search should be magnitude of milliseconds or tens of
1019
+ --- milliseconds on really large file).
1020
+ ---
1021
+ ---@param captures table Captures for outer and inner parts of region pair:
1022
+ --- table with <outer> and <inner> fields with captures for outer
1023
+ --- (`[left.form; right.to]`) and inner (`(left.to; right.from)` both edges
1024
+ --- exclusive, i.e. they won't be a part of surrounding) regions. Each value
1025
+ --- should be a string capture starting with `'@'`.
1026
+ ---@param opts table|nil Options. Possible values:
1027
+ --- - <use_nvim_treesitter> - whether to try to use `nvim-treesitter` plugin
1028
+ --- (if present) to do the query. It used to implement more advanced behavior
1029
+ --- and more coherent experience if `nvim-treesitter-textobjects` queries are
1030
+ --- used. However, as |lua-treesitter-core| methods are more capable now,
1031
+ --- the option will soon be removed. Only present for backward compatibility.
1032
+ --- Default: `false`.
1033
+ ---
1034
+ ---@return function Function which returns array of current buffer region pairs
1035
+ --- representing differences between outer and inner captures.
1036
+ ---
1037
+ ---@seealso - |MiniSurround-surrounding-specification| for how this type of
1038
+ --- surrounding specification is processed.
1039
+ --- - |vim.treesitter.query.get()| for how query is fetched.
1040
+ --- - |Query:iter_captures()| for how all query captures are iterated in case of
1041
+ --- no `nvim-treesitter`.
1042
+ --- - |MiniAi.gen_spec.treesitter()| for similar |mini.ai| generator.
1043
+ MiniSurround.gen_spec.input.treesitter = function(captures, opts)
1044
+ -- TODO: Remove after releasing 'mini.nvim' 0.17.0
1045
+ opts = vim.tbl_deep_extend('force', { use_nvim_treesitter = false }, opts or {})
1046
+ captures = H.prepare_captures(captures)
1047
+
1048
+ -- Tree-sitter ranges are 0-based, end-exclusive, and usually
1049
+ -- `row1-col1-byte1-row2-col2-byte2` (i.e. "range six") format.
1050
+ local ts_range_to_region = function(r)
1051
+ -- The `master` branch of 'nvim-treesitter' can return "range four" format
1052
+ -- if it uses custom directives, like `#make-range!`. Due to the fact that
1053
+ -- it doesn't fully mock the `TSNode:range()` method to return "range six".
1054
+ -- TODO: Remove after 'nvim-treesitter' `master` branch support is dropped.
1055
+ local offset = #r == 4 and -1 or 0
1056
+ local res = { from = { line = r[1] + 1, col = r[2] + 1 }, to = { line = r[4 + offset] + 1, col = r[5 + offset] } }
1057
+
1058
+ -- NOTE: Adjust "row-exclusive, col-0" range that means "all previous row
1059
+ -- including the newline character"
1060
+ if res.to.col == 0 then
1061
+ res.to.line = res.to.line - 1
1062
+ res.to.col = vim.fn.col({ res.to.line, '$' })
1063
+ end
1064
+
1065
+ return res
1066
+ end
1067
+
1068
+ return function()
1069
+ local has_nvim_treesitter = pcall(require, 'nvim-treesitter') and pcall(require, 'nvim-treesitter.query')
1070
+ local range_pair_querier = (has_nvim_treesitter and opts.use_nvim_treesitter) and H.get_matched_range_pairs_plugin
1071
+ or H.get_matched_range_pairs_builtin
1072
+ local matched_range_pairs = range_pair_querier(captures)
1073
+
1074
+ -- Return array of region pairs
1075
+ return vim.tbl_map(function(range_pair)
1076
+ local outer_region = ts_range_to_region(range_pair.outer)
1077
+ local left_from, right_to = outer_region.from, outer_region.to
1078
+
1079
+ local left_to, right_from
1080
+ if range_pair.inner == nil then
1081
+ left_to = right_to
1082
+ right_from = H.pos_to_right(right_to)
1083
+ right_to = nil
1084
+ else
1085
+ local inner_region = ts_range_to_region(range_pair.inner)
1086
+ left_to, right_from = inner_region.from, inner_region.to
1087
+ -- Take into account that inner capture should be both edges exclusive
1088
+ left_to, right_from = H.pos_to_left(left_to), H.pos_to_right(right_from)
1089
+ end
1090
+
1091
+ return { left = { from = left_from, to = left_to }, right = { from = right_from, to = right_to } }
1092
+ end, matched_range_pairs)
1093
+ end
1094
+ end
1095
+
1096
+ -- Helper data ================================================================
1097
+ -- Module default config
1098
+ H.default_config = vim.deepcopy(MiniSurround.config)
1099
+
1100
+ -- Namespaces to be used within module
1101
+ H.ns_id = {
1102
+ highlight = vim.api.nvim_create_namespace('MiniSurroundHighlight'),
1103
+ input = vim.api.nvim_create_namespace('MiniSurroundInput'),
1104
+ }
1105
+
1106
+ --stylua: ignore
1107
+ -- Builtin surroundings
1108
+ H.builtin_surroundings = {
1109
+ -- Use balanced pair for brackets. Use opening ones to possibly
1110
+ -- replace/delete innder edge whitespace.
1111
+ ['('] = { input = { '%b()', '^.%s*().-()%s*.$' }, output = { left = '( ', right = ' )' } },
1112
+ [')'] = { input = { '%b()', '^.().*().$' }, output = { left = '(', right = ')' } },
1113
+ ['['] = { input = { '%b[]', '^.%s*().-()%s*.$' }, output = { left = '[ ', right = ' ]' } },
1114
+ [']'] = { input = { '%b[]', '^.().*().$' }, output = { left = '[', right = ']' } },
1115
+ ['{'] = { input = { '%b{}', '^.%s*().-()%s*.$' }, output = { left = '{ ', right = ' }' } },
1116
+ ['}'] = { input = { '%b{}', '^.().*().$' }, output = { left = '{', right = '}' } },
1117
+ ['<'] = { input = { '%b<>', '^.%s*().-()%s*.$' }, output = { left = '< ', right = ' >' } },
1118
+ ['>'] = { input = { '%b<>', '^.().*().$' }, output = { left = '<', right = '>' } },
1119
+ -- Derived from user prompt
1120
+ ['?'] = {
1121
+ input = function()
1122
+ local left = MiniSurround.user_input('Left surrounding')
1123
+ if left == nil or left == '' then return end
1124
+ local right = MiniSurround.user_input('Right surrounding')
1125
+ if right == nil or right == '' then return end
1126
+
1127
+ return { vim.pesc(left) .. '().-()' .. vim.pesc(right) }
1128
+ end,
1129
+ output = function()
1130
+ local left = MiniSurround.user_input('Left surrounding')
1131
+ if left == nil then return end
1132
+ local right = MiniSurround.user_input('Right surrounding')
1133
+ if right == nil then return end
1134
+ return { left = left, right = right }
1135
+ end,
1136
+ },
1137
+ -- Brackets
1138
+ ['b'] = { input = { { '%b()', '%b[]', '%b{}' }, '^.().*().$' }, output = { left = '(', right = ')' } },
1139
+ -- Function call
1140
+ ['f'] = {
1141
+ input = { '%f[%w_%.][%w_%.]+%b()', '^.-%(().*()%)$' },
1142
+ output = function()
1143
+ local fun_name = MiniSurround.user_input('Function name')
1144
+ if fun_name == nil then return nil end
1145
+ return { left = ('%s('):format(fun_name), right = ')' }
1146
+ end,
1147
+ },
1148
+ -- Tag
1149
+ ['t'] = {
1150
+ input = { '<(%w-)%f[^<%w][^<>]->.-</%1>', '^<.->().*()</[^/]->$' },
1151
+ output = function()
1152
+ local tag_full = MiniSurround.user_input('Tag')
1153
+ if tag_full == nil then return nil end
1154
+ local tag_name = tag_full:match('^%S*')
1155
+ return { left = '<' .. tag_full .. '>', right = '</' .. tag_name .. '>' }
1156
+ end,
1157
+ },
1158
+ -- Quotes
1159
+ ['q'] = { input = { { "'.-'", '".-"', '`.-`' }, '^.().*().$' }, output = { left = '"', right = '"' } },
1160
+ }
1161
+
1162
+ -- Cache for dot-repeatability. This table is currently used with these keys:
1163
+ -- - 'input' - surround info for searching (in 'delete' and 'replace' start).
1164
+ -- - 'output' - surround info for adding (in 'add' and 'replace' end).
1165
+ -- - 'direction' - direction in which `MiniSurround.find()` should go.
1166
+ -- Currently is not used for dot-repeat, but for easier mappings.
1167
+ -- - 'search_method' - search method.
1168
+ -- - 'msg_shown' - whether helper message was shown.
1169
+ H.cache = {}
1170
+
1171
+ -- Helper functionality =======================================================
1172
+ -- Settings -------------------------------------------------------------------
1173
+ H.setup_config = function(config)
1174
+ H.check_type('config', config, 'table', true)
1175
+ config = vim.tbl_deep_extend('force', vim.deepcopy(H.default_config), config or {})
1176
+
1177
+ H.check_type('custom_surroundings', config.custom_surroundings, 'table', true)
1178
+ H.check_type('highlight_duration', config.highlight_duration, 'number')
1179
+ H.check_type('mappings', config.mappings, 'table')
1180
+ H.check_type('n_lines', config.n_lines, 'number')
1181
+ H.check_type('respect_selection_type', config.respect_selection_type, 'boolean')
1182
+ H.validate_search_method(config.search_method)
1183
+ H.check_type('silent', config.silent, 'boolean')
1184
+
1185
+ H.check_type('mappings.add', config.mappings.add, 'string')
1186
+ H.check_type('mappings.delete', config.mappings.delete, 'string')
1187
+ H.check_type('mappings.find', config.mappings.find, 'string')
1188
+ H.check_type('mappings.find_left', config.mappings.find_left, 'string')
1189
+ H.check_type('mappings.highlight', config.mappings.highlight, 'string')
1190
+ H.check_type('mappings.replace', config.mappings.replace, 'string')
1191
+
1192
+ H.check_type('mappings.suffix_last', config.mappings.suffix_last, 'string')
1193
+ H.check_type('mappings.suffix_next', config.mappings.suffix_next, 'string')
1194
+
1195
+ return config
1196
+ end
1197
+
1198
+ H.apply_config = function(config)
1199
+ MiniSurround.config = config
1200
+
1201
+ local maps, maps_l, maps_n = config.mappings, {}, {}
1202
+ local suf_l, suf_n = maps.suffix_last, maps.suffix_next
1203
+ for k, v in pairs(maps) do
1204
+ -- Don't create extended mapping if user chose not to create a regular one
1205
+ maps_l[k] = (v ~= '' and suf_l ~= '') and (v .. suf_l) or ''
1206
+ maps_n[k] = (v ~= '' and suf_n ~= '') and (v .. suf_n) or ''
1207
+ end
1208
+
1209
+ local m = function(mode, lhs, rhs, desc) H.map(mode, lhs, rhs, { expr = true, desc = desc }) end
1210
+
1211
+ --stylua: ignore start
1212
+ m('n', maps.add, H.make_operator('add', nil, true), 'Add surrounding')
1213
+ H.map('x', maps.add, ':<C-u>lua MiniSurround.add("visual")<CR>', { desc = 'Add surrounding to selection' })
1214
+
1215
+ m('n', maps.delete, H.make_operator('delete', nil), 'Delete surrounding')
1216
+ m('n', maps_l.delete, H.make_operator('delete', 'prev'), 'Delete previous surrounding')
1217
+ m('n', maps_n.delete, H.make_operator('delete', 'next'), 'Delete next surrounding')
1218
+
1219
+ m('n', maps.replace, H.make_operator('replace', nil), 'Replace surrounding')
1220
+ m('n', maps_l.replace, H.make_operator('replace', 'prev'), 'Replace previous surrounding')
1221
+ m('n', maps_n.replace, H.make_operator('replace', 'next'), 'Replace next surrounding')
1222
+
1223
+ m('n', maps.find, H.make_action('find', 'right', nil), 'Find right surrounding')
1224
+ m('x', maps.find, H.make_action('find', 'right', nil), 'Find right surrounding')
1225
+ m('o', maps.find, H.make_action('find', 'right', nil), 'Find right surrounding')
1226
+ m('n', maps_l.find, H.make_action('find', 'right', 'prev'), 'Find previous right surrounding')
1227
+ m('x', maps_l.find, H.make_action('find', 'right', 'prev'), 'Find previous right surrounding')
1228
+ m('o', maps_l.find, H.make_action('find', 'right', 'prev'), 'Find previous right surrounding')
1229
+ m('n', maps_n.find, H.make_action('find', 'right', 'next'), 'Find next right surrounding')
1230
+ m('x', maps_n.find, H.make_action('find', 'right', 'next'), 'Find next right surrounding')
1231
+ m('o', maps_n.find, H.make_action('find', 'right', 'next'), 'Find next right surrounding')
1232
+
1233
+ m('n', maps.find_left, H.make_action('find', 'left', nil), 'Find left surrounding')
1234
+ m('x', maps.find_left, H.make_action('find', 'left', nil), 'Find left surrounding')
1235
+ m('o', maps.find_left, H.make_action('find', 'left', nil), 'Find left surrounding')
1236
+ m('n', maps_l.find_left, H.make_action('find', 'left', 'prev'), 'Find previous left surrounding')
1237
+ m('x', maps_l.find_left, H.make_action('find', 'left', 'prev'), 'Find previous left surrounding')
1238
+ m('o', maps_l.find_left, H.make_action('find', 'left', 'prev'), 'Find previous left surrounding')
1239
+ m('n', maps_n.find_left, H.make_action('find', 'left', 'next'), 'Find next left surrounding')
1240
+ m('x', maps_n.find_left, H.make_action('find', 'left', 'next'), 'Find next left surrounding')
1241
+ m('o', maps_n.find_left, H.make_action('find', 'left', 'next'), 'Find next left surrounding')
1242
+
1243
+ m('n', maps.highlight, H.make_action('highlight', nil, nil), 'Highlight surrounding')
1244
+ m('n', maps_l.highlight, H.make_action('highlight', nil, 'prev'), 'Highlight previous surrounding')
1245
+ m('n', maps_n.highlight, H.make_action('highlight', nil, 'next'), 'Highlight next surrounding')
1246
+ --stylua: ignore end
1247
+ end
1248
+
1249
+ H.create_autocommands = function()
1250
+ local gr = vim.api.nvim_create_augroup('MiniSurround', {})
1251
+ vim.api.nvim_create_autocmd('ColorScheme', { group = gr, callback = H.create_default_hl, desc = 'Ensure colors' })
1252
+ end
1253
+
1254
+ H.create_default_hl = function() vim.api.nvim_set_hl(0, 'MiniSurround', { default = true, link = 'IncSearch' }) end
1255
+
1256
+ H.is_disabled = function() return vim.g.minisurround_disable == true or vim.b.minisurround_disable == true end
1257
+
1258
+ H.get_config = function(config)
1259
+ return vim.tbl_deep_extend('force', MiniSurround.config, vim.b.minisurround_config or {}, config or {})
1260
+ end
1261
+
1262
+ H.validate_search_method = function(x)
1263
+ local allowed_methods = vim.tbl_keys(H.span_compare_methods)
1264
+ if vim.tbl_contains(allowed_methods, x) then return end
1265
+
1266
+ table.sort(allowed_methods)
1267
+ local allowed_methods_string = table.concat(vim.tbl_map(vim.inspect, allowed_methods), ', ')
1268
+ H.error('`search_method` should be one of ' .. allowed_methods_string)
1269
+ end
1270
+
1271
+ -- Mappings -------------------------------------------------------------------
1272
+ H.make_operator = function(task, search_method, ask_for_textobject)
1273
+ return function()
1274
+ if H.is_disabled() then
1275
+ -- Using `<Esc>` helps to stop moving cursor caused by current
1276
+ -- implementation detail of adding `' '` inside expression mapping
1277
+ return [[\<Esc>]]
1278
+ end
1279
+
1280
+ H.cache = { count = vim.v.count1, search_method = search_method }
1281
+
1282
+ vim.o.operatorfunc = 'v:lua.MiniSurround.' .. task
1283
+
1284
+ -- NOTEs:
1285
+ -- - Prepend with command to reset `vim.v.count1` to allow
1286
+ -- `[count1]sa[count2][textobject]`.
1287
+ -- - Concatenate `' '` to operator output to "disable" motion
1288
+ -- required by `g@`. It is used to enable dot-repeatability.
1289
+ return '<Cmd>redraw<CR>g@' .. (ask_for_textobject and '' or ' ')
1290
+ end
1291
+ end
1292
+
1293
+ H.make_action = function(task, direction, search_method)
1294
+ return function()
1295
+ if H.is_disabled() then return '<Esc>' end
1296
+ H.cache = { count = vim.v.count1, direction = direction, search_method = search_method }
1297
+ return '<Cmd>lua MiniSurround.' .. task .. '()<CR>'
1298
+ end
1299
+ end
1300
+
1301
+ -- Work with surrounding info -------------------------------------------------
1302
+ H.get_surround_spec = function(surr_type, use_cache)
1303
+ local res
1304
+
1305
+ -- Try using cache
1306
+ if use_cache then
1307
+ res = H.cache[surr_type]
1308
+ if res ~= nil then return res end
1309
+ else
1310
+ H.cache = {}
1311
+ end
1312
+
1313
+ -- Prompt user to enter identifier of surrounding
1314
+ local char = H.user_surround_id(surr_type)
1315
+ if char == nil then return nil end
1316
+
1317
+ -- Get surround specification
1318
+ res = H.make_surrounding_table()[char][surr_type]
1319
+
1320
+ -- Allow function returning spec or surrounding region(s)
1321
+ if vim.is_callable(res) then res = res() end
1322
+
1323
+ -- Do nothing if supplied not appropriate structure
1324
+ if not H.is_surrounding_info(res, surr_type) then return nil end
1325
+
1326
+ -- Wrap callable tables to be an actual functions. Otherwise they might be
1327
+ -- confused with list of patterns.
1328
+ if H.is_composed_pattern(res) then res = vim.tbl_map(H.wrap_callable_table, res) end
1329
+
1330
+ -- Track id for possible messages. Use metatable to pass "islist" check.
1331
+ res = setmetatable(res, { __index = { id = char } })
1332
+
1333
+ -- Cache result
1334
+ if use_cache then H.cache[surr_type] = res end
1335
+
1336
+ return res
1337
+ end
1338
+
1339
+ H.make_surrounding_table = function()
1340
+ -- Extend builtins with data from `config`
1341
+ local surroundings = vim.deepcopy(H.builtin_surroundings)
1342
+ for char, spec in pairs(H.get_config().custom_surroundings or {}) do
1343
+ local cur_spec = surroundings[char] or {}
1344
+ local default = H.get_default_surrounding_info(char)
1345
+ -- NOTE: Don't use `tbl_deep_extend` to prefer full `input` arrays
1346
+ cur_spec.input = spec.input or cur_spec.input or default.input
1347
+ cur_spec.output = spec.output or cur_spec.output or default.output
1348
+ surroundings[char] = cur_spec
1349
+ end
1350
+
1351
+ -- Use default surrounding info for not supplied single character identifier
1352
+ return setmetatable(surroundings, {
1353
+ __index = function(_, key) return H.get_default_surrounding_info(key) end,
1354
+ })
1355
+ end
1356
+
1357
+ H.get_default_surrounding_info = function(char)
1358
+ local char_esc = vim.pesc(char)
1359
+ return { input = { char_esc .. '().-()' .. char_esc }, output = { left = char, right = char } }
1360
+ end
1361
+
1362
+ H.is_surrounding_info = function(x, surr_type)
1363
+ if surr_type == 'input' then
1364
+ return H.is_composed_pattern(x) or H.is_region_pair(x) or H.is_region_pair_array(x)
1365
+ elseif surr_type == 'output' then
1366
+ return (type(x) == 'table' and type(x.left) == 'string' and type(x.right) == 'string')
1367
+ end
1368
+ end
1369
+
1370
+ H.is_region = function(x)
1371
+ if type(x) ~= 'table' then return false end
1372
+ local from_is_valid = type(x.from) == 'table' and type(x.from.line) == 'number' and type(x.from.col) == 'number'
1373
+ -- Allow `to` to be `nil` to describe empty regions
1374
+ local to_is_valid = true
1375
+ if x.to ~= nil then
1376
+ to_is_valid = type(x.to) == 'table' and type(x.to.line) == 'number' and type(x.to.col) == 'number'
1377
+ end
1378
+ return from_is_valid and to_is_valid
1379
+ end
1380
+
1381
+ H.is_region_pair = function(x)
1382
+ if type(x) ~= 'table' then return false end
1383
+ return H.is_region(x.left) and H.is_region(x.right)
1384
+ end
1385
+
1386
+ H.is_region_pair_array = function(x)
1387
+ if not H.islist(x) then return false end
1388
+ for _, v in ipairs(x) do
1389
+ if not H.is_region_pair(v) then return false end
1390
+ end
1391
+ return true
1392
+ end
1393
+
1394
+ H.is_composed_pattern = function(x)
1395
+ if not (H.islist(x) and #x > 0) then return false end
1396
+ for _, val in ipairs(x) do
1397
+ local val_type = type(val)
1398
+ if not (val_type == 'table' or val_type == 'string' or vim.is_callable(val)) then return false end
1399
+ end
1400
+ return true
1401
+ end
1402
+
1403
+ -- Work with finding surrounding ----------------------------------------------
1404
+ ---@param surr_spec table Composed pattern. Last item(s) - extraction template.
1405
+ ---@param opts table|nil Options.
1406
+ ---@private
1407
+ H.find_surrounding = function(surr_spec, opts)
1408
+ if surr_spec == nil then return end
1409
+ if H.is_region_pair(surr_spec) then return surr_spec end
1410
+
1411
+ opts = vim.tbl_deep_extend('force', H.get_default_opts(), opts or {})
1412
+ H.validate_search_method(opts.search_method)
1413
+
1414
+ local region_pair = H.find_surrounding_region_pair(surr_spec, opts)
1415
+ if region_pair == nil then
1416
+ local msg = ([[No surrounding %s found within %d line%s and `config.search_method = '%s'`.]]):format(
1417
+ vim.inspect((opts.n_times > 1 and opts.n_times or '') .. surr_spec.id),
1418
+ opts.n_lines,
1419
+ opts.n_lines > 1 and 's' or '',
1420
+ opts.search_method
1421
+ )
1422
+ H.message(msg)
1423
+ end
1424
+
1425
+ return region_pair
1426
+ end
1427
+
1428
+ H.find_surrounding_region_pair = function(surr_spec, opts)
1429
+ local reference_region, n_times, n_lines = opts.reference_region, opts.n_times, opts.n_lines
1430
+
1431
+ if n_times == 0 then return end
1432
+
1433
+ -- Find `n_times` matching spans evolving from reference region span
1434
+ -- First try to find inside 0-neighborhood
1435
+ local neigh = H.get_neighborhood(reference_region, 0)
1436
+ local reference_span = neigh.region_to_span(reference_region)
1437
+
1438
+ local find_next = function(cur_reference_span)
1439
+ local res = H.find_best_match(neigh, surr_spec, cur_reference_span, opts)
1440
+
1441
+ -- If didn't find in 0-neighborhood, possibly try extend one
1442
+ if res.span == nil then
1443
+ -- Stop if no need to extend neighborhood
1444
+ if n_lines == 0 or neigh.n_neighbors > 0 then return {} end
1445
+
1446
+ -- Update data with respect to new neighborhood
1447
+ local cur_reference_region = neigh.span_to_region(cur_reference_span)
1448
+ neigh = H.get_neighborhood(reference_region, n_lines)
1449
+ reference_span = neigh.region_to_span(reference_region)
1450
+ cur_reference_span = neigh.region_to_span(cur_reference_region)
1451
+
1452
+ -- Recompute based on new neighborhood
1453
+ res = H.find_best_match(neigh, surr_spec, cur_reference_span, opts)
1454
+ end
1455
+
1456
+ return res
1457
+ end
1458
+
1459
+ local find_res = { span = reference_span }
1460
+ for _ = 1, n_times do
1461
+ find_res = find_next(find_res.span)
1462
+ if find_res.span == nil then return end
1463
+ end
1464
+
1465
+ -- Extract final span
1466
+ local extract = function(span, extract_pattern)
1467
+ -- Use table extract pattern to allow array of regions as surrounding spec
1468
+ -- Pair of spans is constructed based on best region pair
1469
+ if type(extract_pattern) == 'table' then return extract_pattern end
1470
+
1471
+ -- First extract local (with respect to best matched span) surrounding spans
1472
+ local s = neigh['1d']:sub(span.from, span.to - 1)
1473
+ local local_surr_spans = H.extract_surr_spans(s, extract_pattern)
1474
+
1475
+ -- Convert local spans to global
1476
+ local off = span.from - 1
1477
+ local left, right = local_surr_spans.left, local_surr_spans.right
1478
+ return {
1479
+ left = { from = left.from + off, to = left.to + off },
1480
+ right = { from = right.from + off, to = right.to + off },
1481
+ }
1482
+ end
1483
+
1484
+ local final_spans = extract(find_res.span, find_res.extract_pattern)
1485
+ local outer_span = { from = final_spans.left.from, to = final_spans.right.to }
1486
+
1487
+ -- Ensure that output region is different from reference.
1488
+ if H.is_span_covering(reference_span, outer_span) then
1489
+ find_res = find_next(find_res.span)
1490
+ if find_res.span == nil then return end
1491
+ final_spans = extract(find_res.span, find_res.extract_pattern)
1492
+ outer_span = { from = final_spans.left.from, to = final_spans.right.to }
1493
+ if H.is_span_covering(reference_span, outer_span) then return end
1494
+ end
1495
+
1496
+ -- Convert to region pair
1497
+ return { left = neigh.span_to_region(final_spans.left), right = neigh.span_to_region(final_spans.right) }
1498
+ end
1499
+
1500
+ H.get_default_opts = function()
1501
+ local config = H.get_config()
1502
+ local cur_pos = vim.api.nvim_win_get_cursor(0)
1503
+ return {
1504
+ n_lines = config.n_lines,
1505
+ n_times = H.cache.count or vim.v.count1,
1506
+ -- Empty region at cursor position
1507
+ reference_region = { from = { line = cur_pos[1], col = cur_pos[2] + 1 } },
1508
+ search_method = H.cache.search_method or config.search_method,
1509
+ }
1510
+ end
1511
+
1512
+ -- Work with treesitter surrounding -------------------------------------------
1513
+ H.prepare_captures = function(captures)
1514
+ local is_capture = function(x) return type(x) == 'string' and x:sub(1, 1) == '@' end
1515
+
1516
+ if not (type(captures) == 'table' and is_capture(captures.outer) and is_capture(captures.inner)) then
1517
+ H.error('Wrong format for `captures`. See `MiniSurround.gen_spec.input.treesitter()` for details.')
1518
+ end
1519
+
1520
+ return { outer = captures.outer, inner = captures.inner }
1521
+ end
1522
+
1523
+ H.get_matched_range_pairs_plugin = function(captures)
1524
+ local ts_queries = require('nvim-treesitter.query')
1525
+ local buf_id = vim.api.nvim_get_current_buf()
1526
+ local outer_matches = ts_queries.get_capture_matches_recursively(buf_id, captures.outer, 'textobjects')
1527
+
1528
+ -- Make sure that found matches contain `node` field that is actually a node,
1529
+ -- otherwise later `get_capture_matches` will error as it requires an actual
1530
+ -- `TSNode` object. This is needed as capture might be defined with custom
1531
+ -- directive (like `#make-range!`) which 'nvim-treesitter' handles manually
1532
+ -- by returning "extended range" and not `TSNode`.
1533
+ outer_matches = vim.tbl_filter(function(x) return x.node.tree ~= nil end, outer_matches)
1534
+
1535
+ -- Pick inner range as the biggest range for node matching inner query. This
1536
+ -- is needed because query output is not guaranteed to come in order, so just
1537
+ -- picking first one is not enough.
1538
+ return vim.tbl_map(function(m_outer)
1539
+ local outer_range = vim.treesitter.get_range(m_outer.node, buf_id, m_outer.metadata)
1540
+ local inner = ts_queries.get_capture_matches(0, captures.inner, 'textobjects', m_outer.node, nil)
1541
+ local inner_ranges = vim.tbl_map(function(m) return vim.treesitter.get_range(m.node, buf_id, m.metadata) end, inner)
1542
+ return { outer = outer_range, inner = H.get_biggest_nested_range(inner_ranges, outer_range) }
1543
+ end, outer_matches)
1544
+ end
1545
+
1546
+ H.get_matched_range_pairs_builtin = function(captures)
1547
+ -- Get buffer's parser (LanguageTree)
1548
+ local buf_id = vim.api.nvim_get_current_buf()
1549
+ -- TODO: Remove `opts.error` after compatibility with Neovim=0.11 is dropped
1550
+ local has_parser, parser = pcall(vim.treesitter.get_parser, buf_id, nil, { error = false })
1551
+ if not has_parser or parser == nil then H.error_treesitter('parser') end
1552
+
1553
+ -- Get parser (LanguageTree) at cursor (important for injected languages)
1554
+ local pos = vim.api.nvim_win_get_cursor(0)
1555
+ local lang_tree = parser:language_for_range({ pos[1] - 1, pos[2], pos[1] - 1, pos[2] })
1556
+ local init_lang_tree = lang_tree
1557
+
1558
+ local missing_query_langs = {}
1559
+ -- Compute matched ranges for both outer and inner captures
1560
+ local outer, inner = {}, {}
1561
+ -- Go up parent trees to work with injected languages
1562
+ while (vim.tbl_isempty(inner) or vim.tbl_isempty(outer)) and lang_tree ~= nil do
1563
+ H.append_lang_ranges(outer, inner, missing_query_langs, buf_id, captures, lang_tree)
1564
+
1565
+ -- `LanguageTree:parent()` was added in Neovim<0.10
1566
+ -- TODO: Drop extra check after compatibility with Neovim=0.9 is dropped
1567
+ lang_tree = lang_tree.parent and lang_tree:parent() or nil
1568
+ end
1569
+
1570
+ -- Fall back to children trees for injected languages
1571
+ if vim.tbl_isempty(inner) or vim.tbl_isempty(outer) then
1572
+ local check_children
1573
+ check_children = function(l_tree)
1574
+ for _, child in pairs(l_tree:children()) do
1575
+ H.append_lang_ranges(outer, inner, missing_query_langs, buf_id, captures, child)
1576
+ check_children(child)
1577
+ end
1578
+ end
1579
+ check_children(init_lang_tree)
1580
+ end
1581
+
1582
+ -- Match outer and inner ranges: for each outer range pick the biggest inner
1583
+ -- range that lies within outer
1584
+ local res = {}
1585
+ for i, o in ipairs(outer) do
1586
+ res[i] = { outer = o, inner = H.get_biggest_nested_range(inner, o) }
1587
+ end
1588
+
1589
+ if vim.tbl_isempty(res) and not vim.tbl_isempty(missing_query_langs) then
1590
+ H.error_treesitter('query', vim.tbl_keys(missing_query_langs))
1591
+ end
1592
+
1593
+ return res
1594
+ end
1595
+
1596
+ H.append_lang_ranges = function(outer, inner, missing_query_langs, buf_id, captures, lang_tree)
1597
+ local lang = lang_tree:lang()
1598
+ local query = vim.treesitter.query.get(lang, 'textobjects')
1599
+
1600
+ if query ~= nil then H.append_ranges(outer, inner, buf_id, query, captures, lang_tree) end
1601
+ if query == nil then missing_query_langs[lang] = true end
1602
+ end
1603
+
1604
+ H.append_ranges = function(outer, inner, buf_id, query, captures, lang_tree)
1605
+ for _, tree in ipairs(lang_tree:trees()) do
1606
+ local root = tree:root()
1607
+ vim.list_extend(outer, H.get_match_ranges_builtin(root, buf_id, query, captures.outer:sub(2)))
1608
+ vim.list_extend(inner, H.get_match_ranges_builtin(root, buf_id, query, captures.inner:sub(2)))
1609
+ end
1610
+ end
1611
+
1612
+ H.get_match_ranges_builtin = function(root, buf_id, query, capture)
1613
+ local res = {}
1614
+ -- TODO: Remove `opts.all`after compatibility with Neovim=0.10 is dropped
1615
+ for _, match, metadata in query:iter_matches(root, buf_id, nil, nil, { all = true }) do
1616
+ for capture_id, nodes in pairs(match) do
1617
+ local mt = metadata[capture_id]
1618
+ if query.captures[capture_id] == capture then table.insert(res, H.get_nodes_range_builtin(nodes, buf_id, mt)) end
1619
+ end
1620
+ end
1621
+
1622
+ return res
1623
+ end
1624
+
1625
+ H.get_nodes_range_builtin = function(nodes, buf_id, metadata)
1626
+ -- In Neovim<0.10 `Query:iter_matches()` has `match` map to single node.
1627
+ -- TODO: Remove `opts.all`after compatibility with Neovim=0.9 is dropped
1628
+ nodes = type(nodes) == 'table' and nodes or { nodes }
1629
+
1630
+ -- Get matched range as spanning from left most node start to right most node
1631
+ -- end. This accounts for several matched nodes that are intentionally there
1632
+ -- to cover complex cases. Approach is named "quantified captures".
1633
+ local left, right
1634
+ for _, node in ipairs(nodes) do
1635
+ local range = vim.treesitter.get_range(node, buf_id, metadata)
1636
+ if left == nil or range[3] < left[3] then left = range end
1637
+ if right == nil or range[6] > right[6] then right = range end
1638
+ end
1639
+ return { left[1], left[2], left[3], right[4], right[5], right[6] }
1640
+ end
1641
+
1642
+ H.get_biggest_nested_range = function(ranges, parent)
1643
+ local best_range, best_byte_count = nil, -math.huge
1644
+ for _, r in ipairs(ranges) do
1645
+ local is_nested = parent[3] <= r[3] and r[6] <= parent[6] and not (parent[3] == r[3] and r[6] == parent[6])
1646
+ local byte_count = r[6] - r[3] + 1
1647
+ if is_nested and best_byte_count < byte_count then
1648
+ best_range, best_byte_count = r, byte_count
1649
+ end
1650
+ end
1651
+
1652
+ return best_range
1653
+ end
1654
+
1655
+ H.error_treesitter = function(failed_get, langs)
1656
+ local buf_id, ft = vim.api.nvim_get_current_buf(), vim.bo.filetype
1657
+ if langs == nil then
1658
+ local has_lang, ft_lang = pcall(vim.treesitter.language.get_lang, ft)
1659
+ -- `vim.treesitter.language.get_lang()` defaults to `ft` on Neovim>0.11
1660
+ -- TODO: Drop check after compatibility with Neovim=0.10 is dropped
1661
+ langs = (has_lang and ft_lang ~= nil) and { ft_lang } or { ft }
1662
+ end
1663
+ table.sort(langs)
1664
+ local langs_str = table.concat(vim.tbl_map(vim.inspect, langs), ', ')
1665
+ local langs_noun = #langs == 1 and 'language' or 'languages'
1666
+ local msg = string.format('Can not get %s for buffer %d and %s %s.', failed_get, buf_id, langs_noun, langs_str)
1667
+ H.error(msg)
1668
+ end
1669
+
1670
+ -- Work with matching spans ---------------------------------------------------
1671
+ ---@param neighborhood table Output of `get_neighborhood()`.
1672
+ ---@param surr_spec table
1673
+ ---@param reference_span table Span to cover.
1674
+ ---@param opts table Fields: <search_method>.
1675
+ ---@private
1676
+ H.find_best_match = function(neighborhood, surr_spec, reference_span, opts)
1677
+ local best_span, best_nested_pattern, current_nested_pattern
1678
+ local f = function(span)
1679
+ if H.is_better_span(span, best_span, reference_span, opts) then
1680
+ best_span = span
1681
+ best_nested_pattern = current_nested_pattern
1682
+ end
1683
+ end
1684
+
1685
+ if H.is_region_pair_array(surr_spec) then
1686
+ -- Iterate over all spans representing outer regions in array
1687
+ for _, region_pair in ipairs(surr_spec) do
1688
+ -- Construct outer region used to find best region pair
1689
+ local outer_region = { from = region_pair.left.from, to = region_pair.right.to or region_pair.right.from }
1690
+
1691
+ -- Consider outer region only if it is completely within neighborhood
1692
+ if neighborhood.is_region_inside(outer_region) then
1693
+ -- Make future extract pattern based directly on region pair
1694
+ current_nested_pattern = {
1695
+ {
1696
+ left = neighborhood.region_to_span(region_pair.left),
1697
+ right = neighborhood.region_to_span(region_pair.right),
1698
+ },
1699
+ }
1700
+
1701
+ f(neighborhood.region_to_span(outer_region))
1702
+ end
1703
+ end
1704
+ else
1705
+ -- Iterate over all matched spans
1706
+ for _, nested_pattern in ipairs(H.cartesian_product(surr_spec)) do
1707
+ current_nested_pattern = nested_pattern
1708
+ H.iterate_matched_spans(neighborhood['1d'], nested_pattern, f)
1709
+ end
1710
+ end
1711
+
1712
+ local extract_pattern
1713
+ if best_nested_pattern ~= nil then extract_pattern = best_nested_pattern[#best_nested_pattern] end
1714
+ return { span = best_span, extract_pattern = extract_pattern }
1715
+ end
1716
+
1717
+ H.iterate_matched_spans = function(line, nested_pattern, f)
1718
+ local max_level = #nested_pattern
1719
+ -- Keep track of visited spans to ensure only one call of `f`.
1720
+ -- Example: `((a) (b))`, `{'%b()', '%b()'}`
1721
+ local visited = {}
1722
+
1723
+ local process
1724
+ process = function(level, level_line, level_offset)
1725
+ local pattern = nested_pattern[level]
1726
+ local next_span = function(s, init) return H.string_find(s, pattern, init) end
1727
+ if vim.is_callable(pattern) then next_span = pattern end
1728
+
1729
+ local is_same_balanced = type(pattern) == 'string' and pattern:match('^%%b(.)%1$') ~= nil
1730
+ local init = 1
1731
+ while init <= level_line:len() do
1732
+ local from, to = next_span(level_line, init)
1733
+ if from == nil then break end
1734
+
1735
+ if level == max_level then
1736
+ local found_match = H.new_span(from + level_offset, to + level_offset)
1737
+ local found_match_id = string.format('%s_%s', found_match.from, found_match.to)
1738
+ if not visited[found_match_id] then
1739
+ f(found_match)
1740
+ visited[found_match_id] = true
1741
+ end
1742
+ else
1743
+ local next_level_line = level_line:sub(from, to)
1744
+ local next_level_offset = level_offset + from - 1
1745
+ process(level + 1, next_level_line, next_level_offset)
1746
+ end
1747
+
1748
+ -- Start searching from right end to implement "balanced" pair.
1749
+ -- This doesn't work with regular balanced pattern because it doesn't
1750
+ -- capture nested brackets.
1751
+ init = (is_same_balanced and to or from) + 1
1752
+ end
1753
+ end
1754
+
1755
+ process(1, line, 0)
1756
+ end
1757
+
1758
+ -- NOTE: spans are end-exclusive to allow empty spans via `from == to`
1759
+ H.new_span = function(from, to) return { from = from, to = to == nil and from or (to + 1) } end
1760
+
1761
+ ---@param candidate table Candidate span to test against `current`.
1762
+ ---@param current table|nil Current best span.
1763
+ ---@param reference table Reference span to cover.
1764
+ ---@param opts table Fields: <search_method>.
1765
+ ---@private
1766
+ H.is_better_span = function(candidate, current, reference, opts)
1767
+ -- Candidate should be never equal or nested inside reference
1768
+ if H.is_span_covering(reference, candidate) or H.is_span_equal(candidate, reference) then return false end
1769
+
1770
+ return H.span_compare_methods[opts.search_method](candidate, current, reference)
1771
+ end
1772
+
1773
+ H.span_compare_methods = {
1774
+ cover = function(candidate, current, reference)
1775
+ local res = H.is_better_covering_span(candidate, current, reference)
1776
+ if res ~= nil then return res end
1777
+ -- If both are not covering, `candidate` is not better (as it must cover)
1778
+ return false
1779
+ end,
1780
+
1781
+ cover_or_next = function(candidate, current, reference)
1782
+ local res = H.is_better_covering_span(candidate, current, reference)
1783
+ if res ~= nil then return res end
1784
+
1785
+ -- If not covering, `candidate` must be "next" and closer to reference
1786
+ if not H.is_span_on_left(reference, candidate) then return false end
1787
+ if current == nil then return true end
1788
+
1789
+ local dist = H.span_distance.next
1790
+ return dist(candidate, reference) < dist(current, reference)
1791
+ end,
1792
+
1793
+ cover_or_prev = function(candidate, current, reference)
1794
+ local res = H.is_better_covering_span(candidate, current, reference)
1795
+ if res ~= nil then return res end
1796
+
1797
+ -- If not covering, `candidate` must be "previous" and closer to reference
1798
+ if not H.is_span_on_left(candidate, reference) then return false end
1799
+ if current == nil then return true end
1800
+
1801
+ local dist = H.span_distance.prev
1802
+ return dist(candidate, reference) < dist(current, reference)
1803
+ end,
1804
+
1805
+ cover_or_nearest = function(candidate, current, reference)
1806
+ local res = H.is_better_covering_span(candidate, current, reference)
1807
+ if res ~= nil then return res end
1808
+
1809
+ -- If not covering, `candidate` must be closer to reference
1810
+ if current == nil then return true end
1811
+
1812
+ local dist = H.span_distance.near
1813
+ return dist(candidate, reference) < dist(current, reference)
1814
+ end,
1815
+
1816
+ next = function(candidate, current, reference)
1817
+ if H.is_span_covering(candidate, reference) then return false end
1818
+
1819
+ -- `candidate` must be "next" and closer to reference
1820
+ if not H.is_span_on_left(reference, candidate) then return false end
1821
+ if current == nil then return true end
1822
+
1823
+ local dist = H.span_distance.next
1824
+ return dist(candidate, reference) < dist(current, reference)
1825
+ end,
1826
+
1827
+ prev = function(candidate, current, reference)
1828
+ if H.is_span_covering(candidate, reference) then return false end
1829
+
1830
+ -- `candidate` must be "previous" and closer to reference
1831
+ if not H.is_span_on_left(candidate, reference) then return false end
1832
+ if current == nil then return true end
1833
+
1834
+ local dist = H.span_distance.prev
1835
+ return dist(candidate, reference) < dist(current, reference)
1836
+ end,
1837
+
1838
+ nearest = function(candidate, current, reference)
1839
+ if H.is_span_covering(candidate, reference) then return false end
1840
+
1841
+ -- `candidate` must be closer to reference
1842
+ if current == nil then return true end
1843
+
1844
+ local dist = H.span_distance.near
1845
+ return dist(candidate, reference) < dist(current, reference)
1846
+ end,
1847
+ }
1848
+
1849
+ H.span_distance = {
1850
+ -- Other possible choices of distance between [a1, a2] and [b1, b2]:
1851
+ -- - Hausdorff distance: max(|a1 - b1|, |a2 - b2|).
1852
+ -- Source:
1853
+ -- https://math.stackexchange.com/questions/41269/distance-between-two-ranges
1854
+ -- - Minimum distance: min(|a1 - b1|, |a2 - b2|).
1855
+
1856
+ -- Distance is chosen so that "next span" in certain direction is the closest
1857
+ next = function(span_1, span_2) return math.abs(span_1.from - span_2.from) end,
1858
+ prev = function(span_1, span_2) return math.abs(span_1.to - span_2.to) end,
1859
+ near = function(span_1, span_2) return math.min(math.abs(span_1.from - span_2.from), math.abs(span_1.to - span_2.to)) end,
1860
+ }
1861
+
1862
+ H.is_better_covering_span = function(candidate, current, reference)
1863
+ local candidate_is_covering = H.is_span_covering(candidate, reference)
1864
+ local current_is_covering = H.is_span_covering(current, reference)
1865
+
1866
+ if candidate_is_covering and current_is_covering then
1867
+ -- Covering candidate is better than covering current if it is narrower
1868
+ return (candidate.to - candidate.from) < (current.to - current.from)
1869
+ end
1870
+ if candidate_is_covering and not current_is_covering then return true end
1871
+ if not candidate_is_covering and current_is_covering then return false end
1872
+
1873
+ -- Return `nil` if neither span is covering
1874
+ return nil
1875
+ end
1876
+
1877
+ --stylua: ignore
1878
+ H.is_span_covering = function(span, span_to_cover)
1879
+ if span == nil or span_to_cover == nil then return false end
1880
+ if span.from == span.to then
1881
+ return (span.from == span_to_cover.from) and (span_to_cover.to == span.to)
1882
+ end
1883
+ if span_to_cover.from == span_to_cover.to then
1884
+ return (span.from <= span_to_cover.from) and (span_to_cover.to < span.to)
1885
+ end
1886
+
1887
+ return (span.from <= span_to_cover.from) and (span_to_cover.to <= span.to)
1888
+ end
1889
+
1890
+ H.is_span_equal = function(span_1, span_2)
1891
+ if span_1 == nil or span_2 == nil then return false end
1892
+ return (span_1.from == span_2.from) and (span_1.to == span_2.to)
1893
+ end
1894
+
1895
+ H.is_span_on_left = function(span_1, span_2)
1896
+ if span_1 == nil or span_2 == nil then return false end
1897
+ return (span_1.from <= span_2.from) and (span_1.to <= span_2.to)
1898
+ end
1899
+
1900
+ H.is_point_inside_spans = function(point, spans)
1901
+ for _, span in ipairs(spans) do
1902
+ if span[1] <= point and point <= span[2] then return true end
1903
+ end
1904
+ return false
1905
+ end
1906
+
1907
+ H.str_utfindex = function(s, i) return vim.str_utfindex(s, 'utf-32', i) end
1908
+ if vim.fn.has('nvim-0.11') == 0 then H.str_utfindex = function(s, i) return (vim.str_utfindex(s, i)) end end
1909
+
1910
+ H.str_byteindex = function(s, i) return vim.str_byteindex(s, 'utf-32', i) end
1911
+ if vim.fn.has('nvim-0.11') == 0 then H.str_byteindex = function(s, i) return vim.str_byteindex(s, i) end end
1912
+
1913
+ -- Work with operator marks ---------------------------------------------------
1914
+ H.get_marks_pos = function(mode)
1915
+ -- Region is inclusive on both ends
1916
+ local mark1, mark2
1917
+ if mode == 'visual' then
1918
+ mark1, mark2 = '<', '>'
1919
+ else
1920
+ mark1, mark2 = '[', ']'
1921
+ end
1922
+
1923
+ local pos1 = vim.api.nvim_buf_get_mark(0, mark1)
1924
+ local pos2 = vim.api.nvim_buf_get_mark(0, mark2)
1925
+
1926
+ local selection_type = H.get_selection_type(mode)
1927
+
1928
+ -- Tweak position in linewise mode as marks are placed on the first column
1929
+ if selection_type == 'linewise' then
1930
+ -- Move start mark past the indent
1931
+ local _, line1_indent = vim.fn.getline(pos1[1]):find('^%s*')
1932
+ pos1[2] = line1_indent
1933
+
1934
+ -- Move end mark to the last non-whitespace character
1935
+ pos2[2] = vim.fn.getline(pos2[1]):find('%s*$') - 2
1936
+ end
1937
+
1938
+ -- Make columns 1-based instead of 0-based. This is needed because
1939
+ -- `nvim_buf_get_mark()` returns the first 0-based byte of mark symbol and
1940
+ -- all the following operations are done with Lua's 1-based indexing.
1941
+ pos1[2], pos2[2] = pos1[2] + 1, pos2[2] + 1
1942
+
1943
+ -- Tweak second position to respect multibyte characters. Reasoning:
1944
+ -- - These positions will be used with `region_replace()` to add some text,
1945
+ -- which operates on byte columns.
1946
+ -- - For the first mark we want the first byte of symbol, then text will be
1947
+ -- insert to the left of the mark.
1948
+ -- - For the second mark we want last byte of symbol. To add surrounding to
1949
+ -- the right, use `pos2[2] + 1`.
1950
+ if mode == 'visual' and vim.o.selection == 'exclusive' then
1951
+ -- Respect 'selection' option
1952
+ pos2[2] = pos2[2] - 1
1953
+ else
1954
+ local line2 = vim.fn.getline(pos2[1])
1955
+ -- Use `math.min()` because it might lead to 'index out of range' error
1956
+ -- when mark is positioned at the end of line (that extra space which is
1957
+ -- selected when selecting with `v$`)
1958
+ local utf_index = H.str_utfindex(line2, math.min(#line2, pos2[2]))
1959
+ -- This returns the last byte inside character because `vim.str_byteindex()`
1960
+ -- 'rounds upwards to the end of that sequence'.
1961
+ pos2[2] = H.str_byteindex(line2, utf_index)
1962
+ end
1963
+
1964
+ return {
1965
+ first = { line = pos1[1], col = pos1[2] },
1966
+ second = { line = pos2[1], col = pos2[2] },
1967
+ selection_type = selection_type,
1968
+ }
1969
+ end
1970
+
1971
+ H.get_selection_type = function(mode)
1972
+ if (mode == 'char') or (mode == 'visual' and vim.fn.visualmode() == 'v') then return 'charwise' end
1973
+ if (mode == 'line') or (mode == 'visual' and vim.fn.visualmode() == 'V') then return 'linewise' end
1974
+ if (mode == 'block') or (mode == 'visual' and vim.fn.visualmode() == '\22') then return 'blockwise' end
1975
+ end
1976
+
1977
+ -- Work with cursor -----------------------------------------------------------
1978
+ H.set_cursor = function(line, col) vim.api.nvim_win_set_cursor(0, { line, col - 1 }) end
1979
+
1980
+ H.set_cursor_nonblank = function(line)
1981
+ H.set_cursor(line, 1)
1982
+ vim.cmd('normal! ^')
1983
+ end
1984
+
1985
+ H.compare_pos = function(pos1, pos2)
1986
+ if pos1.line < pos2.line then return '<' end
1987
+ if pos1.line > pos2.line then return '>' end
1988
+ if pos1.col < pos2.col then return '<' end
1989
+ if pos1.col > pos2.col then return '>' end
1990
+ return '='
1991
+ end
1992
+
1993
+ H.cursor_cycle = function(pos_array, dir)
1994
+ local cur_pos = vim.api.nvim_win_get_cursor(0)
1995
+ cur_pos = { line = cur_pos[1], col = cur_pos[2] + 1 }
1996
+
1997
+ local compare, to_left, to_right, res_pos
1998
+ -- NOTE: `pos_array` should be an increasingly ordered array of positions
1999
+ for _, pos in pairs(pos_array) do
2000
+ compare = H.compare_pos(cur_pos, pos)
2001
+ -- Take position when moving to left if cursor is strictly on right.
2002
+ -- This will lead to updating `res_pos` until the rightmost such position.
2003
+ to_left = compare == '>' and dir == 'left'
2004
+ -- Take position when moving to right if cursor is strictly on left.
2005
+ -- This will update result only once leading to the leftmost such position.
2006
+ to_right = res_pos == nil and compare == '<' and dir == 'right'
2007
+ if to_left or to_right then res_pos = pos end
2008
+ end
2009
+
2010
+ res_pos = res_pos or (dir == 'right' and pos_array[1] or pos_array[#pos_array])
2011
+ H.set_cursor(res_pos.line, res_pos.col)
2012
+ end
2013
+
2014
+ -- Work with user input -------------------------------------------------------
2015
+ H.user_surround_id = function(surr_type)
2016
+ -- Get from user single character surrounding identifier
2017
+ local needs_reminder = true
2018
+ vim.defer_fn(function()
2019
+ if not needs_reminder then return end
2020
+
2021
+ local msg = string.format('Reminder to press %s surrounding id ', surr_type)
2022
+ H.echo(msg)
2023
+ H.cache.msg_shown = true
2024
+ end, 1000)
2025
+ local ok, char = pcall(vim.fn.getcharstr)
2026
+ needs_reminder = false
2027
+ H.unecho()
2028
+
2029
+ -- Terminate if couldn't get input (like with <C-c>) or on `<Esc>`
2030
+ if not ok or char == '' or char == '\3' or char == '\27' then return nil end
2031
+ return char
2032
+ end
2033
+
2034
+ -- Work with positions --------------------------------------------------------
2035
+ H.pos_to_left = function(pos)
2036
+ if pos.line == 1 and pos.col == 1 then return { line = pos.line, col = pos.col } end
2037
+ if pos.col == 1 then return { line = pos.line - 1, col = H.get_line_cols(pos.line - 1) } end
2038
+ return { line = pos.line, col = pos.col - 1 }
2039
+ end
2040
+
2041
+ H.pos_to_right = function(pos)
2042
+ local n_cols = H.get_line_cols(pos.line)
2043
+ -- Using `>` and not `>=` helps with removing '\n' and in the last line
2044
+ if pos.line == vim.api.nvim_buf_line_count(0) and pos.col > n_cols then return { line = pos.line, col = n_cols } end
2045
+ if pos.col > n_cols then return { line = pos.line + 1, col = 1 } end
2046
+ return { line = pos.line, col = pos.col + 1 }
2047
+ end
2048
+
2049
+ -- Work with regions ----------------------------------------------------------
2050
+ H.region_replace = function(region, text)
2051
+ -- Compute start and end position for `vim.api.nvim_buf_set_text()`.
2052
+ -- Indexing is zero-based. Rows - end-inclusive, columns - end-exclusive.
2053
+ local start_row, start_col = region.from.line - 1, region.from.col - 1
2054
+
2055
+ local end_row, end_col
2056
+ -- Allow empty region
2057
+ if H.region_is_empty(region) then
2058
+ end_row, end_col = start_row, start_col
2059
+ else
2060
+ end_row, end_col = region.to.line - 1, region.to.col
2061
+
2062
+ -- Possibly correct to allow removing new line character
2063
+ if end_row < vim.api.nvim_buf_line_count(0) and H.get_line_cols(end_row + 1) < end_col then
2064
+ end_row, end_col = end_row + 1, 0
2065
+ end
2066
+ end
2067
+
2068
+ -- Allow single string as replacement
2069
+ if type(text) == 'string' then text = { text } end
2070
+
2071
+ -- Allow `\n` in string to denote new lines
2072
+ if #text > 0 then text = vim.split(table.concat(text, '\n'), '\n') end
2073
+
2074
+ -- Replace. Use `pcall()` to do nothing if some position is out of bounds.
2075
+ pcall(vim.api.nvim_buf_set_text, 0, start_row, start_col, end_row, end_col, text)
2076
+ end
2077
+
2078
+ H.surr_to_pos_array = function(surr)
2079
+ local res = {}
2080
+
2081
+ local append_position = function(pos, correction_direction)
2082
+ if pos == nil then return end
2083
+ -- Don't go past the line if it is not empty
2084
+ if H.get_line_cols(pos.line) < pos.col and pos.col > 1 then
2085
+ pos = correction_direction == 'left' and H.pos_to_left(pos) or H.pos_to_right(pos)
2086
+ end
2087
+
2088
+ -- Don't add duplicate. Assumes that positions are used increasingly.
2089
+ local line, col = pos.line, pos.col
2090
+ local last = res[#res]
2091
+ if not (last ~= nil and last.line == line and last.col == col) then
2092
+ table.insert(res, { line = line, col = col })
2093
+ end
2094
+ end
2095
+
2096
+ -- Possibly correct position towards inside of surrounding region
2097
+ -- Also don't add positions from empty regions
2098
+ if not H.region_is_empty(surr.left) then
2099
+ append_position(surr.left.from, 'right')
2100
+ append_position(surr.left.to, 'right')
2101
+ end
2102
+ if not H.region_is_empty(surr.right) then
2103
+ append_position(surr.right.from, 'left')
2104
+ append_position(surr.right.to, 'left')
2105
+ end
2106
+
2107
+ return res
2108
+ end
2109
+
2110
+ H.region_highlight = function(buf_id, region)
2111
+ -- Don't highlight empty region
2112
+ if H.region_is_empty(region) then return end
2113
+ local ns_id = H.ns_id.highlight
2114
+
2115
+ -- Indexing is zero-based. Rows - end-inclusive, columns - end-exclusive.
2116
+ local from_line, from_col, to_line, to_col =
2117
+ region.from.line - 1, region.from.col - 1, region.to.line - 1, region.to.col
2118
+ H.highlight_range(buf_id, ns_id, 'MiniSurround', { from_line, from_col }, { to_line, to_col })
2119
+ end
2120
+
2121
+ H.region_unhighlight = function(buf_id, region)
2122
+ local ns_id = H.ns_id.highlight
2123
+
2124
+ -- Remove highlights from whole lines as it is the best available granularity
2125
+ vim.api.nvim_buf_clear_namespace(buf_id, ns_id, region.from.line - 1, (region.to or region.from).line)
2126
+ end
2127
+
2128
+ H.region_is_empty = function(region) return region.to == nil end
2129
+
2130
+ -- Work with text -------------------------------------------------------------
2131
+ H.get_range_indent = function(from_line, to_line)
2132
+ local n_indent, indent = math.huge, nil
2133
+
2134
+ local lines = vim.api.nvim_buf_get_lines(0, from_line - 1, to_line, true)
2135
+ local n_indent_cur, indent_cur
2136
+ for _, l in ipairs(lines) do
2137
+ _, n_indent_cur, indent_cur = l:find('^(%s*)')
2138
+
2139
+ -- Don't indent blank lines
2140
+ if n_indent_cur < n_indent and n_indent_cur < l:len() then
2141
+ n_indent, indent = n_indent_cur, indent_cur
2142
+ end
2143
+ end
2144
+
2145
+ return indent or ''
2146
+ end
2147
+
2148
+ H.shift_indent = function(command, from_line, to_line)
2149
+ if to_line < from_line then return end
2150
+ vim.cmd('silent ' .. from_line .. ',' .. to_line .. command)
2151
+ end
2152
+
2153
+ H.is_line_blank = function(line_num) return vim.fn.nextnonblank(line_num) ~= line_num end
2154
+
2155
+ -- Work with Lua patterns -----------------------------------------------------
2156
+ H.extract_surr_spans = function(s, extract_pattern)
2157
+ local positions = { s:match(extract_pattern) }
2158
+
2159
+ local is_all_numbers = true
2160
+ for _, pos in ipairs(positions) do
2161
+ if type(pos) ~= 'number' then is_all_numbers = false end
2162
+ end
2163
+
2164
+ local is_valid_positions = is_all_numbers and (#positions == 2 or #positions == 4)
2165
+ if not is_valid_positions then
2166
+ local msg = 'Could not extract proper positions (two or four empty captures) from '
2167
+ .. string.format([[string '%s' with extraction pattern '%s'.]], s, extract_pattern)
2168
+ H.error(msg)
2169
+ end
2170
+
2171
+ if #positions == 2 then
2172
+ return { left = H.new_span(1, positions[1] - 1), right = H.new_span(positions[2], s:len()) }
2173
+ end
2174
+ return { left = H.new_span(positions[1], positions[2] - 1), right = H.new_span(positions[3], positions[4] - 1) }
2175
+ end
2176
+
2177
+ -- Work with cursor neighborhood ----------------------------------------------
2178
+ ---@param reference_region table Reference region.
2179
+ ---@param n_neighbors number Maximum number of neighbors to include before
2180
+ --- start line and after end line.
2181
+ ---@private
2182
+ H.get_neighborhood = function(reference_region, n_neighbors)
2183
+ -- Compute '2d neighborhood' of (possibly empty) region
2184
+ local from_line, to_line = reference_region.from.line, (reference_region.to or reference_region.from).line
2185
+ local line_start = math.max(1, from_line - n_neighbors)
2186
+ local line_end = math.min(vim.api.nvim_buf_line_count(0), to_line + n_neighbors)
2187
+ local neigh2d = vim.api.nvim_buf_get_lines(0, line_start - 1, line_end, false)
2188
+ -- Append 'newline' character to distinguish between lines in 1d case
2189
+ for k, v in pairs(neigh2d) do
2190
+ neigh2d[k] = v .. '\n'
2191
+ end
2192
+
2193
+ -- '1d neighborhood': position is determined by offset from start
2194
+ local neigh1d = table.concat(neigh2d, '')
2195
+
2196
+ -- Convert 2d buffer position to 1d offset
2197
+ local pos_to_offset = function(pos)
2198
+ if pos == nil then return nil end
2199
+ local line_num = line_start
2200
+ local offset = 0
2201
+ while line_num < pos.line do
2202
+ offset = offset + neigh2d[line_num - line_start + 1]:len()
2203
+ line_num = line_num + 1
2204
+ end
2205
+
2206
+ return offset + pos.col
2207
+ end
2208
+
2209
+ -- Convert 1d offset to 2d buffer position
2210
+ local offset_to_pos = function(offset)
2211
+ if offset == nil then return nil end
2212
+ local line_num = 1
2213
+ local line_offset = 0
2214
+ while line_num <= #neigh2d and line_offset + neigh2d[line_num]:len() < offset do
2215
+ line_offset = line_offset + neigh2d[line_num]:len()
2216
+ line_num = line_num + 1
2217
+ end
2218
+
2219
+ return { line = line_start + line_num - 1, col = offset - line_offset }
2220
+ end
2221
+
2222
+ -- Convert 2d region to 1d span
2223
+ local region_to_span = function(region)
2224
+ if region == nil then return nil end
2225
+ local is_empty = region.to == nil
2226
+ local to = region.to or region.from
2227
+ return { from = pos_to_offset(region.from), to = pos_to_offset(to) + (is_empty and 0 or 1) }
2228
+ end
2229
+
2230
+ -- Convert 1d span to 2d region
2231
+ local span_to_region = function(span)
2232
+ if span == nil then return nil end
2233
+ -- NOTE: this might lead to outside of line positions due to added `\n` at
2234
+ -- the end of lines in 1d-neighborhood.
2235
+ local res = { from = offset_to_pos(span.from) }
2236
+
2237
+ -- Convert empty span to empty region
2238
+ if span.from < span.to then res.to = offset_to_pos(span.to - 1) end
2239
+ return res
2240
+ end
2241
+
2242
+ local is_region_inside = function(region)
2243
+ local res = line_start <= region.from.line
2244
+ if region.to ~= nil then res = res and (region.to.line <= line_end) end
2245
+ return res
2246
+ end
2247
+
2248
+ return {
2249
+ n_neighbors = n_neighbors,
2250
+ region = reference_region,
2251
+ ['1d'] = neigh1d,
2252
+ ['2d'] = neigh2d,
2253
+ pos_to_offset = pos_to_offset,
2254
+ offset_to_pos = offset_to_pos,
2255
+ region_to_span = region_to_span,
2256
+ span_to_region = span_to_region,
2257
+ is_region_inside = is_region_inside,
2258
+ }
2259
+ end
2260
+
2261
+ -- Utilities ------------------------------------------------------------------
2262
+ H.error = function(msg) error('(mini.surround) ' .. msg, 0) end
2263
+
2264
+ H.check_type = function(name, val, ref, allow_nil)
2265
+ if type(val) == ref or (ref == 'callable' and vim.is_callable(val)) or (allow_nil and val == nil) then return end
2266
+ H.error(string.format('`%s` should be %s, not %s', name, ref, type(val)))
2267
+ end
2268
+
2269
+ H.echo = function(msg, is_important)
2270
+ if H.get_config().silent then return end
2271
+
2272
+ -- Construct message chunks
2273
+ msg = type(msg) == 'string' and { { msg } } or msg
2274
+ table.insert(msg, 1, { '(mini.surround) ', 'WarningMsg' })
2275
+
2276
+ -- Avoid hit-enter-prompt
2277
+ local max_width = vim.o.columns * math.max(vim.o.cmdheight - 1, 0) + vim.v.echospace
2278
+ local chunks, tot_width = {}, 0
2279
+ for _, ch in ipairs(msg) do
2280
+ local new_ch = { vim.fn.strcharpart(ch[1], 0, max_width - tot_width), ch[2] }
2281
+ table.insert(chunks, new_ch)
2282
+ tot_width = tot_width + vim.fn.strdisplaywidth(new_ch[1])
2283
+ if tot_width >= max_width then break end
2284
+ end
2285
+
2286
+ -- Echo. Force redraw to ensure that it is effective (`:h echo-redraw`)
2287
+ vim.cmd([[echo '' | redraw]])
2288
+ vim.api.nvim_echo(chunks, is_important, {})
2289
+ end
2290
+
2291
+ H.unecho = function()
2292
+ if H.cache.msg_shown then vim.cmd([[echo '' | redraw]]) end
2293
+ end
2294
+
2295
+ H.message = function(msg) H.echo(msg, true) end
2296
+
2297
+ H.map = function(mode, lhs, rhs, opts)
2298
+ if lhs == '' then return end
2299
+ opts = vim.tbl_deep_extend('force', { silent = true }, opts or {})
2300
+ vim.keymap.set(mode, lhs, rhs, opts)
2301
+ local no_global_s_mapping = not H.has_global_mapping(mode, 's')
2302
+ if no_global_s_mapping and lhs:find('^s.') ~= nil then vim.keymap.set(mode, 's', '<Nop>') end
2303
+ end
2304
+
2305
+ H.has_global_mapping = function(mode, lhs)
2306
+ for _, map in ipairs(vim.api.nvim_get_keymap(mode)) do
2307
+ if map.lhs == lhs then return true end
2308
+ end
2309
+ return false
2310
+ end
2311
+
2312
+ H.get_line_cols = function(line_num) return vim.fn.getline(line_num):len() end
2313
+
2314
+ H.string_find = function(s, pattern, init)
2315
+ init = init or 1
2316
+
2317
+ -- Match only start of full string if pattern says so.
2318
+ -- This is needed because `string.find()` doesn't do this.
2319
+ -- Example: `string.find('(aaa)', '^.*$', 4)` returns `4, 5`
2320
+ if pattern:sub(1, 1) == '^' then
2321
+ if init > 1 then return nil end
2322
+ return string.find(s, pattern)
2323
+ end
2324
+
2325
+ -- Handle patterns `x.-y` differently: make match as small as possible. This
2326
+ -- doesn't allow `x` be present inside `.-` match, just as with `yyy`. Which
2327
+ -- also leads to a behavior similar to punctuation id (like with `va_`): no
2328
+ -- covering is possible, only next, previous, or nearest.
2329
+ local check_left, _, prev = string.find(pattern, '(.)%.%-')
2330
+ local is_pattern_special = check_left ~= nil and prev ~= '%'
2331
+ if not is_pattern_special then return string.find(s, pattern, init) end
2332
+
2333
+ -- Make match as small as possible
2334
+ local from, to = string.find(s, pattern, init)
2335
+ if from == nil then return end
2336
+
2337
+ local cur_from, cur_to = from, to
2338
+ while cur_to == to do
2339
+ from, to = cur_from, cur_to
2340
+ cur_from, cur_to = string.find(s, pattern, cur_from + 1)
2341
+ end
2342
+
2343
+ return from, to
2344
+ end
2345
+
2346
+ ---@param arr table List of items. If item is list, consider as set for
2347
+ --- product. Else - make it single item list.
2348
+ ---@private
2349
+ H.cartesian_product = function(arr)
2350
+ if not (type(arr) == 'table' and #arr > 0) then return {} end
2351
+ arr = vim.tbl_map(function(x) return H.islist(x) and x or { x } end, arr)
2352
+
2353
+ local res, cur_item = {}, {}
2354
+ local process
2355
+ process = function(level)
2356
+ for i = 1, #arr[level] do
2357
+ table.insert(cur_item, arr[level][i])
2358
+ if level == #arr then
2359
+ -- Flatten array to allow tables as elements of step tables
2360
+ table.insert(res, H.tbl_flatten(cur_item))
2361
+ else
2362
+ process(level + 1)
2363
+ end
2364
+ table.remove(cur_item, #cur_item)
2365
+ end
2366
+ end
2367
+
2368
+ process(1)
2369
+ return res
2370
+ end
2371
+
2372
+ H.wrap_callable_table = function(x)
2373
+ if vim.is_callable(x) and type(x) == 'table' then
2374
+ return function(...) return x(...) end
2375
+ end
2376
+ return x
2377
+ end
2378
+
2379
+ -- TODO: Remove after compatibility with Neovim=0.9 is dropped
2380
+ H.islist = vim.fn.has('nvim-0.10') == 1 and vim.islist or vim.tbl_islist
2381
+ H.tbl_flatten = vim.fn.has('nvim-0.10') == 1 and function(x) return vim.iter(x):flatten(math.huge):totable() end
2382
+ or vim.tbl_flatten
2383
+
2384
+ -- TODO: Remove after compatibility with Neovim=0.10 is dropped
2385
+ H.highlight_range = function(...) vim.hl.range(...) end
2386
+ if vim.fn.has('nvim-0.11') == 0 then H.highlight_range = function(...) vim.highlight.range(...) end end
2387
+
2388
+ return MiniSurround