I am often burdened with "converting" and "including" stuff into larger documents. I have compiled some scripts and voodoo to ease my work but rather often I'm still facing the task of manually converting a list given to me as plain text into LaTeX, for example:
1. Foo
2. Bar
When doing so, I select the plain text list in visual mode and replace the prefix with \item
. In this example s/^../\\item/
yields:
\item Foo
\item Bar
Then I select the list again and hit F5 and when asked which environment I want i type itemize
(or whatever) and this finally leads to what I want:
\begin{itemize}
\item Foo
\item Bar
\end{itemize}
My question is: How can I create a shortcut in Vim that does both steps in one? Ultimately I just want to select a list and hit F6.
Of course I will need to redefine the function (or just global variables) ocationally to use a different pattern when replacing prefixes with \item and to use different environments. I think I can do that once I have the initial shortcut/function working.
Best Answer
If your list of lines is surrounded by blank lines, the following mapping will work:
Place the cursor anywhere in your numbered list and press F6
Update
A more general approach is to search backwards until the first line which does not start with a digit, and select from that until the last line which starts with digit. In the selected range, the digits are replaced by
\item
. Then we have to mark again the same range to comvert it into anitemize
, and this is tricky because we cannot use the same regexp to select (because the digits were replaced). We can use vi "marks" to mark the points when we find them, and use those marks to select again the same set of lines. The following mapping does all this (and uses mark namesa
andb
):Perhaps it can be illustrative to dissect that black magic:
:map <f6>
creates a mapping for key F6. When that key is pressed, the following sequence of keystrokes will be "executed".?^\D<cr>
Moves the cursor to the first line (backwards) which matches the regexp^\D
, which means "beginning of line followed by a non-digit"j
Advances to the next linema
stores the current cursor position in marka
V
starts selection in visual mode/<cr>
advances to the next line (forward) which matches the last used regexp, i.e. to the first line which starts with a non-digit char.k
moves to previous linemb
stores the cursor position in markb
:s/^../\\item/<cr>
replaces the two first chars of each line in the selected range by\item
'a
moves to the stored marka
(beginning of the selection)V
starts visual selection again'b
moves to markb
. At this point we have selected again the set of\item
s<f5>itemize<cr>
presses key F5 and selectsitemize
environment. This calls alatex-suite
macro which encloses the selection in anitemize
environment.This cover the cases in which there are blank lines between items, and non-blank lines surrounding them.