Showing posts with label Vim. Show all posts
Showing posts with label Vim. Show all posts
Sunday, February 10, 2013

Getting YouCompleteMe to work in RHEL 6 (or Fedora)

No matter what IDE I use, so far I still give up and go back to vim. However, Eclipse is quite missed for it’s autocomplete facility. The recent announcement on Hacker News gave me a glimpse of hope with YouCompleteMe, as with clang complete a while ago, but even sleeker.

But YouCompleteMe uses a number of really new dependencies, which RHEL6, being an old snapshot of Linux, is a bad target candidate since these dependencies are not easily satisfied. Perhaps stopping short of paid support, it’s unlikely that these packages will be made up-to-date. Not being a cheap-ass here, but since I really don’t like waiting, I’ll just have to roll-my-own :-)

Amazingly these dependencies are so new that even vim needs to be rebuilt due to the recently introduced python extensions, so there’s no avoiding some serious source compiling here!

Before we start, let me impart some words of advice. Firstly, even if you are gutsy enough to build your own binaries, never try to reinvent the wheel and build from pristine sources!

Secondly, installing software through package managers (eg. RPMs, .debs) are always superior to “sudo make install”. It ensures you’ll never have lingering dependencies, or wrong versions of libraries that got wrongly linked because the installed script overwrote the default.

For Redhat based OSes, since the guys at Fedora has already done the hard work of building up-to-date packages, applying patches and cleanups for you, it’ll be the best bet to avoid pain from compilation errors, or hours spent in debugging other people’s code.

Pull a copy of the vim.spec file from Fedora Rawhide and re-adapt it to your liking before building an RPM. Obviously, F19 (as this time of writing) has diverged since RHEL6 got snapshotted, so a little patch and backporting is unavoidable.

Then, there’s the issue of Clang, which is recommended to be version 3.2. Even Fedora Rawhide at the moment only supports 3.1, so I was rather surprised about such a new dependency that YouCompleteMe requires. Still it’s not a problem, just a little more hacking on llvm.spec.

Note: my Clang 3.2 build fails a single regression test during building, so I’ve disabled regression testing to allow the RPM to be built. While it may be ok for some other software, but regression test failures on your compiler is a BAD thing, especially if you’re going to build the entire OS from scratch. But since we’re only using it as an annotation tool, I’m going to let it slide.

If building those 2 things hasn’t deterred you yet, you’ll still need to deal with the last headache of building a newer version of CMake, as a dependency that YouCompleteMe require in order to compile the final ycm_core.so library. [ But why? :-( ]

Anyway, for people who want to skip the pain of building it yourself, you can get my pre-built ycm_core.so and all my vim/llvm RPM dependencies from my RPM repo (if you trust my work ;-) and save yourself some compiling hassles. They probably will work on Fedora as well, since dependencies are usually forward-compatible, but YMMV. Have fun!
Friday, September 07, 2012

Vim: When Copy and Paste doesn't work ...

I used to remember that copying and pasting to the clipboard used to work a long while ago, but I just couldn't remember what exactly did I do in order to get it to work. That were the days where I was still bothered enough to tweak things to get it running - these days I just want to get things to work, which many will arguably retort that what I'm asking for is impossible.

While Linux may be perceived as still a much less-accessible OS compared to the ones that you have to pay for, it actually works pretty well once you've gone past the learning curve. But from time-to-time, you can still be surprised with what you don't know. It can feel like a hassle sometimes, but on the flip-side, learning new things is what makes using it fun. (Sure many may disagree on that too - and if you are one of them, I'll save you the torture; shut your brain down and go back to surf your Facepage instead ;p)

I remembered about having to recompile vim from dog years ago, and started to look at what's missing in the standard vim-enhanced package; lo-and-behold, the version flag shows the following:


$ /usr/bin/vim --version
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Nov 16 2010 17:05:25)
Included patches: 1-56
Modified by 
Compiled by 
Huge version without GUI.  Features included (+) or not (-):
+arabic +autocmd -balloon_eval -browse ++builtin_terms +byte_offset +cindent 
-clientserver -clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments 
+conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con +diff +digraphs 
-dnd -ebcdic +emacs_tags +eval +ex_extra +extra_search +farsi +file_in_path 
+find_in_path +float +folding -footer +fork() +gettext -hangul_input +iconv 
+insert_expand +jumplist +keymap +langmap +libcall +linebreak +lispindent 
+listcmds +localmap -lua +menu +mksession +modify_fname +mouse -mouseshape 
+mouse_dec +mouse_gpm -mouse_jsbterm +mouse_netterm -mouse_sysmouse 
+mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg -osfiletype 
+path_extra +perl +persistent_undo +postscript +printer +profile +python 
-python3 +quickfix +reltime +rightleft +ruby +scrollbind +signs +smartindent 
-sniff +startuptime +statusline -sun_workshop +syntax +tag_binary 
+tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title
 -toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo 
+vreplace +wildignore +wildmenu +windows +writebackup -X11 -xfontset -xim -xsmp
 -xterm_clipboard -xterm_save 
   system vimrc file: "/etc/vimrc"
     user vimrc file: "$HOME/.vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/etc"
 f-b for $VIMRUNTIME: "/usr/share/vim/vim73"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H     -O2 -g -pipe -Wall  -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64  -D_FORTIFY_SOURCE=1     
Linking: gcc   -L.  -rdynamic -Wl,-export-dynamic  -Wl,--enable-new-dtags -Wl,-rpath,/usr/lib64/perl5/CORE   -L/usr/local/lib -Wl,--as-needed -o vim       -lm -lnsl  -lselinux  -lncurses -lacl -lattr -lgpm -ldl    -Wl,--enable-new-dtags -Wl,-rpath,/usr/lib64/perl5/CORE  -fstack-protector  -L/usr/lib64/perl5/CORE -lperl -lresolv -lnsl -ldl -lm -lcrypt -lutil -lpthread -lc -L/usr/lib64/python2.7/config -lpython2.7 -lpthread -ldl -lutil -lm -Xlinker -export-dynamic   -lruby -lpthread -lrt -ldl -lcrypt -lm   


The compiler flag xterm_clipboard isn't compiled with standard text mode vim, that was the main reason that I had to recompile vim in the past!

But these days, I'm lazy. I much rather not have to recompile and maintain my own packages if I have to, and it turns out that I'm in luck - a bit of digging showed that the vim-X11 package contains vimx, a version of vim that has the xterm_clipboard flag enabled. Happy days!

So just do:


$ sudo yum install vim-X11
$ alias vim=$(which vimx)


The alias command just makes it easier given I'm so used to typing vim than vimx, so that I don't have to undo my habit :)

So how do you make use of the clipboard? Let say you have mouse mode on (set mouse=a), and selected some text using your mouse; in order to send it to the clipboard, do


"+y


Note that the quote isn't a typo. To paste from the clipboard into vim, do:


"+p


Bonus trick. You can make your selection in normal mode automatically be sent to the x11 clipboard by making this configuration:


set go+=a


Have fun! :D
Saturday, May 31, 2008

Vim: Editing Command History

One of the few oft-forgotten commands that are rather handy:


q:


Opens the command line buffer for editing


q/


Open the previous regular expression search buffer for editing.
Friday, February 15, 2008

Visualizing Differences Between Source Modifications in Vim

There's always something new to learn from #vim, and here's another gem that allows you to use vim's built-in diff capability to visually inspect the code changes on your source inline. Add the following into your .vimrc:


function() DiffPreview()
diffthis | vsplit | enew | set buftype=nofile | read # | 1delete | diffthis
endfunction
map <F9> :call DiffPreview()<CR>


In this case, I've mapped it to the <F9> function key. How to use this: once you made all the changes you wanted, DON'T save the current buffer yet, and invoke the DiffPreview() function. It'll provide you with a highlighted 'diff' of all the changes you've made. Have fun!
Thursday, February 14, 2008

Non-Greedy Regular Expression Matching

This applies to Ruby, and many other languages too (eg. Perl), just that I keep forgetting it. In order to have non-greedy matching enabled, append the question mark after the quantifiers, ie.


* (0 or more) greedy matching
+ (1 or more) greedy matching
*? (0 or more) non-greedy matching
+? (1 or more) non-greedy matching


For vim, the syntax is slightly more convoluted, so it's important to put a note here for my own reminder:


* (0 or more) greedy matching
\+ (1 or more) greedy matching
\{-} (0 or more) non-greedy matching
\{-n,} (at least n) non-greedy matching


There's no direct '(1 or more) non-greedy matching' in vim, but the 'at least n' operation should be the equivalent. For vim, these should normally be default and independent of whether if the 'very magic' or 'very nomagic' mode is set. See help in pattern.txt, for more pattern matching details.
Friday, January 18, 2008

Tab Completion for Vim (Updated)

As I've said before, I wasn't really satisfied with the original tab completion script, which didn't perform all the possible search completion combinations vim is capable of. After accidentally overwriting my existing .vimrc file, I just thought it was high time I remedied the incomplete implementation of tab completion for vim to work properly with Java.

As with before, the script has to utilize existing auto-completion script, and the additional changes on my script now makes tab 'intelligently' to perform completion on incomplete methods and fields, rather than having only to be able to do so only at the start of the dot ('.'). Also, if tab occurs at locations where it doesn't fit the profile of a method or field (i.e, it's not in the pattern of 'package.class.methodname_or_fieldname', where package is optional), it will try to use vim's built-in keyword completion (<C-X><C-P>) instead.

Here's the script that you'll need to copy and paste into your .vimrc:


" Modified tab completion. It works fine now.
function! My_TabComplete()
let line = getline('.') " curline
let substr = strpart(line, -1, col('.')+1) " from start to cursor
let substr = matchstr(substr, "[^ \t]*$") " word till cursor
if (strlen(substr)==0) " nothing to match on empty string
return "\<tab>"
endif
let bool = match(substr, '\.') " position of period, if any
if (bool==-1)
return "\<C-X>\<C-P>" " existing text matching
else
return "\<C-X>\<C-U>" " plugin matching
endif
endfunction
autocmd BufNew,BufRead *.java inoremap <tab> <C-R>=My_TabComplete()<CR>


If you like reading this, you may also enjoy:
Tuesday, December 18, 2007

Regular Expression matching more than a single line in Vim

As grep doesn't allow for regular matching of multiple lines, I've found that vim is a handy substitute if I didn't have use it as a pipe to another program's input.

The trick that allows vim to do so, is to enable multiple line matching by using the special regular expression escape '\_.' combined with a greedy qualifier.

The help line in the vim documentation offers how this trick is accomplished:


\_. Matches any single character or end-of-line.
Careful: "\_.*" matches all text to the end of the buffer!


It's precisely the warning highlighted in red that we are going to 'exploit' in order to allow multi-line matching to occur.

An example where this sort of matching usually applies are usually found in data formats like HTML/XML, where data sets can span multiple lines, separated by markups rather than newline characters.

As an example, say, if you wanted to match data that's bounded by <div> markup pairs, you'll have the following regular expression:


<div>\_.\{-}</div>


I often use this technique as a 'quick and dirty' way of breaking up markups into separate data easily, especially if it's only for a one-off use that doesn't merit writing a Perl or Awk scripts.

If you like reading this, you may also enjoy:
Sunday, December 09, 2007

Adding text before and after a regular expression match in Vim

Let say that you have a series of lines of text that you want to convert into 'System.out.println' or 'printf' statements, for example:


1 myapplication - an application that does something
2 usage: myapplication [-abch] param1 param2
3 -a: does a particular feature
4 -b: does another feature
5 -c: does yet another feature
6 -h: shows this help message


It's is laborious to append all those print statements manually, so the generally you'll want to use regular expressions to replace it for you. One way of doing this with POSIX compliant regular expression with grouping:


:'<,'>s/\(.*\)/printf("\1");/


(Note that this assumes that you have selected the given block with the 'v' keystroke or from the mouse already. Subsequent examples will also assume the same.)

Vim requires escapes for the parenthesises, by which one of the ways of shortening it may be by using the '\v' (very magic) operator:


:'<,'>s/\v(.*)/printf("\1");/


But the shortest way so far that I've found in vim is to use the '\&' matching operator, which works even when grouping is not explicitly used:


:'<,'>s/.*/printf("\&");/


The resultant output should for the quoted example is shown below, if you are too lazy to try it and see for yourself:


1 printf("myapplication - an application that does something");
2 printf("usage: myapplication [-abch] param1 param2");
3 printf(" -a: does a particular feature");
4 printf(" -b: does another feature");
5 printf(" -c: does yet another feature");
6 printf(" -h: shows this help message");


It's certainly much more powerful to be able to perform replacements like that with pinpoint accuracy at a single go, something that 'search and replace' text editors that do not have regular expressions capabilities are able to do.

If you like reading this, you may also enjoy:
Tuesday, October 30, 2007

Tricks on handling multiple line inputs and outputs

There are some of the trivial bag of tricks that I don't normally take notice, which does often comes back to bother me. I just have to trip on Finagle's Law whenever I forget these tricks after long disuse. Things like handling multi-line inputs and outputs seems to fit into that category, so here's all I can recall form my own reference:

Printing multiple line outputs with a single echo command

The special escape for newline in bash is $'\n'. Here's an example how it's being used:


% echo "Hello$'\n'World"
Hello
World


Other non-printable characters can be similarly escaped this way (e.g. The NUL terminator represented by $'\0').

Reading multi-line inputs from stdin

This is achieved by using the << operator:


% cat <<TEST
> This is a test
> Hello World
> TEST
This is a test
Hello World


Reading multi-lines of a file into a single variable

Because spaces are treated as field separators in bash, and it won't try to read past the first separator, you need to force the shell to treat nothing as a separator, by modifying the IFS (Input Field Separator):


OLDIFS=$IFS IFS= var=($(< filename.txt)) IFS=$OLDIFS


This above example assumes that you have a file called filename.txt, and at the end of the operation, the entire contents of the file is stored in the var variable.

Matching multiple lines using grep

When searching for two or more consecutive words within a sentence on a text file (or HTML), sometimes it is possible that the words are span across multiple lines, hence making typical word search, barring from using a script, difficult. One of the neat tricks to accomplish this without using any script, is through GNU grep's -P flag.

Assuming that you have a file called test.txt that spans two or more lines:


I like to say a nice warm "Hello
World" to all of you out there!


To search for the consecutive words "Hello World":


grep -P "Hello\WWorld" test.txt


Curiously, it does not seem to work on Gentoo/Ubuntu linux's version of grep but works only on my old RedHat distro only. Maybe it's something that has been phased out.

Splitting inputs into multiple lines

The easiest way to split things on the command line is to use the sed
command:


% echo "Hello World" | sed -e 's/ /\n/'
Hello
World


If you want to do this within vim, it is a little bit less straightforward but still doable:


:s/ /<CTRL-V><ENTER>/


Replace the items in the angled-braces with the actual keystroke itself. The screen the output actually looks like:


:s/ /^M/


So don't be concerned by the visual difference.
Saturday, September 15, 2007

Cscope with Vim for finding Java symbols

Cscope, like ctags, allow you to find symbols in your source from multiple files in your project easily. While it was originally developed for C (easily inferred by the name), the project has extended to cover a number of other languages as well, Java included.

Before you mistake cscope as a rehash of my tip on using exuberant-ctags, let me explain why scope is different. Cscope has semantic knowledge of the Java as a language, and understands when you are looking for a symbol (a variable or method definition), and other useful search functions, like finding out other methods that invoke method you want, or listing all the methods definition uses.

(Image of Cscope in Action)

The advantage of semantic knowledge is that when you are looking for a variable or method, you won't be sent to some uncharted parts of your code, such as within your comments, just because there is a piece of text that matches the name.

To use it with vim as the default editor, you'll have to set that in the environment in your shell (where the following is for bash) if it isn't set already:


export EDITOR=/usr/bin/vim


You'll need to generate a list of files for cscope to be able to generate cross references to. This is easily done by using the find command in the root directory where your java files are found:


find ./ -name *.java > cscope.files


cscope.files is the filename that cscope will read each time it starts up, so make sure you adhere to that.

There are ways to allow cscope to run within vim instead of the other way round, but while I managed to do it after a bit of experimentation, I did find that I've used it with cscope invoking vim more commonly, whenever I need to fire it up and look for the methods or variables that I want from time to time. Happy cscoping!

If you like reading this, you may also enjoy:
Monday, September 03, 2007

Vim Remade: Working on Java with all of Netbeans' features

The title sounds like a bold claim, given that the comparison sounds like one between apples and oranges. While vim will probably never incorporate some features that Netbeans as an IDE has, fundementally, both are text editors, and do share some commonalities that we can contrast and compare with.

I started using Netbeans because I needed a good RAD tool for building Swing GUIs. Matisse, the graphical GUI builder built-in with Netbeans, came to me as an impressive tool that allows for an easy and intuitive way of building graphical frontends.

It wasn't just Matisse that impressed me. Netbeans had bucketloads of other editing features that weren't available with vim, which left me feeling less satisfied than I originally was. But even as I toyed with the idea of dumping vim for Netbeans, trying to unlearn my keystrokes, getting used to context switches from fidgeting with menus and alternating between the mouse and keyboard again just wasn't worth the trouble.

That had been my primary reason for writing the various Java Tips for Vim, which I hope becomes useful to other Java developers who code primarily in vim. To do a rehash on my current list of tips:

Intellisense (or Syntax Completion)

The first and foremost feature that I'd really liked in Netbeans is 'intellisense', or the auto-completion of syntax. It makes coding much a less tedious effort, saving up time and the trouble of having to constantly look up API calls via Javadoc.

Tabbing for Syntax Completion
As nice as it is, Netbeans' auto completion sometimes does not work as intended, either suggesting wrong stuff, or nothing at all. But what irks me most is that auto-suggestion can be intrusive and uncalled for at times.

However the existing keystroke sequences <C-X><C-U> for syntax completion in vim can be a bother sometimes, and easier way is to map the <tab> key to contextually determine whether you want syntax suggestion, or a tab itself.

Auto-bracketing

Related to automatic syntax completion, is the ability to complete brackets, braces and curly braces, etc. While I haven't completely figured out the way to foolproof auto-bracketing quotes and other quirks with my solution, this solution will probably be one of those 'keep in view' hacks that I'll try to improve in the future.

API Lookup using ctags
Netbeans has a preview window that pops up relevant API information for Java, something that is lacking in vim. The closest alternative I know, is achieved by using ctags to look up API calls, saving a bit of a hassle by directing you to the right source file automatically.

Automatic compilation via Ant
Allows you to do a compilation with just the :make command. Of course you can bind it to the <F5> key and that would make it feel just as the same as an IDE.

Code Folding
Reduces visual clutter from your code, by folding them up according to methods, or other large blocks of code that makes semantic sense to you.

After these adjustments I've made, it is really starting to feel that vim is now customized sufficiently to have roughly the same amount of usability as Netbeans for Java specific development, so it will probably be while later before I revisit these issues again. Hopefully the tips will be as useful for you as I've found it!
Wednesday, August 22, 2007

Vim Tips for Java #6: Auto-Bracketing Within Vim

One of the things that I've learnt that Netbeans is able to do, was the ability to perform auto-bracket completion. For a while, I was missing that nifty little feature when I reverted back to using vim, and I tried tweaking around with vim to provide the same feature, only with limited success. Only after writing my tip on tab-completion had I realised that I have already a complete solution in providing for auto-brackets.

The following script I have will allow me to detect whether if I really wanted a closing bracket/brace or whether if has already been inserted previously by the auto-bracketing script, and hence I should skip it, by checking what the current character on the cursor right is. So here's what's needed to be added to your .vimrc in order for it to work:


autocmd Filetype java imap ( ()<left>
function! My_BracketComplete()
let char = strpart(getline('.'), col('.')-1, 1)
if (char == ")")
return "\<Right>"
else
return ")"
endif
endfunction
autocmd FileType java inoremap ) <C-R>=My_BracketComplete()<CR>

autocmd Filetype java imap { {}<left><cr><cr><up><tab>
function! My_BraceComplete()
let char = strpart(getline('.'), col('.')-1, 1)
if (char == ")")
return "\<Right>"
else
return "}"
endif
endfunction
autocmd FileType java inoremap } <C-R>=My_BraceComplete()<CR>


While it is neither the cleanest nor the most elegant way, but it replicates faithfully with what Netbeans does. Unfortunately, this solution will still not work for quotes and double-quotes because of the nature of the 'imap' command, which will make vim go into a non-terminating loop. So if some of you have thought of a better way to do this, do share it with me by posting your solution on my blog.

If you like reading this, you may also enjoy:
Friday, August 17, 2007

Vim Tips for Java #5: Folding Code Blocks to prevent Visual Blindness

When dealing with large source files, there is a tendency for visual blindness to kick in, where there is just too much code everywhere for you to find things like the start of a method or a particular important segment of code, in a sea of random visual clutter.

With Vim (6.0 onwards I think), there is support for concept of folding, which helps to segregate your code into meaningful chunks visually, expanding and collapsing the folds as you work. There are a number of keystrokes to learn, so if you are new to folding you might want to read a tutorial like
this one (link to linux.com).


Initially I wanted a way to automatically generate folds for me based on the type of source code I'm working on, and a nice answer I have found is the SimpleFold plugin from Eigenclass, which helps in creating folds automatically for you by matching the source file with certain patterns.

I believe that it does automatic folding for Ruby quite well, but because of the syntax structure of Java, folding using plain regex probably doesn't fully match my requirements (it doesn't handle the treatment of inner classes and methods that well, and mistakes certain variable declarations as methods) so I tend to use manual folding instead, which is done by using the command:


:set foldmethod=manual


While folding by default on vim looks alright, but I find SimpleFold's display with brackets and indentation much better for differentiation between class definitions and methods, so I decided to shamelessly copy the formatting part of SimpleFold's code for my own nefarious use instead (Copy to .vimrc):


function! Num2S(num, len)
let filler = " "
let text = '' . a:num
return strpart(filler, 1, a:len - strlen(text)) . text
endfunction

function! FoldText()
let sub = substitute(getline(v:foldstart), '/\*\|\*/\|{{{\d\=', '', 'g')
let diff = v:foldend - v:foldstart + 1
return '+' . v:folddashes . '[' . Num2S(diff,3) . ']' . sub
endfunction

set foldtext=FoldText()



With the change, you'll see a difference between the indentation of the methods within the folds, and the number of lines within square brackets. And now, it looks much better!





If you like reading this, you may also enjoy:
Tuesday, August 14, 2007

Vim Tips for Java #4: Use 'Tab' for Syntax Completion


Note: This tip has been updated, please see Tab Completion for Vim (Updated) instead.


If you have used my previous tip for automatic syntax completion, you might find that using the <CTRL-X><CTRL-U> keystrokes to perform omni-completion can sometimes get quite frustrating after a while. To help address this annoyance, I wrote a little vim function to use the <tab> button to perform syntax completion instead.

The nice thing about that, is the function does contextual scanning to see if you actually want a <tab> or omni-completion to be performed by scanning the token at immediately before the cursor when the <tab> button is pressed.

Put these lines into your .vimrc:


function! My_TabComplete()
let substr = strpart(getline('.'), col('.'))
let result = match(substr, '\w\+\(\.\w*\)$')
if (result!=-1)
return "\<C-X>\<C-U>"
else
return "\<tab>"
endfunction
autocmd FileType java inoremap <tab> <C-R>=My_TabComplete()<CR>


The specific pattern I'm looking for in this case is 'objectOrClass.' or 'objectOrClass.incompleteMethodName', but do feel free to change to fit your own needs. Also, if you are using the keyword replacement keystroke <CTRL-P> rather than vjde, you should modify the script to return '\<C-P>' instead.

If you like reading this, you may also enjoy:
Saturday, August 11, 2007

Vim Tips for Java #3: Use Omni-Completion (or Intellisense) for syntax completion

As much as I like vim, Netbeans trumps it when we talk about automatic syntax completion. Because of the vast amount of API that is present for the Java platform, the ability of having auto-suggestion for syntax is a godsend.

While things like looking up an API call while you are in the thick of coding are irritating, the effects of such distractions are often much more profound. A recent article by the New York Times suggests that such interruptions do not just result in the reduction of your efficiency, but increase the chances of making mistakes as well.

In vim 7.0, there is a facility that allows you to have auto-suggestion capabilities, which comes bundled for a number of languages like Ruby, Python, etc, but however not for Java. If you have followed my tip in using exhuberant-ctags for Java, the modification will allow vim to have primitive syntax completion capabilities, by using <CTRL-P>. In this case, it tries to match a word you've typed with all the keywords found in ctag's tag file.

The problem with this approach, is that it performs 'dumb' keyword completion of previous matching patterns, rather than the 'intelligent' contextual syntax completion. This can lead to mistakes in suggestions, which can be rather frustrating.

For true contextual syntax completion, there are a few plugins out there works for Java. By and large, they aren't as polished as Netbeans, but still, they are quite functional and and usable. I've used a number of them in the past before, and the one that I reccomend for you to install is vjde.

(An Image of Onmi-Completion for Java in Action)

While the plugin is quite usable, the documentation can use some working on. The default instructions requires you to install it in the /etc/vim global directory, something I'm not willing to do in fear of of messing up my default installation's configurations. Fortunately instructions for local installation is pretty straightforward:

1) Download the latest copy of vjde;
2) Uncompress the downloaded .tar archive;
3) Copy the autoload/, compiler/, doc/, plugin/, syntax/ directories to your $HOME/.vim/ directory;

In order to use the completion, use the <CTRL-X><CTRL-U> keystroke, which will provide you with an Intellisense-like syntax completion capability. Have fun with your new syntax-completion capability, and keep on vimming!


If you like reading this, you may also enjoy:
Wednesday, August 08, 2007

Vim Tips for Java #2: Using exuberant-ctags

ctags is a great tool for programmers. It creates an index to your source code to allow you to trawl through them for cross referencing. While the way it works doesn't look as snazzy as nicely formatted javadoc output like Netbeans, it does its job well enough for you to read up a field or method definition whenever you need it. You'll need to install exuberant-ctags separately, which you can find on its website.

A requirement of using ctags, is that you'll need to have the Java source code available for ctags to parse them into a searchable index file for vim. It's usually located in your Java distribution at $JAVA_HOME/src.zip. Unzip the file, and in my case I extract it into the $JAVA_HOME/share directory I've created. Then run exuberant-ctags:


exuberant-ctags -R --language-force=java -f.tags /opt/sun-jdk-1.5.0.08/share/


This command generates a '.tags' index file in my home directory. The next thing to do is to allow vim to be able to locate and use the index file. Add the following line into your .vimrc:


autocommand FileType java set tags=~/.tags


This should now allow you to jump to any definition in the Java API, whenever you need to look it up from your code. To test this, create a Java file and put some code in it:


public class TestClass {
String s = new String();
}


Move your cursor under to the word 'String' and press ctrl-]. Voila, you should now be reading into the source of.. not just yet, it is not java.lang.String! Most probably it is showing you some other classes that has a String object in its field, which is probably not what you are looking for. To cycle through the remaining matches, use the command mode instruction ':ts' to go through the list of matching tags and select the right item you want.

You might also want to be familiarized with the navigation keystrokes, by doing a ':help' on ':ta', ':ts', 'CTRL-L', 'CTRL-]', which may be useful.

A few dissatisfactions that I still have with this method:

1) It doesn't allow me to read the embedded javadocs in code as html. It will be pretty cool if this feature can be linked to lynx and shown in a window within vim, but I'm not certain if it is possible;

2) I don't believe that searching through all the miscellaneous fields of other classes is the best way of using ctags. There may be something that I have not mastered that permits me to fully utilize the power of ctags yet.

I'll be looking further to see if I can learn more tips on using ctags, but in the meantime, if anybody have any suggestions for improvement, I'll appreciate if can leave a suggestion, thanks!

If you like reading this, you may also enjoy:
Monday, August 06, 2007

Vim Tips for Java #1: Build Java files with Ant automatically

Ant is a great tool for compiling large projects with a large number of Java files. It is the equivalent of 'make' for C, but is customised specifically for Java. While the support for make works with vim by default, certain changes have to be made for vim in order to make it work properly for Java.

Add the following lines in your .vimrc:


autocmd BufRead *.java set efm=%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%#
autocmd BufRead set makeprg=ant\ -find\ build.xml


As long the build.xml file is in the parent directory of where the Java files you are working on is located, vim will be able to locate it, compile the changed files and inform you of where the compilation errors are.

All that's remaining is just to type :make, and you now have automatic compilation from within Vim!

If you like reading this, you may also enjoy: