Code navigation in vim and emacs - vim

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.

Related

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.

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.

Search tags only in current file

I am using ":ta " to jump to a method.
For example i got two classes named A.java and B.java. They both have a foo() method and B.java have another method called fooBar(). Then i open A.java and input :ta foo then press TAB then i will got two completion : foo and fooBar. But what i want to jump now is just tag in current file, i don't like tag in other file to display.
And i found tagslist does very good in this job. So if i can use the tag generated by taglist to search from, it will be very nice.
Depending on how many times you call your methods a couple of * may be enough.
Without using tags, gd can be used to go to the local declaration of the method under your cursor. I tend to choose the most low-tech solution usually, so I would go with this one.
But ctags is also able to generate tags for a single file only or for an arbitrary selection of files. It can be done in a few steps but it's definetely not as straightforward as what you are accustomed to do…
Create a file with the name(s) of the file(s) you want to scan. Let's say it's called files.txt and it's located at the root of your working directory.
Generate your tags file using the -L <file> argument: ctags -L files.txt.
At this point you should have a tags file containing only the tags present in the file(s) specified at step 1.
Generating different tags files for the whole project and for single files may be useful, here. A short script generating a tags file named after the current file and making it the sole tags source may make the whole thing easier.
EDIT
Actually, TagList and TagBar don't generate tags files. The output of the ctags <options> command they run is used internally and parsed with all kinds of regexp to filter by scope or filename or whatever.
Unfortunately this cannot be done using ctags. Ctags does not respect context, it is a pure list of all possible "functions". Try to open a tag file with an editor (e.g. vim) and you will see it is just a list of "functions" (in case of Java they are "methods"). Example:
getDesc src/com/redhat/rhn/internal/doclet/Handler.java /^ public String getDesc() {$/;" m class:Handler
getDoc src/com/redhat/rhn/internal/doclet/ApiCall.java /^ public String getDoc() {$/;" m class:ApiCall
Vim just search the file "as is" without giving it any context - it just search for a "function". It is able to search for files, classes, methods, enums etc. Tags format is described in more detail here: http://ctags.sourceforge.net/FORMAT
In Vim you have few possibilities. There are several plugins that gives Vim some context sensitivity, but you cannot use tags for that. Vim itself has a feature called OmniComplete and there are few plugins dedicated for Java. Then you can use Ctrl-X Ctrl-O to start a completition. I recommend you to map this to a different key (maybe Ctrl-Space if you like). More info about Java OmniComplete plugins here:
Vim omnicompletion for Java
Eclim (http://eclim.org/) is very comperhensive, but difficult to setup (you need to run Eclipse in the background). JDE script is easier and also robust (http://www.vim.org/scripts/script.php?script_id=1213). And please note IntelliJ IDEA Community Edition (free) also has a very nice Vim plugin that is free to use. But I understand you - Vim is Vim.
Good luck!
Not exactly an answer to your question, but it seems like there's no way to do exactly what you need, so, i would recommend you the following: for your Java development in Vim, try eclim.
This tool helps you to use your favorite text editor Vim with power of an Eclipse (IDE).
I can't find analogue for tab-completion of :ta, but i know a smart analogue for g] : this is a command :JavaSearchContext. You can map it to something.
For example, if you have two classes A and B, and you have method foo() in each class, then g] will ask you every time you want to jump to foo(), but :JavaSearchContext will always jump to the proper declaration of foo().
Of course, there are many other features.

Haskell autocompletion in Emacs using haskell-mode

I installed haskel-mode in emacs. Then I write in my .emacs:
(load "~/.emacs.d/haskell-mode/haskell-site-file")
(add-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode)
(add-hook 'haskell-mode-hook 'turn-on-haskell-indentation)
(add-hook 'haskell-mode-hook 'haskell-font-lock-symbols t)
(put 'downcase-region 'disabled nil)
What must I add in my conf file that emacs could autocomplete for Haskell? Or Haskell mode there is no such possibility?
When there is no language-specific support, you can use tags. This is a generic completion mechanism.
Generate a TAGS file, which contains a list of identifiers and where they are defined. Emacs comes with the etags program to do this in many languages, but not Haskell; ghc comes with hasktags.
Load the TAGS file with M-x visit-tags-table.
Tags are not context-dependent, so they'll indiscriminately suggest types, values, constructors, etc everywhere. They also won't provide advanced features such as easily showing the type of a value. The most important tags commands are:
M-TAB (complete-symbol) completes an identifier according to the loaded list of tags.
M-. (find-tag) goes to the place where the identifier at point is defined, opening the containing file if necessary.
M-* (pop-tag-mark) goes back where you were before M-..
M-x tags-apropos shows a list of identifiers matching a regexp.
For more information, look under "Tags" in the Emacs manual.
For an even cruder, but fully automatic mechanism, there is the dynamic abbrev feature. C-M-/ (dabbrev-completion) looks in most open buffers for a completion; this is completely language-independent, so it'll even find words in strings, comments, whatever. M-/ (dabbrev-expand) is similar, but directly completes to the nearest match before point.
ghc-mod provides some completion for Haskell within Emacs, as well as checking with hlint and ghc. In combination with M-/, it's good enough for me.
haskell-mode currently provides no such possibility. There is some work on implementation of haskell parser for CEDET - in this case, users will get autocompletion features automatically. But this work had started not so much time ago...
My setup is a little more complicated. It uses the auto-complete infrastructure which
shows a dropdown list of candidates automatically similar to traditional IDEs. I downloaded this script that hardcodes all the keywords. In addition to that, I use ghc-mod to generate module names.
As a "cheap and cheerful" autocompletion mechanism, don't overlook M-/. It's completely heuristic and language-independent, but surprisingly effective.
Besides autocompletion for your own code, you can also get autocompletion (with apidocs even) for the standard library, import names, and pragma names using company-ghc. I found this guide to be very helpful. Note, I didn't get it to work fully for myself yet, but I can feel I'm close :-)

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