-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvim.Rmd
2951 lines (1791 loc) · 83.6 KB
/
vim.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Vim Commands"
output:
html_document:
toc: yes
toc_float: true
---
# Introduction
Vim is a modal text editor, to learn how to switch modes, start by the section
[Switch between navigation and editing mode](#navigation_edit). Large part of
this documents have been copied from the vim help accessible through:
:help <topic>
People that I admire use vim.
# Configure vim in .vimrc
See also my vimrc file stored in [setup/.vimrc](setup/.vimrc). Many configuration options are mentioned throughout this document.
Reload the configuration after editing it:
:so ~/.vimrc
Text colour. Add syntax highlight to your .vimrc
syntax enable
## File specific .vimrc options
How to add a file extension to vim syntax highlight
au BufNewFile,BufRead *.dump set filetype=sql
I used it to display markdown files as text files:
au BufNewFile,BufRead *.md set filetype=txt
Make a key combination specific to latex files, to insert a citation key using
the vimtex plugin. Note: ctrl-space appears as ctrl-@ in my terminal
au BufRead,BufNewFile *.tex inoremap <C-Space> <C-x><C-o> | inoremap <C-@> <C-x><C-o>
Prevent tab expanding to space in make files [SO answer](https://stackoverflow.com/a/158990/2641825):
autocmd FileType make set noexpandtab
## Keyboard AZERTY, QUERTZ
* SO [Configure vim for AZERTY keyboards](https://stackoverflow.com/questions/33245317/vim-and-azerty-keyboards)
* Reddit [AZERTY keymapping](https://www.reddit.com/r/vim/comments/2tvupe/azerty_keymapping/)
- Reddit [Vim on CZ
QUERTZ](https://www.reddit.com/r/vim/comments/9bh6ql/vim_on_czqwertz/)
I mapped m to the end of line, maybe I should use m instead?
noremap m $
See also mapping below.
## Colour themes
Be sure to set terminal colour to 256 as explained in an answer
to [a question on vi.stackexchange](https://vi.stackexchange.com/a/25310/6671)
and in the vim wiki [256 colors in vim](https://vim.fandom.com/wiki/256_colors_in_vim)
set t_Co=256
* Slant [vim Theme gallery](https://www.slant.co/topics/480/~best-vim-color-schemes#1)
* [Custom theme aurora](https://github.com/rafalbromirski/vim-aurora)
For a while I used:
set background=dark
colorscheme jellybeans
## Create your own commands
A command that reuses another command can be entered directly after the command
name, separated by a space. To enter normal and insert mode command, you need
to prefix it with "`normal`". See `:help normal` for more information on
executing normal mode commands typed on the command line.
Sample commands that I have in my [.vimrc](setup/.vimrc).
Add the current date
command! Date put =strftime('%Y-%m-%d')
Convert the current line to snake case (1) replace any non alphanumeric
characters by underscores (2) convert to lower case.
command! -range=% Snake s/[^a-zA-Z0-9]\+/_/g | normal Vu
Lexplore with a 30 character size buffer only
command! Ll Lexplore | vert res 30
Display a word diff
command! Gwdiff vert term git diff --word-diff
Create a table of content command based on different tools that depend on the
file type
augroup Toc
autocmd!
autocmd Filetype markdown command! -buffer Toc Voom
autocmd Filetype rmd command! -buffer Toc Voom
" rnoweb are the Rnw notebooks mixing latex and R code
autocmd Filetype rnoweb command! -buffer Toc Voom
autocmd Filetype tex command! -buffer Toc VimtexTocOpen
augroup END
command! TOc Toc
Title inside a script
autocmd FileType python command! Title normal A #<esc>yyppv$r#kkv$r#
Right align columns in tab separated files generated by Nvim-R. After pressing
the <local leader> r v comment to view a data frame.
command! Tt Tabularize /\t/r0
## Key mapping and shortcuts
See
:help map
Show all mappings including <leader> commands:
:map
[How to map the ALT
key](https://vi.stackexchange.com/questions/2350/how-to-map-alt-key)
Explains who to see what key combination is actually seen by the console:
sed -n l
I used this mapping "ALT-;" to insert the pipe "%>%" in R documents:
" The ALT key is mapped to escape in the terminal, remap it
" https://vi.stackexchange.com/questions/2350/how-to-map-alt-key
execute "set <M-;>=\e;"
autocmd FileType r inoremap <M-;> <space>%>%<CR>
autocmd FileType rmd inoremap <M-;> <space>%>%<CR>
This didn't work because the CTRL-; is seen as ; by the terminal:
" Try to map the CTRL+;
autocmd FileType r inoremap <C-;> <space>%>%<CR>
autocmd FileType rmd inoremap <C-;> <space>%>%<CR>
In the end I changed the mapping > to %>% [as explained in NVimR issue 85](https://github.com/jalvesaq/Nvim-R/issues/85):
autocmd FileType r inoremap <buffer> > <Esc>:normal! a %>%<CR>a
autocmd FileType rmd inoremap <buffer> > <Esc>:normal! a %>%<CR>a
[different mappings for CTRL+A and
CTRL+SHIFT+A](https://stackoverflow.com/questions/1506764/how-to-map-ctrla-and-ctrlshifta-differently)
It's generally not possible.
## Minimal .vimrc for bug reports
You can create a minimal .vimrc and use is by calling vim with
vim -u /tmp/.vimrc
See for example this [bug report](https://github.com/lervag/vimtex/issues/1719)
where I used this minimal vimrc file to investigate an issue with the Vimtex
plugin.
set nocompatible
let &runtimepath = '~/.vim/bundle/vimtex,' . &runtimepath
let &runtimepath .= ',~/.vim/bundle/vimtex/after'
filetype plugin indent on
syntax enable
" Use zathura as a PDF viewer
let g:vimtex_view_method = 'zathura'
Or another minimal vimrc to investigate an issue with the nvim-R plugin.
set nocompatible
let &runtimepath = '~/.vim/bundle/Nvim-R,' . &runtimepath
filetype plugin indent on
syntax enable
let maplocalleader = ";"
" enable vim-markdown for .Rmd files too
" This might conflict with the Nvim-R plugin
augroup filetypedetect_markdown
au!
au BufRead,BufNewFile *.Rmd set ft=markdown
augroup END
The solution was to use 2 file types for Rmd files: `set ft=rmd.markdown`.
## Show settings such as file type
Show existing values of settings with a question mark at the end
:set updatetime?
:set signcolumn?
:set filetype?
# Convert
## Pandoc
Vim uses a syntax highlight system that changes quotes and backsticks. It
prevents copy pasting from vim using the tmux copy mechanism. To turn it off
before a copy:
syn off
### From markdown to other formats with pandoc
Convert markdown documents to other formats such as pdf with pandoc.
Convert the current document to html
:Pandoc
Convert the current document to pdf
:Pandoc pdf
Convert the current document to word
:Pandoc docx
Other output -t options from man pandoc
• docx (Word docx)
• html or html5 (HTML, i.e. HTML5/XHTML polyglot markup)
• latex (LaTeX)
• odt (OpenOffice text document)
• pptx (PowerPoint slide show)
Add a yaml front matter to specify more parameters
---
title: "Songs of freedom"
author: "Bob Marley"
geometry: margin=0.5cm
---
### bibliography
To use a bibliography with the pandoc extension insert the following in the
header of the markdown file:
bibliography: /path/to/bibliography/papers.bib
Then the bibliography file should be added to the vim variable
`b:pandoc_biblio_bibs`. You can check it was added correctly by calling:
:echo b:pandoc_biblio_bibs
Once the bibliography files is activated, autocomplete can be called by pressing `CTRL-X CTRL-O` (or
ctrl+space in my case) after `@`. For more see:
:help vim-pandoc-bibliographies-module
Bibliography also works with R markdown documents, see
rmarkdown documentation [authoring bibliographies and citations](https://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html).
# Edit a text file
## Switch between navigation and editing mode {#navigation_edit}
Enter editing mode with `i`, `a`, `o`. Use escape to switch to navigation mode.
Note: I remapped the caps lock key to escape at a system level. See the [Debian
page](debian.Rmd). Some persons remap `jk` and `kj` to escape
([reddit](https://www.reddit.com/r/vim/comments/11fj3x0/comment/jandf3s/?context=3)).
i - Insert text before the cursor.
I - Insert text before the first non-blank in the line.
gi - Insert text in the same position as where insert mode
was stopped last time in the current buffer.
a - Append text after the cursor.
A - Move to the end of the line and switch to editing mode .
o - Begin a new line below the cursor and insert text.
O - Begin a new line above the cursor and insert text.
R - Enter Replace mode: Each character you type replaces an existing character.
When in editing mode you can use escape to enter the navigation mode or use:
alt+h alt+j alt+k alt+l - Switch to navigation mode and move.
alt+: - Switch to navigation mode and send a command.
## Edit a whole line
To edit a whole line:
dd to delete a whole line
yy to copy a whole line
p to paste the copied or deleted text after the current line or
P to paste the copied or deleted text before the current line
## Edit multiple lines
You can edit multiple lines simultaneously by
[inserting text inside a multi-line selection in Vim](https://stackoverflow.com/a/253391) :
Use Ctrl+V to enter visual block mode
Move down with jj to select the columns of text in the lines you want to comment.
Then hit Shift+I and type the text you want to insert.
Then press Escape, the inserted text will appear on all lines.
Similarly to enter text at the end of multiple lines ([vim.wikia](http://vim.wikia.com/wiki/Inserting_text_in_multiple_lines))
Use Ctrl+V to enter visual block mode
Move down with jj to select the columns of text in the lines you want to comment.
Then hit **$** to select all lines until the end of the line.
Then press Shift+A and type the text you want to insert.
The press Escape, the inserted text will appear at the end of all lines.
[How to add text at the end of each line in Vim?](https://stackoverflow.com/questions/11303032/how-to-add-text-at-the-end-of-each-line-in-vim)
> "Visual select a paragraph `vip`, switch to Visual block mode `CTRL V`, append to
> all lines `$A` a comma ,, then press Esc to confirm."
### Delete all lines that contain a pattern
Delete all lines that contain "pattern":
:g/pattern/d
Delete all lines that do not contain a pattern:
:g!/pattern/d
:v/pattern/d
See also:
- https://vim.fandom.com/wiki/Delete_all_lines_containing_a_pattern
- https://superuser.com/questions/265085/how-to-delete-all-lines-that-do-not-contain-a-certain-word-in-vim
### Increment numbers in a list
Use the `range` command as explained in the [vim
wiki](https://vim.fandom.com/wiki/Making_a_list_of_numbers):
:put =range(11,15)
Use the auto incrementation `g CTRL-A`
:help ctrl-a
{Visual}g CTRL-A Add [count] to the number or alphabetic character in
the highlighted text. If several lines are
highlighted, each one will be incremented by an
additional [count] (so effectively creating a
[count] incrementing sequence). {not in Vi}
For Example, if you have this list of numbers:
1. ~
1. ~
1. ~
1. ~
Move to the second "1." and Visually select three
lines, pressing `g CTRL-A` results in:
1. ~
2. ~
3. ~
4. ~
Other example from the vim wiki:
my_array[0] = 0;
Then copy it using `Y6p` (copy the line and paste it six times). The result is:
my_array[0] = 0;
my_array[0] = 0;
my_array[0] = 0;
my_array[0] = 0;
my_array[0] = 0;
my_array[0] = 0;
my_array[0] = 0;
Then select the lines from the second line onwards and use `g CTRL-A` to get:
my_array[0] = 0;
my_array[1] = 0;
my_array[2] = 0;
my_array[3] = 0;
my_array[4] = 0;
my_array[5] = 0;
my_array[6] = 0;
### Filter lines in a csv files
Filter a file in place (seen in a blog post called [Vim
Kōans](https://blog.sanctum.geek.nz/vim-koans/))
:%!awk "/paper/{print $4}"
### Sort lines alphabetically
Select a few lines in visual mode and
:sort
Help sort
With [!] the order is reversed.
:'<,'>sort!
With [i] case is ignored.
:'<,'>sort i
With [u] (u stands for unique) only keep the first of
a sequence of identical lines
Sort outside a pattern
When /{pattern}/ is specified and there is no [r] flag
the text matched with {pattern} is skipped, so that
you sort on what comes after the match.
Instead of the slash any non-letter can be used.
For example, to sort on the second comma-separated
field: >
:sort /[^,]*,/
To sort on the text at virtual column 10 (thus
ignoring the difference between tabs and spaces):
:sort /.*\%10v/
To sort on the first number in the line, no matter
what is in front of it:
:sort /.\{-}\ze\d/
(Explanation: ".\{-}" matches any text, "\ze" sets the
end of the match and \d matches a digit.)
Sort within a pattern
With [r] sorting is done on the matching {pattern}
instead of skipping past it as described above.
For example, to sort on only the first three letters
of each line: >
:sort /\a\a\a/ r
### Reverse selected lines
Super User [reverse selected
lines](https://superuser.com/questions/189947/how-do-i-reverse-selected-lines-order-in-vim)
Select the paragraph and use the GNU `tac` command:
:'<,'>!tac`
To reverse the order of lines in a paragraph, you can use `vip` to select the
current paragraph, followed by `!` which automatically inserts `:'<,'>!`
followed by `tac`. In short what you end up tipping to reverse the current
paragraph is `vip!tac`.
## Edit zip files
It's possible to edit text files inside a zip archive with vim.
Open the file as such:
vim file.zip
## Align columns
The tabular plugin provides a Tabular command which can be abbreviated to
`:Tab`. To align a latex table with the tabular package. Select a few lines, then
press:
:'<,'>Tab /&
Align tab separated text in the current buffer (to view tsv files generated
from data frames by NVim-R for example):
:Tab /\t
Or enter CTRL + V and press the TAB key for a literal tab.
To have numbers right aligned
:Tab /\t/r0
### Markdown table
Similarly to align a markdown table, select a few lines, then call:
:'<,'>Tab /|
For more, see `help tabular`.
## Undo redo
u: undo last change (can be repeated to undo preceding commands)
Ctrl-R: Redo changes which were undone (undo the undos).
Compare to '.' to repeat a previous change, at the current cursor position.
Ctrl-R will redo a previously undone change, wherever the change occurred.
### Navigate the change list
Jump to previous or next editing position `:help g;`
> When making a change the cursor position is remembered. One position is
> remembered for every change that can be undone, unless it is close to a
> previous change. Two commands can be used to jump to positions of changes,
> also those that have been undone:
>
> *g;* *E662*
> g; Go to [count] older position in change list.
> If [count] is larger than the number of older change
> positions go to the oldest change.
> If there is no older change an error message is given.
> (not a motion command)
> {not available without the |+jumplist| feature}
>
> *g,* *E663*
> g, Go to [count] newer cursor position in change list.
> Just like |g;| but in the opposite direction.
> (not a motion command)
> {not available without the |+jumplist| feature}
## Replace characters
Vim help on search and replace `:help :s`
> `[range]s[ubstitute]/{pattern}/{string}/[flags] [count]`
> For each line in `[range]` replace a match of `{pattern}` with `{string}`.
For example find each occurrence of 'red' (in the current line only), and
replace it with 'green':
:s/red/green/g
The `s` command means "substitute".
The `g` means "greedy", it will replace all occurrences of the word on a line
(not just the first occurrence).
When [text is visually selected](http://vim.wikia.com/wiki/Search_and_replace_in_a_visual_selection),
press : to enter a command. The command line will automatically enter the range:
:'<,'>
Then you can enter a replacement command such as `s/red/green/g`
to replace each occurence of "red" with "green"
in all lines of the visual selection. The command will appear as:
:'<,'>s/red/green/g
Find each occurrence of 'red' in all lines (`%s`), and replace it with 'green'.
:%s/red/green/g
Find each occurence of foo but don't perform the replacement, only count the number of occurences
:%s/foo/bar/n
To replace by a new line character, use `\r` instead of `\n`.
For example to insert a new line after each comma in a selection:
:'<,'>s/,/,\r/g
To replace double line breaks by a single line brake
:%s/\n\n/\r/g
You can use replacement to remove text.
For example to [remove the last 2 characters of each line in a selection](https://stackoverflow.com/a/36264759/2641825) :
:'<,'>s/..$//
In case you have slashes in the pattern, you can use another separator such as
`#`
:%s#/path/to/file#/new/path#g
See also:
- https://stackoverflow.com/questions/11823616/how-to-include-forward-slash-in-vi-search-replace
### Abbreviations and boilerplate code
Add a read counter item to a list of papers to read
iabbrev azer - {1}
- Vim wiki [abbreviations](https://vim.fandom.com/wiki/Use_abbreviations_for_frequently-used_words)
iabbrev teh the
- [SO question on boilerplate code](https://stackoverflow.com/questions/55469524/how-to-write-vim-function-to-paste-a-template-text-into-current-file)
### Collection
See `:help collection`: "A collection is a sequence of characters enclosed in brackets."
Example matches ~
[xyz] any 'x', 'y' or 'z'
[^xyz]" anything but 'x', 'y' and 'z'
[a-zA-Z]$ any alphabetic character at the end of a line
For example to replace all characters but the pipe (to create a separation in a
markdown table):
:'<,'>s/[^\|]/-/g
### Confirm replacement
Find and replace with confirmation
:%s/old/new/gc
Press `y` or `n` to confirm each replacement individually.
### Convert to lower-case
[Switching case of characters](https://vim.fandom.com/wiki/Switching_case_of_characters):
Toggle case "HellO" to "hELLo" with g~ then a movement.
Uppercase "HellO" to "HELLO" with gU then a movement.
Lowercase "HellO" to "hello" with gu then a movement.
For example to convert to lower case from the cursor to the end of the line:
gu$
To change the current line from upper to lower case:
guu
### Grouping and back references
http://vimregex.com/ Grouping and Backreferences
> "ou can group parts of the pattern expression enclosing them with `"\(" and
> "\)"` and refer to them inside the replacement pattern by their special
> number \1, \2 ... \9. Typical example is swapping first two words of the
> line:
s:\(\w\+\)\(\s\+\)\(\w\+\):\3\2\1:
> " where \1 holds the first word, \2 - any number of spaces or tabs in between
> and \3 - the second word. How to decide what number holds what pair of \(\) ?
> - count opening `"\("` from the left. "
#### Keep only quoted strings
A simpler version in the case of character strings only
:'<,'>s/.*\(".*"\).*/\1/g
# Paste ready version
s/.*\(".*"\).*/\1/g
Suggestion and explanation by Chat GPT
:'<,'>s/.*\("\([^"]\+\)"\).*/\1/g
Explanation:
- `.*` Matches any character zero or more times.
- `\("([^"]\+)"\)` This is the capturing group for the quoted string. It
captures anything between quotes and stores it in \1.
- `.*` Matches any character zero or more times.
- `\1` This replaces the entire line with just the first capturing group, which
is your quoted string.
### HTML markup
[Remove html tags, not the
content](https://stackoverflow.com/a/6264260/2641825)
yitvatp
### Markdown fixes
Several search and replace patterns to fix text copied from web pages or pdf
files into markdown.
Place quotes around variables that contain a dollar sign (otherwise
interpreted as a formula start in markdown):
:'<,'>s/\(\w*\$\)/`\1`/g
Remove hyphenation at the end of lines in a paragraph
:'<,'>s/\(\i\)- /\1/g
I put this into a command in my \ `.vimrc`
command! -range=% Hyphen <line1>,<line2>s/\(\i\)- /\1/g
TODO: "the 30- year average" should not be replace but only by a space.
### Regex patterns
To place quotes around variables that contain a dollar sign (otherwise
interpreted as a formula start in markdown):
:'<,'>s/\(\w*\$\)/`\1`/g
[add quotes at the start and end of each
line](https://stackoverflow.com/a/3218805/2641825)
:%s/^\(.*\)$/"\1"/
> s/regex/replace/ is vim command for search n replace.
> % makes it apply throughout the file
> ^ and $ denotes start and end of the line respectively.
> `(.*)` captures everything in between. ( and ) needs to be escaped in vim regexes.
> \1 puts the captured content between two quotes.
Remove bracketed references from text copied from Wikipedia.
:'<,'>s/\[[0-9]\+\]//g
#### Character classes
See also patterns below.
See `:help character-classes` for a list of classes accepted in Vim with their
equivalent regex pattern, for example `\w` is equivalent to `[0-9A-Za-z_]`.
Replace all word characters by a dash (to create a markdown table division see
also collection below)
:'<,'>s/\w/-/g
Note that this only works with ASCII characters and doesn't work with accentuated characters.
For example `smöl` gets replaced by `--ö-`.
To replace all identifier characters, use
:'<,'>s/\i/-/g
And then `smöl` gets replaced by `----`.
#### Numbers
Insert Markdown title marker `#` before a number at the beginning of a line
%s/^\(\d.\)/# \1/g
Note `\0` matches the hole pattern. Use backslash-escaped parenthesis to match
a particular pattern. `\d` matches any digit.
Remove bracketed references from text copied from Wikipedia.
:'<,'>s/\[[0-9]\+\]//g
Remove all numbers in a list of authors
:'<,'>s/\d//g
#### Or
Replace this or that with a dot
:%s/this\|that/./g
Replace opening or closing curly braces by two curly braces
:'<,'>s/{/{{/g | s/}/}}/g
### Replace list items
Replace simple list items with a curly braces counter (to count the number of times I
want to read a publication or a paper). I have created a shortcut for this
substitution.
:'<,'>s/\n- /\r- {1} /g
#### Replace file names with markdown links
List files in the present working directory and replace them with a markdown
link:
:.!ls
:'<,'>s/.*/[&](&)/g
### Replace spaces and new lines
Vim wiki [Remove unwanted
spaces](https://vim.fandom.com/wiki/Remove_unwanted_spaces#Automatically_removing_all_trailing_whitespace):
> In a search, \s finds white space (a space or a tab), and \+ finds one or
> more occurrences.
Command to replace repeated white spaces by a single white space in a selection:
:'<,'>s/\s\+/ /g
SO [vim regex replace multiple consecutive spaces with only one
space](https://stackoverflow.com/questions/3860532/vim-regex-replace-multiple-consecutive-spaces-with-only-one-space)
proposes multiple other solutions, this one derived from Aristotle's answer
keeps indentation white spaces at the beginning of the line:
:'<,'>s/[^\s]\zs\s\+/ /g
Remove all beginnings of line. :%s/\option\n/, /g replace all end of line by
comma + space. This cleans an html list of species for inclusion in a text.
%s/option value=".*"//g
This pattern replaces one or more white spaces with a pipe, to create markdown
tables:
:'<,'>s/\s\+/|/g
This pattern removes spaces at the end of the line:
:'<,'>s/\s*$//g
### Visual selection
To search and replace in a visual selection, select an area then press `:`. The
line will automatically begin with `:'<,'>`, you can then enter the patterns.
:'<,'>s/search/replace/g
For [a vertical selection](https://stackoverflow.com/a/25276670/2641825), this
doesn't work automatically and you have to use
:'<,'>s/\%Vsearch/replace/g
To replace a visual selection by inserting new text at the keyboard in insert
mode, use `c` for change:
c
## Copy, cut and paste
Copy
yy The current line
yiw The current word
ye To the end of the current word
yip The current paragraph
yG To the end of the document
Paste with `P` (before) or `p` (after) the cursor.
Copy just one character
vy
Copy and paste in visual mode with the following instructions:
Position the cursor where you want to begin cutting.
Press v (or upper case V if you want to cut whole lines).
Move the cursor to the end of what you want to cut.
Press d to cut or y to yank (copy into the `"0` register).
Move to where you would like to paste.
Press P to paste before the cursor, or p to paste after.
Copy to a system register (to be used by other programs)
"+yy
"+yip
See also the section on registers below and `:help "+` for more details on
system registers.
### Paste the current line many times
Press `Y6p` to copy the following line 6 times
- example
### Paste from the system register
When pasting from the system register i.e. with `Ctrl+Shift+V` you need to prevent auto indent
otherwise vim will mess with the indentation. This can be solved with bracketed
paste, see further down below.
As explained in [Paste without autoindent](https://stackoverflow.com/a/2545242/2641825)
You can either read from the shell with:
:r! cat
And then paste `CTRL + SHIFT + V` the content, and `CTRL+D`.
Also works over SSH.
Or use
:set paste
:set nopaste
Set up a shortcut to toggle paste mode on and off with:
set pastetoggle=<F3>
Note: I don't use paste toggle any more, bracketed paste works well.
#### Bracketed paste
[Enable bracketed paste in a session](https://stackoverflow.com/a/44507798/2641825)
bind 'set enable-bracketed-paste on'
### Registers
[How to use vim registers](https://stackoverflow.com/a/1498026/2641825)
>" Registers in Vim let you run actions or commands on text stored within them.
> To access a register, you type "a before a command, where a is the name of a
> register. If you want to copy the current line into register k, you can type
"kyy
> Or you can append to a register by using a capital letter
"Kyy
> You can then move through the document and paste it elsewhere using
"kp
To display the content of all registers:
:registers
For example yank the word "yank", delete the word "delete" and copy the word
"system" outside of vim in any program will give you the following registers:
:registers
--- Registers ---
"" delete
"0 yank
"- delete
"* system
"+ system
". ^@yank^@delete^@
To clean vim registers as explained on a [SO
answer](https://stackoverflow.com/a/41003241/2641825), enter this at the vim
prompt:
for i in range(34,122) | silent! call setreg(nr2char(i), []) | endfor
### Replace a word
[How can I do a change word in vim using the current paste
buffer](https://unix.stackexchange.com/questions/88714/how-can-i-do-a-change-word-in-vim-using-the-current-paste-buffer)
Select the current word, then select the word to replace and paste
ye
vep
Or select the current word, then paste and delete the word to replace
ye