A better way to write int main(){} - vim

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.

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}

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

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.

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.

Code navigation in vim and emacs

The IDE feature that I miss the most in emacs and vim are code navigation and find usages. Both of these editor have the following similar features for them:
Tags - identifiers from specified files are indexed and when you press shortcut on a word which is an identifier, you will be navigated there
CScope - it allows you to navigate to "usages" of an identifier
As far as I understand, both of these systems are very imprecise. If we have similar identifiers with the same name both tags and scope might mix them up. Are there any better alternatives and how precise they really are?
I use cscope and semantic in Emacs. It is just enough for me.
In cscope the two function I heavily used are cscope-find-global-definition and cscope-find-this-symbol. The previous function is quite precise.
C-c s s Find symbol.
C-c s d Find global definition.
As for semantic(dynamic index, do not need to generate TAGS).
(global-set-key [f8] 'semantic-ia-fast-jump) ;; jump to definition.
(global-set-key [S-f8] ;; jump back
(lambda ()
(interactive)
(if (ring-empty-p (oref semantic-mru-bookmark-ring ring))
(error "Semantic Bookmark ring is currently empty"))
(let* ((ring (oref semantic-mru-bookmark-ring ring))
(alist (semantic-mrub-ring-to-assoc-list ring))
(first (cdr (car alist))))
(if (semantic-equivalent-tag-p (oref first tag)
(semantic-current-tag))
(setq first (cdr (car (cdr alist)))))
(semantic-mrub-switch-tags first))))
GNU Global, for example, allows duplicate identifiers, and you'll be able to select needed.
There are many programs that output ctags-compatible tags files. They are often language-specific because of some low level limitations in ctags but neither they nor ctags help you when you have multiple methods with the same name because these tools only do the indexing part of the job. Searching through the index is actually Vim's job and, because it is a freaking text editor and not an IDE it has zero mean to decide which method declaration is the right one.
Fortunately, Vim shows an actionable list when there are multiple hits. But that's how far you can go.
Cscope is a little smarter than ctags and, when used from Vim, does the searching as well as the indexing. But, like ctags, cscope is still a code indexer.
It's actually possible to use both at the same time with set cscopetags but it won't help with your naming issue.
You could try GNU Global. But it doesn't support JavaScript so I've never really used it long enough to make an opinion.
IDEs usually do their magic through language-specific parsers/static analysis tools that run in the background against your code. Vim has at least one limitation and one feature that make it hard to even imagine it ever reaching the level of code awareness that you seem to be looking for:
Vim is not multithreaded. So it can't run a static analysis tool in the background.
Vim supports hundreds of languages. Providing that kind of feature for that many languages would be impossible for any organization of any size.
But none of this is a problem for me, because Vim is not an IDE.
And because I don't have multiple methods with the same name in my projects.
<C-]>, <C-w>}, :tag /foo<Tab> and :cs f c bar are enough for my humble needs.
See eclim which has a very usable emacs interface which supports the same level of code navigation for java as Eclipse.
Eclim also supoprts C/C++ among others, though support for this is not yet implemented in emacs-eclim, but if you know Elisp then it is pretty trivial to implement, because for java all the necessary infrastructure is already there, so you only need to add the implementation for the c++ calls.

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