Showing posts with label vim. Show all posts
Showing posts with label vim. Show all posts

Tuesday, October 12, 2010

Vim: Escape

UPDATE: Scroll all the way to the bottom for the best VIM ESC mapping in the world!

Vim is a modal editor, meaning it has modes. It's modes are command mode, and edit mode (AKA normal mode and insert mode). Edit mode allows you to add and delete text and move your cursor around. Command mode allows you to execute various commands that can operate on the text.

Most editors only have edit mode. To execute commands you use shortcut keys that must depend on non-printable keys like CTRL, ALT, SHIFT. You quickly run out of simple combinations (ex: CTRL+S), so you have to introduce more complicated key combinations (ex: CTRL+K, CTRL+C). Visual Studio calls these "chords." I call it keyboard gymnastics.

Some people like the "chord" approach, and other people prefer the mode approach. I like the mode approach because if I'm going to execute non-trivial commands, I'd like to type a command.  The main downside to the mode approach is you have to get back and forth between the modes. When you launch Vim and open a file you start out in command mode. There are a bunch of useful different ways to get into edit mode, all of which are just a single keystroke: i, a, o, O, I, A.

Once in edit mode, getting back to command mode is a bit harder because now typing a key will print the character, so Vim uses ESC to leave edit mode and go back to command mode.  Sadly, on modern keyboards this goes against everything Vim stands for because the ESC key is so far away from the home row.  And if you're using Vim properly, you'll be going back and forth between these modes A LOT. So we need a better way.

Vim has an alternative built right in: CTRL+[

(You've mapped your Caps Lock key to Control, right?)

This is kind of an uncomfortable keystroke, but with practice you will get used to it.  If you'd rather not, you CAN map your own keyboard combination to Esc.  For example, you could try CTRL+space:

inoremap <C-space> <Esc>

Whatever you use, I strongly suggest you try to stop using the Escape key.

UPDATE:
A number of people in the comments suggested using various combinations of the j and k keys.  I didn't even realize you could remap printable characters, but you can!  I've been using this for quite a while now and I'm completely addicted!  I call it the "smash":

Add this mapping to your vimrc:
inoremap jk <esc>
inoremap kj <esc>

Now all you have to do is smash the j and k key.  It doesn't matter which you type first!  Just smack them both as if it was a single key!  Absolutely brilliant!

Friday, May 7, 2010

Vim Commenting

Recently there has been some renewed interest in my series of posts on using Vim for C# development, so I thought I should add a few more posts to the series to bring it up to date.

You can find the introduction to this series here.

Visual Studio has a feature which allows you to select a bunch of lines of code and have them all commented out, or uncommented.  In my setup it is bound to Ctrl+k+c to comment and Ctrl+k+u to uncomment.

I use this particular feature pretty regularly, so I definitely wanted it in Vim, and wouldn't you know it, there's a plugin for that!  NERD Commenter.

With NERD Commenter installed you can select a bunch of lines of code (I typically do something like Vjjjj) and then type either
,cc
or
,c<space>
The first is the comment command, the second is the toggle command.  If you use the comment command you'll need to use
,cu
to uncomment.  If you use the toggle command you don't need to remember two commands!

That's all there is to it!

Now, the first step is to visually select the lines you want to comment or uncomment.  You can just hit j,k a bunch of times but there are usually better ways.  For example, if you want to comment out an entire method:
public void IAmAMethod()
{
  ... lots of lines here...
}
If there are lots of lines in  the method, you don't want to be hitting j all day.  Instead, with your cursor on the method declaration line, do:
Vj%
The % is the "match" motion.  So when your cursor is on the { it will find the matching }.

Alternatively, if you just want to comment out a group of text that is arranged in a paragraph:
public void IAmAMethod()
{
  ...paragraph of code...

  // I want to comment out this block of code
  ...more code...
  ...goes here...
}
For this you can use the "paragraph" motion.  With your cursor on the first line of the block, do:
V}
That will select the whole block.

Once again, we have approximated a feature found in Visual Studio, but made it even better with the power Vim!

Wednesday, May 5, 2010

Vim File Navigation

Recently there has been some renewed interest in my series of posts on using Vim for C# development, so I thought I should add a few more posts to the series to bring it up to date.

You can find the introduction to this series here.

In a previous post I talked about how to open and edit files in Vim.  That post discusses just the basics of opening files.  Since then I've started using the wonderful NERDTree plugin.  This plugin opens a small buffer on the left of your Vim window which contains the file system tree.  You can then navigate through directories and open files.  The nifty part is the NERDTree is just a Vim buffer, so you can navigate with h,j,k,l and you can search with / etc.  To see what I'm talking about, you can watch a demo of the NERDTree in action here.

Before I go on I should mention that Vim actually has a built in file system navigation plugin called Netrw.  NERDTree adds a few features and is in someways a bit easier to use, but Netrw is capable of doing all of this stuff and it's built right into Vim.

Using NERDTree has completely changed the way I work in Vim.  When I'm ready to start working, I navigate to my .sln directory in the terminal and I type
gvim .
This opens Vim with NERDTree showing the contents of the current directory.  From here you can navigate around and find the file you want to start editing.

When you open the first file NERDTree will go away.  If you want to pull up NERDTree so it's always visible docked to the left of your Vim window you can type
:NERDTree
To toggle it open and closed you use
:NERDToggle
That's kind of a lot to type. So to shorten it up I've mapped it to F2 by adding this to my vimrc:
" toggles NERDTree on and off
map <f2> :NERDTreeToggle<cr>
imap <f2> <esc>:NERDTreeToggle<cr>i
Now hitting F2 will open and close the NERDTree. Fast and easy.

So NERDTree is great for finding and opening files (you can even open files in splits with i for horizontal and s for vertical), but NERDTree can also manipulate the file system.

For example, to add a new file, put your cursor over (or in) the directory you want to add the file to and hit the "m" key.  This will open up a menu with some options.  Type a to "add a childnode" and then just type in the name of the file. This works for creating directories too.  You can also move (and rename) files as well as delete.

Monday, April 27, 2009

Vim Update Many Files

Here's a really nice Vim trick I learned today and have already used twice.

I'll demonstrate it with an example. I wanted to go through all my .cs files and fix the formatting (they all had 4 spaces per tab and I wanted to update them to 2 spaces per tab).

First, I opened Vim and set the current directory to the root of my source folder.
:cd C:\blah\blah\source\code

Next, I told Vim to pull in all my .cs projects in the entire source tree.
:args .\**\*.cs

** means to go recursively down 30 directories (you can set the max depth, default is 30. Try :help ** for more).
Finally, I told it I wanted it to format each file, from beginning to end, using the "equalsprg" and then to save it.
:argdo exe "normal gg=G" | w

To break this down:
  • :argdo tells it to run the specified command on all "args", or all open files
  • exe tells it to execute the given command
  • normal runs the :normal command, which allows you to execute normal mode commands like motions, etc
  • gg goes to the top of the file, = formats the file, G goes to the end of the file
  • | chains commands together
  • w writes the file
Pretty awesome I thought.

Another common use of :argdo is to run a search and replace across many files. Open the files you want either with the :args command or from the command line. Then do:
:argdo %s/matchon/replacewith/ge | w


If this would require you to open a ridiculous number of files, most of which wouldn't have matches, then you should use the :vimgrep command instead. This will put only files that match your regex on the quickfix list. You can then move through them with :cnext and execute any commands you want. The downside here is that you have to execute your command over and over in each file.

Tuesday, October 14, 2008

Vim Learning

This is the ninth post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

At this point we have a very flexible, fast, and relatively easy to use environment for editing, all within Vim. As you can see, Vim is not the type of editor that does everything you want out of the box. The Vim philosophy seems to be: be capable of doing everything, but make no decisions on behalf of the user. In other words, where other software would have picked a bunch of defaults that they thought were best, Vim does nothing and lets you pick what you want. The downside is it takes time, and it can be hard to even know features exist. The upside is you can configure it just how you want it, and I get 9 blog posts out of it.

This post is about how you find out what Vim can do, and how to setup it up. Basically, this is how I figured out all the things in the last 8 posts.

#1 Vim Help
The best way to learn about Vim, what it has to offer, and how to configure it is to browse around the help. Just do :help and start navigating around. Make sure you read the first section of help.txt as it teaches you how to navigate the help. The most important thing to know is that CTRL-] follows a link ("tag") and CTRL-T takes you back.

Also, read :help help_context as it teaches you how to find help on the commands in a certain Vim mode (normal, visual, insert, etc).

If you're looking for something specific, but you don't know what vim calls it my best advice is to just not get discouraged. Keep fishing with :help , trying different possible words. Don't be in a hurry. Stay in the mind set of browsing around. Read what you land on, if it doesn't look right keep looking for clues before giving up. Frequently all you need to know is Vim terminology.

#2 Google
When fishing through Vim Help fails you, try Google. This may teach you the terminology you needed. If so, dive back into the Vim help.

#3 Vim Tips
The Vim Tips Wiki is the next best place to go. Here you'll find all kinds of stuff people have come up with that might be helpful for you. Most of the scripts I've written are simply adaptations of scripts I found on the Vim Tips Wiki. These can be somewhat scattered. You'll frequently have to read through all the "duplicates" because each will have slight variations. Generally you can get what you want by picking between the variations.

#4 Vim Scripts
The Vim Scripts page is similar to the Vim tips but contains more robust scripts rather than simple tweaks and tips. This is where you'll find things like the Snippets script.

#5 Real People
Sometimes you just can't get an answer on the web or from the help. In those cases, it's best to ask someone who may have more experience. I've had a lot of help from the guys on the Vim IRC channel (server: freenode, channel: #vim). If you don't have an IRC chat program I recommend ChatZilla which is an AddOn to Firefox.

Armed with this, you should be able to get Vim to do anything it's capable of. So if you come up with (or come across) any cool or useful scripts/tips/etc, please let me know!

Thursday, October 9, 2008

Vim File Editing

This is the eighth post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

In Visual Studio you have a solution which contains all of your files. You simply locate the file by clicking around through the tree structure, then double click to open it. When editing more than one file, Visual Studio puts each file in a tab.

In Vim you open files to be edited with
:e path
You can use the tab key to auto-complete directory and file names as you type them. This will open the file to be edited. If you don't know the name of the file and you need to click around a file browser to find it, do
:browse :e
This will open a standard file browser dialog and then open the file you select.

Vim uses the concept of a buffer when editing multiple files. Buffers aren't visible like tabs, but otherwise they're basically the same. To see what buffers are open do
:ls
You'll see a numbered list. To go to one of those do
:b2
where 2 is the number from the list of the buffer you want to switch to. Or if you'd rather use the name of the file do
:b file
where file is the name. Use the tab key to auto-complete from all the open buffers. This auto-complete will even work if the file doesn't begin with what you typed. For example, type "gram" and it will find "program.cs". This is tremendously helpful!

If you're looking for alt-tab like functionality so you can keep switching back and forth between the same two buffers do
:b#
This is another really useful command to remember.

Vim can also split the window and show you multiple buffers simultaneously, or the same buffer at two different locations. There are tons of ways to do this (see :help windows.txt). I'll show you the way I like to do it because I find it to be the easiest to remember.

To open a new horizontal split do Ctrl+w s. For a vertical split do Ctrl+w v. Then just use :e or :b to work on whatever file you want in that split (by default it will open to whatever was in the window when you opened the split).

To close a split do Ctrl+w q. To move between splits do Ctrl+w {h,j,k,l}. h,j,k,l move the cursor around when you're in command mode: left, down, up, right respectively. When you use them with Ctrl+w they move between splits instead of moving the cursor, but the direction stays the same so it's easy to remember. For example, if you have two open splits and you're working in the bottom one, Ctrl+w k will move you to the top one. Then Ctrl+w j will move you to the bottom one.

Vim also has support for normal visible tabs, but I find it's buffer support to be easier to use in the long run. Especially since you can only have so many tabs open before they become useless, and since file names (and paths) can be too long to display reasonably on a tab (just look at MS SQL Management Studio...). If you're interested, :tabe opens a new tab, see :help tabpage.txt for more details.

The last major feature is one that Resharper adds to Visual Studio (and is also available in TextMate I hear) which allows you to search for a file you want to open when you only know part of it's name and you don't know exactly where it is. I have found this to be unbelievably useful, so I wanted to have the same ability in Vim. To do this I adopted a script from Vim Tips to Windows (and removed the Perl dependency). Add the following to your vimrc:
function! Find(name)
let l:_name = substitute( a:name, "\\s", "*", "g" )

let l:files = system( "dir *".l:_name."* /B /S" )
let l:list = split( l:files, '\n' )
let l:len = len( l:list )

if l:len < 1 echo "'".a:name."' not found" return elseif l:len != 1 let l:i = 1 let l:cwd = substitute( getcwd(), '\\', '\\\\', "g" ) for line in l:list echo l:i . ": " . substitute( l:line, l:cwd, "", "g" ) let l:i += 1 endfor let l:input = input( "Which ? (=nothing)\n" )

if strlen( l:input ) == 0
return
elseif strlen( substitute( l:input, "[0-9]", "", "g" ) ) > 0
echo "Not a number"
return
elseif l:input < 1 || l:input > l:len
echo "Out of range"
return
endif

let l:line = l:list[l:input-1]
else
let l:line = l:list[0]
endif
let l:line = substitute( l:line, "^[^\t]*\t./", "", "" )
execute ":e " . l:line
endfunction

command! -nargs=1 Find :call Find("")

Note: this script depends on the DOS dir command. It would have to be modified to work on a different system.

To use it simply type
:Find part of file
This will search recursively from your current directory (:cd) for files whose names contain *part*of*file*. It will then display a numbered list of matches and ask you which you'd like to open. Simply type in the number and hit enter, and the file opens.

With these techniques at your disposal you can now edit many files in a way which I believe to be much superior to what Visual Studio has to offer.

Update 5/4/2010:
Added :b# for alt-tab like functionality

Wednesday, October 8, 2008

Vim to and from Visual Studio

This is the seventh post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

Now that we've got Vim setup to a point where it's quite useful for doing C# development, we need to start actually using it. As I've discussed in the past, there will still be lots of times when you'll want to use Visual Studio. Whether it be for the Designer, or for Exploring APIs you're unfamiliar with through Intellisense, or for manipulating resources, settings, project, or solution files, or for debugging.

VS -> Vim
The key is to be able to get back and forth between them easily. To get from Visual Studio to Vim is the easiest. Simply add an "external tool" which launches Vim and opens the current file. In VS go to Tools -> External Tools. Click Add and enter the following:
Title: Vim
Command: C:\Program Files\Vim\vim70\gvim.exe
Arguments: +$(CurLine) "$(ItemPath)"
Initial directory: $(SolutionDir)

There will now be a "Vim" item in your Tools menu which will open Vim to the current file AND the current line.

You can assign a shortcut key to this command as follows.
  1. Note exactly where the "Vim" command appears in the Tools menu (How many items from the top or bottom is it?)
  2. Go to Tools -> Customize -> Toolbars
  3. Click on the Tools menu so it opens and find where the Vim tool was, it will now say External Command X where X is some number. Remember X.
  4. Back on the Customize window, click "Keyboard..."
  5. Type "ExternalCommandX" into the "Show commands containing" box, where X is the number you just found
  6. Choose your shortcut key and assign it. I use Ctrl+Shift+V, Ctrl+Shift+V
Now you can open Vim from Visual Studio with a simple shortcut key sequence.

Vim -> VS
To get from Vim to Visual Studio is pretty easy as well. Assuming that your current path (:cd) in Vim is the path containing the .sln file, you can simply type the following:
:! *.sln

When you hit the tab key Vim will automatically expand to the full name of the sln file. Hit enter and the solution will open in Visual Studio.

Tuesday, October 7, 2008

Vim Code Folding

This is the sixth post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

Visual Studio has a feature called "Outlining" which automatically allows you to collapse and expand regions, comments, methods, classes, namespaces, using statement blocks, etc. Ctrl+M, Ctrl+M will expand and collapse the block that your cursor is in. Ctrl+M, Ctrl+O will collapse all methods and summary comments (but not classes and namespaces).

Vim has this same ability built in but calls it Folding. The difference is simply that it has to be turned on if you want it, and that it doesn't understand your code as well as Visual Studio does (though it can be taught!).

In Vim, there are a number of different ways that folding can be done: syntax based, indent based, marker based, and manual. Syntax based looks for folding to be defined in the syntax file for the language being edited. Indent based folds lines that are at the same indent level. Marker based looks for a given character sequence and folders everything between those characters. Manual allows you to define where the folds should be.

I like to use the Syntax folding that's defined in the default Vim C# syntax file. This will fold #region ... #endregion blocks.

To make sure this is always on when I'm editing C# files I added the following to my vimrc:
if !exists("autocommands_loaded")
let autocommands_loaded = 1

" setup folding
autocmd BufNewFile,BufRead *.cs set foldmethod=syntax
endif

Note: if you've setup an autocmd for C# building as in my earlier post make sure you use the same if !exists()... block.

The following commands are used to open and close folds:
zo - open fold under cursor
zc - close fold under cursor
zR - open all folds
zM - close all folds

You can remember the "z" by thinking of those old accordion reams of paper where each sheet was connected to the next and imagining it from the side as you lift and lower the top sheet. From that profile the paper will appear to form a "z" as you fold and unfold it.

See :help fold.txt for more details.

Monday, October 6, 2008

Vim Snippets

This is the fifth post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

Snippets are code templates that you can have inserted into your code. Its kind of like copying and pasting from a file with a bunch of common code blocks in it, but faster. Visual Studio has support for snippets, but they require bouncing through menus to find what you want, so they're not that convenient. As such, I don't know anyone who uses them. The only snippet Visual Studio does have that I use is the one for summary comments. When you type '///' it expands to a full summary comment block. It even includes your parameter names and everything, which is pretty sweet.

The TextMate editor on the Mac recently brought a lot of attention to the concept of snippets, and so now everyone loves them. Mostly because the way TextMate implemented them was easy to use, and because it came with a lot of good predefined templates for Ruby on Rails.

Not surprisingly, someone wrote a script for Vim that mimics TextMate's snippet support. Follow that link, then follow the instructions and you'll have it all installed.

I then created a cs_snippets.vim file in ...\vimfiles\after\ftplugin to define a few C# snippets. This is what my file looks like now:
if !exists('loaded_snippet') || &cp
finish
endif

" summary comment
Snippet /// ///<summary><CR><{summary}><CR></summary>

" object declaration
Snippet dec <{Type}> <{VarName}> = new <{Type}>();

"foreach
Snippet foreach foreach ( <{Type}> <{Var}> in <{Coll}> )<CR>{<CR><CR>}

"try/catch
Snippet try try<CR>{<CR><{}><CR>}<CR>catch<CR>{<CR>}

With these snippets you can type: ///<Tab> and it will expand to:
///<summary>
///<{summary}>
///</summary>

The summary tag in the middle will be highlighted and you can simply type whatever you want to write over it. Then hit tab to commit the value you typed and move to the next tag, if there is one. If you have the same tag name in more than one place in your Snippet all occurrences will be replaced.

Check out :help snippet for more details.

Let me know of any useful snippets you use too.

UPDATE 12/23/2009:
I recently switched from using the SnippetsEmu plugin I wrote about in this post to using SnipMate.  The main reason I switched is that SnipMate allows you to define your snippets on more than one line, which makes them much easier to get right and keep up to date.  SnipMate also seems to work a little better when you're filling in your snippets.  I highly recommend you check it out.

Friday, October 3, 2008

Vim Help Integration

This is the fourth post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

The last post on Vim Intellisense talked about using ctags to navigate to the definition of a class/method and read the documentation there. This covers any code you, or your company, has written, but it leaves out all of the .NET framework's objects. That's a pretty big oversight.

The problem is we need to know what methods exist on a .NET object, or what parameters a .NET object accepts, or just general help on a certain .NET object. This information is all easily obtained from the MSDN library, a largely under utilized resource as most developers I know depend primarily on Intellisense instead.

To solve this, we'll setup Vim so that you can put the cursor on any word and hit F1 and Vim will automatically open your browser of choice and do a search of the MSDN library for that word. To do this, add the following to your vimrc:
" setup integrated help
function! OnlineDoc()
let s:wordUnderCursor = expand("<cword>")

if &ft =~ "cs"
let s:url = "http://social.msdn.microsoft.com/Search/en-US/?Refinement=26&Query=" . s:wordUnderCursor
else
execute "help " . s:wordUnderCursor
return
endif

let s:browser = "\"C:\\Program Files\\Mozilla Firefox\\firefox.exe\""
let s:cmd = "silent !start " . s:browser . " " . s:url

execute s:cmd
endfunction

map <silent> <F1> :call OnlineDoc()<CR>
imap <silent> <F1> <ESC>:call OnlineDoc()<CR>
Notice that I use firefox, and that the help site to use is determined based on the file extension of the current file. This allows you to set this up for any language you work with. Finally, if the extension isn't defined it'll open up Vim's help.

Thursday, October 2, 2008

Vim Intellisense

This is the third post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

Before you get excited, I can't tell you how to get Intellisense setup in Vim. I can just tell you how to get close. I would say close enough, but you'll be the judge.

Intellisense in Visual Studio can do the following things:
  1. Complete variable, class, and method names as you type them
  2. Show you what methods/properties/etc are available on a given class after you type "class."
  3. Show you summary documentation on methods/properties/classes/parameters
Visual Studio can also take you to the code that defines a class/method/property with "Go To Definition".

In Vim, I can do #1 (sort of) and "Go To Definition." I claim this is "good enough" in most circumstances because Go To Definition takes you to the code where the method documentation resides AND it makes it easy to get right back to where you came from. This is obviously much more work than it is in Visual Studio where all that information is simply at your finger tips, but I found that the majority of the time the information is in my memory. And when it isn't, going to the definition and then coming back isn't so costly that it is a deal breaker, at least for me.

But in the interest of being very plain and transparent about this, Vim can't even come close to touching Intellisense, and there are many times when Intellisense makes life a lot easier. In these times, I work in Visual Studio. With that out of the way, on to how to do this in Vim!

The first part, Word Completion, is built in to Vim and you don't have to do anything at all to turn it on. Simply hit <ctrl+n> and Vim will autocomplete the word you're typing. If there is more than one match, it will show them in a popup menu. Use <ctrl+n> and <ctrl+p> to move forward and backward through that popup. Type anything to select the word. Vim uses every word in every buffer you've opened (in the current session) to match against, so it will always work on variable and method names in the same file and will work on those in other files if you've opened that file.

The second part, Go To Definition, requires more work. First you have to get a program called ctags. When you run ctags (from the shell) it builds a "tags file" which is basically a dictionary of every method and class name in every file you told it to parse. Vim knows how to parse a tags file, so you can then position your cursor on a method name in Vim and type <ctrl+]>, and Vim will take you to the file and line where that method is defined. After you've found what you need and are ready to return to where you came from simply type <ctrl+t>.

To run ctags just go to the top directory of your source code and run:
ctags --recurse
This will parse all the files in that directory and all it's subdirectories and then create a "tags" file in that directory. By default Vim will look for tags files in Vim's current directory and in the directory where the file you are editing is located. The only trick here is that you have to keep the tags file up to date by manually re-running ctags if you add or remove methods.

Wednesday, October 1, 2008

Vim TFS Integration

This is the second post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

Where I work, we use Microsoft's Team Foundation Server Source Control. It's not very good at merging, but other than that it's a good tool.

Unlike some other source control tools, in TFS a "get" downloads the latest version of a file, a "checkout" lets you edit a file. Basically all a checkout does is make the file not readonly, but you have to do it or else TFS wont let you check the file in when you're done.

Because of this, if you're using Vim to do your work, when you first open a file and try to go into edit mode Vim will warn you that the file is readonly. This reminds you that you need to check it out. It would be very annoying if you had to switch over to the command line (or VS!) to check it out just so you could start editing. So don't do that! Just add this to your vimrc:
" setup TFS integration
function! Tfcheckout()
exe '!tf checkout "' expand('%:p') '"'
endfunction
command! Tfcheckout :call Tfcheckout()

function! Tfcheckin()
exe '!tf checkin "' expand('%:p') '"'
endfunction
command! Tfcheckin :call Tfcheckin()

The "expand" part will expand to the current file with it's full path included (Note: you have to use the execute command instead of running the ! command directly or else you'll have problems with parenthesis not being properly escaped in your file path).

Now you can simply type :Tfcheckout, and the file will be checked out. When you're all done type :Tfcheckin and the TFS checkin dialog will open, allowing you to enter a comment, checkin any other files, associate the checkin with a TFS work item, etc.

Monday, September 29, 2008

Vim C# Compiling

This is the first post in my series on using Vim to do C# development. You can read the introduction into why someone might want to do that here.

The most important thing to be able to do comes in two parts:
  1. Compile
  2. Step through errors
In college we did development in Java without any kind of IDE. So you typed in your text editor. Then switched to the DOS prompt and "javac"ed. When there were errors, which there always were, you opened the file with the error and navigated to the line where it occurred. This was slow and tedious, but not the end of the world. Until you get used to Visual Studio and being able to F5, and then simply double click on an error.

How do we do the same thing in Vim? First, we have to compile. To start with, I'm going to compile using the following command:
devenv slnname.sln /Build Debug

This will perform the build exactly like Visual Studio would, just without opening Visual Studio. I put this command in a .bat file in the same directory as the .sln called build.bat.

To get Vim to use this batch file to compile:
set makeprg=build.bat

Now from within Vim just type :make when your current directory (:cd) is the one containing the build.bat file, and your solution will build.

What about parsing out the errors? Easy:
set errorformat=\ %#%f(%l\\\,%c):\ %m

This tells Vim how to parse the error output.

Now if there are errors, hitting Enter will take you directly to the file and line where the first error occurred. :cn will take you to the next and :cp will take you to the previous. :cl will list all errors. Read :help quickfix.txt for more.

You could also use msbuild to compile your solution. The command for this is simply msbuild /nologo /v:q. It will find the .sln in the current directory and build it for you. However, with this command you have to modify your .csproj so that the error output includes full paths (otherwise the errorformat wont be able to parse it). To do that, just add the following line to the common PropertyGroup element of your .csproj:
<GenerateFullPaths>True</GenerateFullPaths>

The error format is the same as for devenv. But you don't need the build.bat (if you will always have only one solution in the directory at a time), instead you can use this:
set makeprg=msbuild\ /nologo\ /v:q

Now you can happily compile C# solutions and step through errors from right inside Vim.

If you don't like having to add the GenerateFullPaths node to your project file, you can add it to the msbuild command line instead as follows:
:set makeprg=msbuild\ /nologo\ /v:q\ /property:GenerateFullPaths=true

There is one more enhancement we can make. Vim has the ability to easily switch between compilers and set all the settings that the compiler needs as part of the switch. You can enable this by creating a "devenv.vim" file in vimfiles\compiler (on windows) containing the following code:
" Vim compiler file
" Compiler: DevEnv

if exists("current_compiler")
finish
endif
let current_compiler = "devenv"

if exists(":CompilerSet") != 2 " older Vim always used :setlocal
command -nargs=* CompilerSet setlocal <args>
endif

" default errorformat
CompilerSet errorformat=\ %#%f(%l\\\,%c):\ %m

" default make
CompilerSet makeprg=build.bat

To use this, just type :compiler devenv. Or, if you want Vim to always use this anytime you're editing a C# file (a file with a .cs extension) add the following to your _vimrc:
" setup C# building
if !exists("autocommands_loaded")
let autocommands_loaded = 1
autocmd BufNewFile,BufRead *.cs compiler devenv
endif

If you have any improvements to add, please let me know in the comments!

Sunday, September 28, 2008

Visual Studio Development

When I work on C# programs (which is what I do for a living, so I do it a lot), I work in Visual Studio. Currently, that means VS2008.

VS has lots of wonderful features, including:
  1. Intellisense
  2. "Go to definition"
  3. Integrated building and error output parsing
  4. Integrated debugging
  5. Solution/Project management
  6. Windows Forms/WPF designer
  7. Basic Refactoring
You can add Re-sharper, and then you get more, including:
  1. Compile as you type
  2. Code form suggestions
  3. Find file by name search
  4. Find method/class by name search
This is all wonderful, but it comes at a price. Namely, speed. Because VS can't possibly know when you're going to want what features, it has to prepare them all continuously. This means opening a solution takes forever. Opening the designer takes forever. Building takes forever. Add Resharper and your problems just get worse.

It's a trade-off. Lots of people are willing to sacrifice speed for the convenience of these features. Until recently, I was one of these people.

A lot depends on the kind of work you do. For awhile now, my kind of work has had me opening and closing different solutions many times through out the day. As well as having multiple instances of VS open at the same time.

First I got rid of Resharper. I had to. There were times when I could type faster than the letters could appear on the screen because it was busy compiling my changes. Plus, I realized that I didn't like it's implied style of development. With Resharper, it's assumed that the code you're writing should be perfect the first time. So it's always formatting it for you, and suggesting shorter ways you could write it, or pointing out that you could move this variable from here to there, etc.

I discovered that I don't write code line by line, I write it in "logical units", working through the details. Then I go back and make everything perfect when I'm satisfied with it. My mind is on more than just the one line I'm currently typing. I'm thinking about the whole thing. So when Resharper wants me to stop and think about some minor code form improvement, or when it suddenly moves my code around "formatting" it, it only serves to distract me.

So Resharper had to go. I did miss knowing that I'd typed an error without having to wait for a build. And I also missed being able to open a file by just typing it's name in the search box. But I found those to be very minor niceties overall.

There's this article that Steve Yegge wrote called Effective Emacs. He talks about all kinds of minor little Emacs details. But his larger point is that because he knows how to use Emacs so well, and because it does only what he asks it to, he is very efficient with it.

This got me thinking about Visual Studio, and all the time I spend waiting for it, or clicking around looking for things (files in Solution Explorer, methods/classes in Intellisense). I realized that the power of Visual Studio is that it tries to do so much for you, and hide so much (mostly) irrelevant detail from you. This makes it easier to learn how to develop things. And it can also save you time by generating code, and build scripts, etc for you.

Intellisense is the best example of this. It's always guessing what you're probably trying to type. This is great because it helps remind you what the full method names are, or what parameters they accept.

Visual Studio's whole goal in life is to require the programmer to do as little work and put in as little effort as possible. On the surface of it this seems great. But I suspect that less work and less effort doesn't always result in greater productivity.

For example, it's easier to randomly click through Intellisense, looking for something that might do what you want than it is to look up documentation. But the documentation is more likely to show you the right way to do what you're looking for, and explain it to you. You just have to put in more effort reading through it.

So, wouldn't it be better in the long run to use a tool that is very powerful, but stupid? Allowing you to do exactly what you want, but not trying to guess what you want, and not trying to do it all for you?

It seems quite clear to me that if you're willing to put in the effort, you could get a better development experience using something other that Visual Studio. You'll spend less time waiting for VS to do things for you, and more time thinking about just how you want to do it. You'll get to state what you're looking for, rather than clicking all over trying to find it. Basically, your mind will be more actively engaged, instead of passively waiting for VS to solve problems for you.

I'm not suggesting that Visual Studio is worthless. I'm just suggesting that there may be times when using a different tool would be better, and other times when VS would be better. Why not figure out what those times are, and use the right tool at the right time?

I've been working on that. My tool of choice is gVim, because I know it the best, and I like the modal editing concept better than shortcut key acrobatics. I'm going to write a series of posts documenting everything I've done to try and use Vim to develop C# in an environment where everyone else is using only VS.

In the meantime, let me know what you think about the idea of VS = least possible effort != greater productivity.

Links to Posts in Series:
Vim C# Compiling
Vim TFS Integration
Vim Intellisense
Vim Help Integration
Vim Snippets
Vim Code Folding
Vim to and from Visual Studio
Vim File Editing
Vim Learning
Vim File Navigation

Wednesday, November 14, 2007

Happy Viming

In Programming Meets Editing I mentioned that my favorite editor is gVim, and that I was considering buying ViEmu so I could use the Vim input model inside Visual Studio. Today I finally got myself in gear and bought ViEmu and installed it at work.

ViEmu shoutout: Its impressive. It can't be easy to make Visual Studio play well with the Vim input model, but ViEmu manages it flawlessly. It even has a pretty smart method of managing Visual Studio's keybindings. If you want to go in and out of "ViEmu mode" it will disable and enable conflicting keybindings for you.

If you've ever been interested in learning Vim, the ViEmu developer Jon has created some really nice "graphical cheat sheets" that make learning Vim quite a bit easier. He has also written some good articles on why Vim is so nice: "Why, oh WHY..." and "The Vi input model". Those articles will sum it up better than I can, so I recommend you check them out if you're at all interested.

But that's not going to stop me from throwing in my own 2 cents. What makes Vim great?
  • It is comfortable to use
  • It lets you say what you want to do
Its comfortable because your fingers hardly ever have to leave the home row. Just the fact that you can move the cursor around with out moving your hand over to the arrow keys becomes really nice. I'm serious! It seems like such a minor thing, but after you've used it that way for awhile, going back will annoy you. Its like when you have a badly designed UI where you have to type in a text box, then move the mouse to select the next box, then type more, then move the mouse, then type more, etc.

Another example is the "t" and "f" keys which are like mini searches. "t" means to and "f" means find. Type "fa" and it will move your cursor to the next occurrence of the letter a on the current line. "ta" will move your cursor to right before the next occurrence. "T" and "F" go backwards. Again this is nice because it replaces a string of keyboard actions that might look like "ctl+right,ctl+right,right,right,right" Not only is that simply more keystrokes, it also requires you to move your hands around and perform some control key acrobatics.

Both of these examples demonstrate how Vim is comfortable. The second also demonstrates how it lets me say what I mean. Instead of using a combination of meaningless movement keys to get to the letter a, I said "go to a." At first blush this doesn't seem like it would matter, but as the Vim commands become second nature you can start talking to your editor at a much higher level without thinking about it.

It lets you stay focused on what you're trying to do to the text and not how to do it.

Its important to note that these are just the simplest examples I could think of. Vim has A LOT more to offer. Its also important to answer this question: will it make you more productive? Maybe, I don't know, its hard to say. Does it matter? If it makes you more comfortable and less irritated (ctl+right,ctl+right,ctl+right,ctl+right,ctl+right...), isn't that good enough? After all, I'm going to guess you spend a lot of time typing into that editor of yours.

Finally, if you're interested in giving Vim a shot I would certainly encourage it. It does have a pretty steep learning curve, but the cool thing is you can still do all the "notepad" style editing things you're used to. So you can learn it at whatever pace you want to, one feature at a time. If you're in Visual Studio, ViEmu has a 30 day trial. If you're in Eclipse, there is a Vi plugin. And if you're just editing text there's always gVim.