Faster way to type control flow statements (in C and php etc)? - vim

I am new to Vim and I need to speed up my typing for this kind of statements.
if (a == 'e') {
foo();
}
In other text editors, I usually type if() {} first and then insert the text in to the parenthesis and curly braces. If I do this in Vim, I need to switch back to normal, move cursor to middle of () then middle of {}... switch between i and esc ...
What is your suggestion on typing this kind of syntax for Vim beginner? I would be grateful if you can show me the commands for that example step by step.

This is a job for snippet expansion. Take a look at SnipMate or UltiSnips.

snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.

There are two approaches that solves your goal:
abbreviations
and snippets engines
Abbreviations and the old way of doing things. You just type if and space, and tada! You'll find plenty examples around the web. Only a few will be context-sensitive (i.e. they won't expand within comment or string contexts), or able to take the current project spacing style into consideration. In lh-cpp, you'll find the usual control-statement abbreviations for C and C++, they'll need to be duplicated for similar languages (a runtime ftplugin/c/c_snippets.vim from a php ftplugin should do it in your case)-- in lh-misc I support a couple of others languages (for VimL and shell)
Snippet engines are the trendy way of doing the same thing. This time, you will be able to type i or if and then <tab> (or CTRL+SPACE, or ...). Control-statement snippets won't need to be aware of the current context as we need to explicitly require the expansion. Others have already given links to the trendy snippets engines. Snippets from lh-cpp (which relies on mu-template) take the project style into account when expanding control-statement snippets (i.e. some projects want ) and { on a same line, other want a newline in between, ...)

Here's my answer in case you want to go with vanilla Vim.
In the majority of the cases I guess there is no point in entering the parentheses first and filling in the condition later, just type it all in right away:
if (a == 'e')
Then you can either continue
by typing {}<ESC>:
if (a == 'e') {}
^ cursor is here
The cursor is already placed so you can continue with i<CR> and type the body (if properly configured, Vim should indent for you).
or by typing {<CR>}<ESC>:
if (a == 'e') {
}
^ cursor is here
Then you can enter the body by pressing O (open new line above cursor). Possibly Vim also automatically indents here (it doesn't in my configuration).
If you really want to fill in the condition after you have entered this:
if () {
}
^ cursor
you can do so by typing kf(a.
If anybody knows better ways to do this without plugins, suggestions are welcome.

Related

Vim generate text expansion from shortcut

The codebase I'm working on requires standard comments around any modifications that we make:
// -----------ABCD---------------
and then
// ----------\ABCD---------------
What's the best way to map a short combination of keys like -abcd and \abcd to generate these longer strings?
The simplest, built-in :help abbreviations:
inoreab abcd // -----------ABCD---------------
inoreab abcD // ----------\ABCD---------------
Why did I choose different triggers? There are some rules (documented as "three types of abbreviations" under the above help link) for the allowed keys; the easiest is that it's all keyword characters.
If you insist on those exact triggers, you'd have to fiddle with the 'iskeyword' option (which can affect syntax highlighting and motions!), or switch to :inoremap. The downside of that is that you won't see the typed characters until any ambiguity has been resolved (try it; you'll see what I mean).
ABCD is just a dummy; I need dynamic text here
If multiple abbreviations won't do, you'll need snippets.
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki and this comparison by Mark Weber.
A snippet would look like this (snipMate syntax):
snippet abcd
// -----------${1:ABCD}---------------
${2:content}
// ----------\$1---------------
${3}

A better way to write int main(){}

I recently started to use vim.
When I start coding, I usually start with following format.
('_' denotes the location of a cursor.)
int main(){
_
}
Here is what I have done
1. type int main(){}
2. ctrl-o h (move left)
3. enter twice
4. ctrl-o k (move up)
5. tab (indent)
The problem is that, it takes so many key strokes.
I am wondering if there is a better way to do this.
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.
Things as simple as C&C++ main() are already defined in all snippet plugins and even in specialized plugins like lh-cpp (I'm maintaining this one) or c.vim.
You could also do it by yourself with abbreviations, but then you'll have to detect whether you're in a code or a string/comment context. You could define your own snippet plugin, but there already are many of them.

How to script in Vim to yank only lines from a visual selection (or fold) that match a certain pattern?

I'd like to add a command to my .vimrc that allows to, within a visual selection or the range of the current fold level to
yank all, but only those lines that match a certain pattern.
and as a bonus to
reverse their order
and
perform a small pattern substitution.
Specifically the idea is to reduce the legwork in writing the common C idiom fail-goto-rollback, i.e. (can be found in lot of C projects most prominently the Linux kernel) if the body of a function (or a block) is this
someErrorType errorcode;
if(fail1) {
errorcode = someError1;
goto error_1;
}
prepare_a();
if(fail2) {
errorcode = someError2;
goto error_2;
}
then the result of the desired transformation shall be this.
error_2:
/* <insert cleanup code operation that did not fail1 here> */
error_1:
for the "yanking all", you can do:
normal mode: qaq to clear reg a
do visual selection
press :, vim will auto add '<,'>, then g/pattern/y A<Enter>
all your needed lines are in reg a, you can "ap to paste. for the reversing order requirement, I don't understand. What output do you expect. A concrete before/after example may help.
For adding boilerplate code, the usual solution is via a snippets plugin, which solves this (at least partially) in a generic way, instead of building a (possibly brittle) special solution with Vim built-ins.
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.

Vim smart tabs inside an if statement

I'm using Vim's SmartTabs plugin to alingn C code with tabs up to the indentation level, then spaces for alignment after that. It works great for things like
void fn(int a,
________int b) {
--->...
Tabs are --->, spaces are _. But it doesn't seem to work so well for cases like
--->if(some_variable >
--->--->some_other_variable) {
--->...
In the case above, Vim inserts tabs on the second line inside the parentheses. Is there a way I can modify what Vim sees as a continuation line to include cases like this, so I get:
--->if(some_variable >
--->___some_other_variable) {
--->...
If there's an indentation style that would both allow flexible indentation width according to one's preferences, and consistent alignment, your suggested scheme would be it. Unfortunately, this style requires some basic understanding of the underlying syntax (e.g. whether some_other_variable is part of the line-broken conditional (→ Spaces) or a function call within the conditional (→ Tab)), and this makes implementing it difficult.
I'm not aware of any existing Vim plugin. The 'copyindent' and 'preserveindent' options help a bit, but essentially you have to explicitly insert the non-indent with Space yourself (and probably :set list to verify).
I don't know about that other Editor, but the situation is similar for most other inferior code editors. Without good automatic support, this otherwise elegant style will have a hard time gaining acceptance. I would love to see such a plugin for Vim.

Which editors out of Emacs, Vim and JEdit support multiple simultaneous text insertion points?

Background: JEdit (and some other text editors as well) support a feature called Multiple simultaneous text insertion points. (at least that's what I'm calling it here).
To understand what this means, take a look at the link.
Out of all the features in use in modern text editors, initial research seems to indicate that this is one feature that both Emacs and Vim do not actually support. If correct, this would be pretty exceptional since it's quite difficult to find a text editor feature that has not made its way into at least one of these two old-school editors.
Question: Has anyone ever seen or implemented this feature in either Emacs, Vim, or both? If so, please point me to a link, script, reference or summary that explains the details.
If you know an alternate way to do the same (or similar) thing, please let me know.
The vim way to do this is the . command which repeats the last change. So, for instance, if I change a pointer to a reference and I have a bunch of
obj->func
that I want to change to
obj.func
then I search for obj->, do 2cw to change the obj-> to obj., then do n.n.n. until all the instances are changed.
Perhaps not a flexible as what you're talking about, but it works frequently and is very intuitive and fast when it does.
moccur-edit.el almost does what you want. All the locations matching the regexp are displayed, and the editing the matches makes changes in the corresponding source. However, the editing is done on a single instance of the occurrence.
I imagine it'd be straight forward to extend it to allow you to edit them all simultaneously (at least in the simple case).
There is a demo of it found here.
Turns out, the newest versions of moccur-edit don't apply changes in real-time - you must apply the changes. The changes are also now undoable (nice win).
In EMACS, you could/would do it with M-x find-grep and a macro. If you really insist that it be fully automatic, then you'd include the find-next in the macro.
But honestly, this strikes me as a sort of Microsoft-feature: yes, it adds to the feature list, but why bother? And would you remember it existed in six months, when you want to use it again?
For emacs, multiple-cursors does exactly that.
Have a look at emacsrocks episode 13, by the author of the module.
I don't think this feature has a direct analogue in either Emacs or Vim, which is not to say that everything achievable with this feature is not possible in some fashion with the two 'old-school' editors. And like most things Emacs and Vim, power-users would probably be able to achieve such a task exceedingly quickly, even if mere mortals like myself could spend five minutes figuring out the correct grep search and replace with appropriate back-references, for example.
YASnippet package for Emacs uses it. See 2:13 and 2:44 in the screencast.
Another slight similarity: In Emacs, the rectangle editing features provided by cua-selection-mode (or cua-mode) automatically gives you multiple insertion points down the left or right edge of the marked rectangle, so that you can type a common prefix or suffix to all of those lines.
e.g.:
M-x cua-selection-mode RET (enable the global minor mode, if you don't already use this or cua-mode)
C-RET down down down (marks a 1x3 character rectangle)
type prefix here
C-RET (unmark the rectangle to return to normal editing)
It should be something like this in vim:
%s/paint.\((.*),/\1.paint(/
Or something like that, I am really bad at "mock" regular expressions.
The idea is substitute the pattern:
/paint(object,/
with
/object.paint(/
So, yes, it is "supported"
It seemed simple to do a basic version of this in Emacs lisp. This is for when you just want two places to insert text in parallel:
(defun cjw-multi-insert (text)
"insert text at both point and mark"
(interactive "sText:")
(insert-before-markers text)
(save-excursion
(exchange-point-and-mark)
(insert-before-markers text)))
When you run it, it prompts for text and inserts it at both point (current position) and mark. You can set the mark with C-SPC. This could be easily extended for N different positions. A function like set-insert-point would record current position (stored as an Emacs marker) into a list and then when you run the multi-insert command, it just iterates through the list adding text at each.
I'm not sure about what would a simple way to handle a more general "multi-editing" feature.
Nope. This would be quite difficult to do with a primarily console-based UI.
That said, there is similar features in vim (and emacs, although I've not used it nearly as much) - search and replace, as people have said, and more similarly, column insert mode: http://pivotallabs.com/users/brian/blog/articles/350-column-edit-mode-in-vi

Resources