I am using vim-latexsuite to edit a latex file. The text is originally from google doc and there are many math symbols not written in math mode.
I have to add $ before and after each symbol. But that is painful. (Search/Replace does not work because some equation patterns are complicated.)
Is there a way that allows me to visually select the symbols or equestions using Ctrl-V in visual mode, then after pressing the key, the $ can be automatically added before and after the visual selection?
I don't think there is any standard command for this, but you can use the surround.vim plugin to do this:
http://www.catonmat.net/blog/vim-plugins-surround-vim/
The command is csW$ to surround the current text with $
There actually is a standard command for this built into vim-latexsuite. See the vim-latex docs for macros here.
In addition the visual mode macros are provided:
`( encloses selection in \left( and \right)
`[ encloses selection in \left[ and \right]
`{ encloses selection in \left\{ and \right\}
`$ encloses selection in $$ or \[ \] depending on characterwise or
linewise selection
You can record a macro to do this.
With a visual selection, do this:
qq – record macro in register q
c – change the content of the visual selection
$$Esc – insert $$
P – paste the original text between the $s (note it's a capital P)
q – stop recording the macro
From then on, you can make your visual selection and just run #q.
Related
I want to replicate the VS code feature of 'highlight and comment out code' (usually bound to keys SHIFT + /) in vim.
I can run :g//s/^/\/\/ / in normal mode to prepend // at the start of every line. I just want to put a constraint on this so it only applies the substitution to lines highlighted in visual mode.
Visually select all the lines (using V), then hit :.
This will give you :'<,'> which is the range of your visual selection.
Then you can add your vim command to it.
I would recommend the following method if you wish to not use plugins.
:'<,'>normal I//
Which is not a substitution.
If you want a really nice vim plugin that does this task in a vim manner, check out tpope's vim-commentary which is an essential in my opinion.
I can run :g//s/^/\/\/ / in normal mode to prepend // at the start of every line.
Well, that would be an unnecessarily complicated way to do it and your command wouldn't really work anyway.
:g// either matches nothing or it matches the previous search. What you want, here, is probably something like :g/^/ or :g/$/.
A simple substitution on the whole buffer would be much simpler and much faster:
:%s/^/\/\/ /
Using :help :global in this context provides no value (you want to operate on every line anyway) and is considerably slower (we are talking thousands of times slower)
You can use alternative separators to avoid all that backslashing:
:%s#^#// #
The last separator is not even needed:
:%s#^#// <-- there is a space, here
And the kicker: you can enter command-line mode from visual mode like you would do from normal mode, by pressing :. So you can simply make your visual selection, press :, and run your substitution:
v " enter visual mode
<motion> " expand the selection
: " press :
:'<,'> " Vim inserts the range covering the visual selection for you
:'<,'>s#^#// <CR> " perform your substitution
I have the following paragraph in a plain text file that I am viewing (and editing) in Vim:
The synthesis and secretion of estrogens is stimulated by follicle-stimulating hormone (FSH), which is, in turn, controlled by the hypothalamic gonadotropin releasing hormone (GnRH). High levels of estrogens suppress the release of GnRH (bar) providing a negative-feedback control of hormone levels.
I am creating cloze deletion flashcards out of the text in this text file (ie. fill in the blank questions) which I will then feed to a home-made flashcard program I've written. My format for a cloze deletion is as follows:
The synthesis and secretion of [estrogens] is stimulated by [follicle-stimulating hormone]
This would produce two flashcards (when the text file is parsed by my flashcard program):
The synthesis and secretion of [...] is stimulated by follicle-stimulating hormone
The synthesis and secretion of [estrogens] is stimulated by [...]
I would like to automate the creation of these flashcards using Vim. The manual option would be to write a '[' to the beginning of each cloze deletion and a ']' at the end, but this is tedious and I'd like to use Vim's automation abilities. Ideally, I would like to be able to:
select a region of text to clozeify
execute a macro on this text
This macro would:
prepend '[' to the selection
append ']' to the selection
and exit.
How would I achieve this using Vim? When I try to use Ctrl-R in Visual Selection Mode it doesn't seem to work.
Essentially, the replacement I would like to do is:
:%s/(CONTENT OF VISUAL SELECT)/[(CONTENT OF VISUAL SELECT)]/g
This is very easy to do with built-in commands:
v<motion>
c[<C-r>"]<Esc>
Breakdown:
v<motion> is what you already do to visually select the text to transform.
c cuts the visually selected text to the unnamed register and puts you in insert mode.
[ inserts an opening bracket.
<C-r>" inserts the content of the unnamed register.
] inserts a closing bracket.
<Esc> puts you back into normal mode.
With that in mind, you can record a macro of the edit above and play it back on any visual selection:
v<motion>
qq
c[<C-r>"]<Esc>
q
then:
v<motion>#q
Breakdown:
qq starts recording in register q.
q stops recording.
or create a visual mode mapping:
xnoremap <key> c[<C-r>"]<Esc>
If that's something you need to do often, you should probably take a look at Surround or Sandwich, which make all that considerably easier.
Reference:
:help c
:help i_ctrl-r
:help recording
I modified some code I found here to work for LaTeX. I demonstrate the desired output for two cases. Please have a look at
Dealing with LaTeX Commands
Dealing with LaTeX Environments
http://vim.wikia.com/wiki/Wrap_a_visual_selection_in_an_HTML_tag
Dealing with LaTeX Commands
Given:
elephant
visually select "elephant"
press F7
enter "test"
Output:
\test{elephant}
Example Code Code for VisualcommandTagWrap
This works for singleline selections. I'd like to make it work for multiline selections.
Simply select text to wrap using your visual selector, then press F7.
" Wrap visual selection in a latex command tag.
map <F7> : call VisualcommandTagWrap()
function! VisualcommandTagWrap()
let tag = input("Tag to wrap block: ")
if len(tag) > 0
normal `>
if &selection == 'exclusive' "set selection=exclusive means position before the cursor marks the end of the selection vs. inclusive
exe "normal i\\".tag."}"
else
exe "normal a\}"
endif
normal `<
exe "normal i\\".tag."{"
normal `<
endif
endfunction
Dealing with LaTeX Environments
Given:
elephant
visually select "elephant"
press F7
enter "test"
Output:
\begin{test}
elephant
\end{test}
Example Code for VisualenvironmentTagWrap
I do not know how to implement functions that cover multiple lines.
Additional Examples
For those unfamiliar with LaTeX. There are two situations to satisfy requirements for LaTeX commands and environments.
Here is some visual mode selected text.
And another line of visual mode selected text.
Command Situation:
type function key defined in .vimrc to call function
vim prompts for user input (e.g. "Please enter name of command:")
vim surrounds selection with command.
Result:
\inputstep2{Here is some visual mode selected text.
And another line of visual mode selected text.}
Environment Situation
type function key defined in .vimrc to call function
vim prompts for user input (e.g. "Please enter name of environment:")
vim surrounds selection with environment.
Result:
\begin{inputstep2}
Here is some visual mode selected text.
And another line of visual mode selected text.
\end{inputstep2}
Step 1:
You can store the text you want (like test) in register a.
:let #a='test'
(Until you change it, it will remain the same and can be reused. If you want it to be changed, you have to follow the step again.)
Step 2:
Then, select the the text using visual selection (v, V or ctrl V) and then press escape to cancel the selection.
Step 3;
Keep the cursor on anywhere in the screen, (preferably in the line where you want to surround with) and press \s in normal mode.
Put the following mapping in ~/.vimrc file.
Let's create a mapping to wrap around.
For first example: (begin and end type)
:nmap \s '<O\begin{<C-R>a<ESC>}'>o\end{<C-R>a}
For second example: (begin type)
:nmap \s '<O\{<C-R>a<ESC>'>a}
Is there a motion for moving to the start or end of a visual selection?
I know that o while in visual mode alternates between the two, but I need to be able to select precisely the start.
The overall goal is to surround a visually selected area with parentheses.
Follow-Up:
Based on the comments, I was able to implement this using the following macro. The idea is to:
Esc to exit visual mode;
`> to go to the end of the previous visual selection;
a) to append a closing parentheses;
Esc to exit insert mode;
`< to go to the start of the previous visual selection;
i( to insert an opening parentheses;
Esc to exit insert mode again.
For example:
map \q <ESC>`>a)<ESC>`<i(<ESC>
Based on another comment, we have an even more concise solution:
map \q c()<ESC>P
There are two relevant built-in marks holding the positions of the first
and last characters of the last visual selection in the current buffer.
In order to move the cursor to these marks, use the commands `<
and `>, respectively (see :help `> and :help `<).
While you are in Visual Selection click o. It will change position of cursor to other end of selection. Then O to jump back.
The easiest way to "surround a visually selected area with parentheses" is:
change the visually selected area to () and Put it back in the middle: c()<ESC>P
I suggest defining in the .vimrc file a new visual-mode command (e.g., \q) with that:
:vmap \q c()<ESC>P
This approach also works with visual rectangular areas (<C-V>): it
puts ( and ) around each block-line.
if you just want to surround a visual selection there has already work been done, namely by tim pope, who wrote this plugin called surround. It surrounds words or visual selection with delimiters of your liking.
select your visual selection, say i like vim hit S) to get (i like vim) or S( to get ( i like vim ), to change this to [i like vim] type cs] (change surrounding) and to delete ds] to get i like vim at last.
If you can't use Surrond.vim, here is one way to do it:
Do your visual selection with v or V.
Get out of it with <Esc>.
Type `>a)<Esc> to insert a closing parenthesis after the last character of the selection.
Type `<i(<Esc> to insert an open parenthesis before the first character of the selection.
I'm relatively new to the world of Vim. I've been learning my way around it but have yet to find a practical purpose to enter visual mode.
What are some scenarios when visual mode is especially useful?
Are there actions that can only be performed from within visual mode?
I use visual mode when I want to highlight a section of text. I start by typing v in standard mode, which then enables the visual mode. Then I use the arrow keys to move the cursor. This causes the text between my starting point and the current cursor location to be highlighted. Once you select a section of text like this, entering a command (e.g. search/replace) in command mode (by typing :) will only affect the selected area.
Another useful visual command is shift+v (visual line). This does the same as above, but it selects entire lines at a time instead of individual characters.
When you want to comment a block of text.
In command mode :
Shift + v
,ctrl +v,
j or k,
I , #(comment
character) and then Esc
Vim inserts the comment character to
the start of the block..
is when I am using Gvim, I find it much easier to copy data
to the clipboard through visual mode.
In command mode :
Shift + v
, j or k ,
" , +
,y
Here + is the clipboard
register
This to me is much more legible that using markers
is for manual indenting
Shift + v,
Shift + > for
moving to the right.
Shift + < for
moving to the left. .
repeats
this is fun :-)
One of the nice things about visual mode is that, because of Vim's focus on modality, you can perform most of the commands that you are used to (such as search/replace with :s, d to delete text, or r to replace text) while also seeing exactly what will be affected -- this allows you to determine the exact scope of whatever you are doing.
Furthermore, as someone else mentioned, you can easily insert a prefix (like a comment character or, say, & for alignment or \item in LaTeX) by selecting the first character of each line in visual block mode (ctrl+v), pressing I to insert before the first character, typing in whatever you want to insert, and then Escing back to normal mode.
The last kind of visual mode is visual line (Shift+v), which allows you to quickly select a number of lines. From there, you can change their indentation using > or < (prefix this with a number to indent by that many tabs), use d or y to delete or copy those lines, use zf to create a new fold from those lines, or use any other selection-based command.
Finally, there are a lot of other cool things you can do with visual mode, including gv to reselect your last visual[line/block] mode selection, gU to convert a visual selection to uppercase or gu for lowercase, and many more.
In addition to the other (great) answers, it's an easy way to define scope for an action. For example, to limit a search & replace to a specific method...
Say you have this code:
function foo() {
abc();
while (1) {
def();
abc();
}
}
You can place the cursor on any of the braces or parentheses and press v, %, :, s/abc/xyz/g and your search & replace will have a defined scope in which the action will occur.
Visual mode is useful if you want to apply a command to a section of text that isn't easily described as a primitive movement command. You can select some text in visual mode with a complex sequence of movements and then apply a command to that selection.
I often find myself using visual-block mode (Ctrl + v) more than any of the other visual modes.
You can easily remove indentation, comments, etc. once you are aware of this mode. In my experience, this is often faster than figuring out how to form an equivalent search-and-delete statement.
You can also add indentation (or comments as Cherian stated) by selecting a block of text and pressing I, typing whatever you want to add, and pressing Esc (note: you may need to redraw the screen (e.g. by moving the cursor) to see the effects of this).
I haven't seen the following mentioned, probably because they're subtle.
1 - Less hassle with the unnamed register
Whenever you copy (yank) some text, and then want to d to change some other text, e.g., diw to "delete inner word," Vim will place the deleted text into the unnamed register. Then if you try to paste, it will just paste the deleted text right back unless you do "0p to paste from the 0 register.
But with visual mode, you can just do something like viwp and don't have to mess with registers.
So, for comparison, to copy and replace inside some parens:
yiw -> move somewhere -> vi(p
vs
yiw -> move -> ci(<C-r>0p
yiw -> move -> "_di(p
yiw -> move -> di("0P
Note: this also works for deleting text and pasting it back over a text object. See here.
2 - Jumping to parts of a text object
If you want to jump to the beginning or end of a text object, you can select it in visual mode and press o. For example, va" to select anywhere inside quotes, and then press o to jump to the matching quotes, kind of like % for matching brackets.