Wednesday, December 9, 2009

Vimgrep Tips

I've mentioned vimgrep in a previous post, but I neglected to mention a few useful flags that can be used in conjunction with it.

If you apply the 'g' flag to your vimgrep, it will return all matches instead of just one match per line.

:vimgrep /foo/g **/*

If you apply the 'j' flag, Vim will not automatically jump to the first match.

:vimgrep /foo/j **/*

Thanks to Chanel for pointing these out.

Thursday, December 3, 2009

More on Text States

A few people have asked me for more information on text states. An anonymous reader contributed the following in the comments of my previous post on the topic.

Using g+ and g- is very different than using u and ^r.

Try following:
* Create new file
* (in normal mode) Type iOne - Esc
* Type oTwo - Esc
* Type oThree - Esc
* Type oFour - Esc
* Type oFive - Esc
* Type 2u
* Type oSix - Esc
* Type oSeven - Esc

Now you have an undo tree with 2 branches. Typing u only goes up the last branch. Using g- goes up by time - branch doesn't matter here.

Have a look in :help usr_32.txt for good explanation of using the undo tree.

Thanks to whomever contributed the tip!

Wednesday, December 2, 2009

Indent From Normal Mode

From normal mode, pressing == will indent the current line.

Tuesday, December 1, 2009

Starting on a Specific Line

An anonymous reader writes:

You can open a file on the command line and automatically put the cursor on the last line by typing:

vim + file

If you want vim to start at a specific line you can do the following instead:

vim +LINENUMBER file

Thanks for the tip!

Monday, November 30, 2009

Text States

If you're using Vim 7+, you can use g- and g+ to go between text states. For a more advanced usage see the :help earlier and :help later.

Tuesday, November 24, 2009

Jumping to a Buffer

If you have split windows open with multiple buffers, you can jump directly to a specific buffer number by doing the following:

N<C-w><C-w>

N is the window number you want to move the cursor to.

Thanks to Duff for the coffee!

Monday, November 23, 2009

Indent From Insert

In the comments of my last post, graywh left a great tip that I didn't know about. If you're working in insert mode, you can change the indent level of the current line using <C-t> and <C-d>. These commands work no matter where your cursor is positioned on the current line and adjust the indent level based on your shiftwidth setting.

Thursday, November 19, 2009

Shift-Tab'ing

I have the following in my vimrc:

set sts=4
set et

This allows me to take advantage of the convenience of the tab key when editing while actually inserting spaces into the current buffer. Intuitively I've always wished I could shift-tab to unindent the current line one tab stop. After a minute of fiddling with my vimrc, I found a solution.

imap <S-Tab> <C-o><<

I should also mention that << and >> shifts the provided text based on your shiftwidth setting.

Tuesday, November 17, 2009

The Tao of Programming

I stumbled onto this quip recently and found it particularly poignant.

"A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James"

Monday, November 16, 2009

Last Insert

Hitting gi in normal mode will take you to the last location where you were in insert mode. This is great for bouncing back to where you were editing after browsing the current buffer from normal mode.

Friday, November 13, 2009

Last Directory Visited

From the shell, typing "cd -" will take you to the last directory visited. This is useful from a command-line navigation perspective and from inside of shell scripts as well.

Thursday, November 12, 2009

Last Command

Hitting "fc" from a Bash shell invokes your default editor (hopefully Vim) on your last shell command and executes it after Vim exits. This is great for command-line history editing after the fact.

-e ENAME selects which editor to use. Default is FCEDIT, then EDITOR, then vi.

Wednesday, November 11, 2009

Window Scrolling

Hit ctrl-e to scroll the current window down. Hit ctrl-y to scroll the current window up. An advantage of using these commands is that the cursor stays in the current location. Try it!

Reader Question: Tags?

Daniel Näslund writes:

"I use tags a lot. But I'm annoyed by all those open files it leaves
behind. It would be great if the file opened with g] or Ctrl-] would be
closed with Ctrl-T. If the file had been previously opened it would
remain open.

Another thing is a way to close all files except those currently viewed."


I don't use tags too often, so perhaps another reader can answer that question, but if you want to make all buffers except for the current buffer hidden, you can type in the :on ex-command. If you want to hide modified buffers as well, you can do :on!.

If the desired behavior is to actually delete the buffer, and you know it's buffer # or filename, you can do the following:

:bdelete file1 file2 file3

or something like

:1,3bdelete

Lastly, if you want to use a script to accomplish this, there's the BufOnly.vim which provides a single command to unload all buffers except the current one.

http://www.vim.org/scripts/script.php?script_id=1071

Reader Question: MMM Mode?

Chris Keating writes:

"Could you ask your readership if there's a vim equivalent for emacs MMM mode:
http://mmm-mode.sourceforge.net/

mmm mode basically allows you to have different syntax highlighting for different parts of your document. This is really handy when you have SQL embedded in strings, etc."


Anybody have any ideas?

Tuesday, November 10, 2009

Setting Options

Typing :options will allow you to set options interactively from inside of Vim. Just choose a command set to edit, and edit from there. This is a nice way to discover new settings.

Monday, November 9, 2009

Undo Levels

You can set the number of desired undo levels by issuing a :set undolevels=N ex command.

Friday, November 6, 2009

Autowrite

If you're tired of Vim asking you if you want to save the current buffer, you can :set autowrite to avoid this. Be careful if you enable this settings as it relies on your own prudence to prevent accidents from happening.

Thursday, November 5, 2009

Next and Previous Characters

Hitting "^" will take you to the first non-blank character on the current line. Hitting the Enter key will take you to the first non-blank character on the next line. Hitting "-" will take you to the first non-blank character on the previous line. All these should be executed from normal mode.

Wednesday, November 4, 2009

Beginning and End of a Buffer

Hitting "gg" in normal mode will take you to the first line of the current buffer. Hitting "G" will take you to the end of the current buffer.

Tuesday, November 3, 2009

Grab A Ruler

If you :set ruler in your vimrc, you'll retain a constant ruler at the bottom of your editing window. It contains the same statistics as provided by ctrl-g and allows valuable information to be gleaned with a quick glance.

Monday, November 2, 2009

Knowing Where You Are

If you want to know the current filename, what percentage of the current file you're editing, whether the current file has been modified, or the character or line position, all you have to do is hit ctrl-g from normal mode inside Vim.

Friday, October 30, 2009

More Posts Coming

I know Daily Vim hasn't exactly been "daily". I've got a bunch of posts prepared for the next few weeks. If the response continues to be good, I'm going to try and increase the post frequency on this blog. I appreciate the feedback and contributions you guys and gals have offered so far. If anyone wants to contact me directly with suggestions for posts, please send an email to tinymountain at gmail dot com.

Repeat Last Substitution

If you want to repeat your last substitution on the current line hit the "&" character from normal mode.

Quick Exits

Hitting ZZ in normal mode will exit and save the current file. Hitting ZQ will exit without saving.

Handy Shell Pattern

When piping commands, you can often benefit from breaking your data into multiple lines. A combination of sed and xargs can make this very easy to do. Take the following commands for example:

cd /tmp && mkdir blah && cd blah;
touch file-1 file-2 file-3;
ls | sed 'p; s/-//' | xargs -n2

Breaking this down, we create a directory and touch three empty files. From there, we use sed to print two lines. The first line is the original file name, the second line is the filename without the dash. From here, we can use the -n argument in conjunction with xargs to merge the two lines back into a single line. The resulting output would be:

file-1 file1
file-2 file2
file-3 file3

Once you have the lines joined, you could do something like:

... | while read a b; do mv $a $b; done

Bonus tip: the "read" bash builtin takes a line and associates each word with a given variable. Type "help read" from the shell for the complete documentation.

In summary the full command-chain for this tip would be:

cd /tmp && mkdir blah && cd blah;
touch file-1 file-2 file-3;
ls | sed 'p; s/-//' | xargs -n2 | while read a b; do mv $a $b; done

Thanks to Chris Sutter for contributing this handy shell pattern, and thanks to Andeers for the coffee!

Friday, October 23, 2009

Fun With Unicode ٩(●̮̮̃•̃)۶

Following up on the last post, you can also use CTRL-V to enter unicode characters. All you have to do is the following:

CTRL-V u (unicode character hex code)

Note that you can also combine multi-byte characters as demonstrated in the title of this post.

Wednesday, October 21, 2009

CTRL-V for Literal Characters

When typing in insert or ex mode, hiting CTRL-V allows you to enter a literal character. Some examples:

CTRL-V CTRL-M # enters a literal carriage-return \r
CTRL-V 10 <enter> # enters a null character

After entering the CTRL-V, you can either enter the character explicitly or type in its decimal code. A list of decimal codes is available through the :digraph ex command. If you're curious why this might be useful, I've used it on a number of occasions in conjunction with a substitution to remove binary characters from a file. An example might be:

:%s/CTRL-V CTRL-M//g # remove erroneous CTRL-M from the current file

You can find out the code for any character by putting it under the cursor and hitting "ga" in normal mode. For entering digraphs, you can also hit CTRL-K from insert mode and type the two letter character code preceeding the desired character.

Friday, September 18, 2009

Resizing with GNU Screen

I know a lot of you use screen frequently. My friend Chris gave me a tip recently related to resizing split windows in a screen session.

In screen, you can do <C-a>:resize [+-]N<CR> to resize a window +/- N lines

This is handy if you've got a cmd running and want to see when it's done. You can split the screen, load it in one window, and resize it to be small; thereby, preventing it from occupying valuable real estate on your monitor.

Screen has a handful of : commands such as :number N to change the numeric position of the current window. Take a look at the DEFAULT KEY BINDINGS section of man(1) screen for the the full list (parenthesized next to each key binding).

For more screen tips, check out the screen extravaganza posted back in 2008.

Mouse Tips

This has been mentioned on the blog in the past, but readers email me about it often enough that it deserves a formal tip. You can use the mouse to resize windows in Vim if you set your mouse as follows.

:set mouse=a

This will even work over a remote ssh session if you also set your term appropriately.

:set term=[the appropriate setting]

Options for term settings are as follows:

in the GUI: "builtin_gui"
on Amiga: "amiga"
on BeOS: "beos-ansi"
on Mac: "mac-ansi"
on MiNT: "vt52"
on MS-DOS: "pcterm"
on OS/2: "os2ansi"
on Unix: "ansi"
on VMS: "ansi"
on Win 32: "win32"

If the mouse setting interferes with your operating system's copy and paste ability such as the select to copy feature under X windows, you can revert to the standard behavior by holding shift while selecting text.

Setting your mouse as described also prevents accidental terminal scrolling with the mouse wheel when editing a file remotely and causes Vim to scroll within the current buffer instead.

Thanks to mmmattos for emailing me and providing the motivation for this tip.

Monday, September 14, 2009

Diffing From Inside Vim

To compare two files without resorting to launching vidiff from the command-line, you can do the following.

1) open one of the two files in a standard buffer
2) type in :vert diffsplit filename

Put the name of the file you'll be comparing in place of filename. Prefixing the command with vert gives you a vertical split. If you'd prefer a horizontal split, simply omit the vert.

Wednesday, July 29, 2009

Types of Registers

There was some mention of the special registers in Vim in the comments on my last post. Here's a list of all available registers in Vim (copied directly from the docs). For more info on what these registers do, please see :help registers.

There are nine types of registers:
1. The unnamed register ""
2. 10 numbered registers "0 to "9
3. The small delete register "-
4. 26 named registers "a to "z or "A to "Z
5. four read-only registers ":, "., "% and "#
6. the expression register "=
7. The selection and drop registers "*, "+ and "~
8. The black hole register "_
9. Last search pattern register "/

Tuesday, July 28, 2009

Insert Register Contents

If you're in insert mode and would like to insert the contents of a given register without going into normal mode, you can hit ctrl-r and then input the desired register. Between typing ctrl-r and the second character, a '"' will be displayed to indicate that you are expected to enter a register.

Friday, June 19, 2009

An Introduction to Clojure's Agents

For anyone that's interested in alternative programming languages, I've written a lengthy introduction to Clojure's agents.

For those unfamiliar with Clojure, it's a modern Lisp running on the JVM with excellent support for concurrency. It allows excellent interoperability with Java, so essentially you get a dynamic and clean programming language with a huge standard library. On the performance front, it's often on par with Java. I've spent a good deal of time learning the language lately, and I have to say that it's very enjoyable to work with.

One huge bonus of working with Clojure inside Vim is the VimClojure project. It allows interactive programming from inside of Vim and proxies code between a stateful NailGun server and the editor. To be honest, I wasn't aware that an interactive REPL was possible inside of Vim until I installed this, and I'm wondering if there are any other projects out there using similar techniques with different languages.

Wednesday, June 17, 2009

Switching from Horizontal to Vertical Split

If you have two windows which are horizontally split, and you'd like to make them vertically split instead, the following command sequence works well:

<ctrl-w>t<ctrl-w>H

To orient them back to a horizontal split do this:

<ctrl-w>t<ctrl-w>K

Note that if the top (or left) window is already current you can omit the <ctrl-w>t and simply do <ctrl-w>H or <ctrl-w>K.

Monday, June 15, 2009

Vi Mode in Readline Applications

Mike Pea submitted this comment in a recent tip, and I thought it deserved it's own post.

If you find that you do like using vi editing mode (and what's not to love about it :), add 'set editing-mode vi' to your .inputrc, and vi mode will work in any readline based client, eg psql, irb.

Thanks Mike!

Friday, June 12, 2009

Recursive Macros

A friend at work pointed out to me yesterday that he had accidentally written a recursive macro in Vim. I had never thought about the fact that this was possible, but I'd imagine there could be some potential usefulness for these somewhere. As a trivial (and useless) example, here's a recursive macro to move the cursor to the end of the current line one step at a time: qal@aq

Edit: A little research has shown that this is an excellent way to repeat a macro to the end of the file. Say that you have a file containing one number per line from top to bottom:

123
234
345
456

Put the cursor on the first line and type the following:

qaq (clears register "a" of any previous macros)
qa<ctrl-a><enter>@aq

Now type @a once more, and the macro will run to the bottom of the file incrementing the value on each line by one leaving you with the following:

124
235
346
457

Friday, June 5, 2009

Screen in OS X Leopard

Sorry for the horribly platform specific tip, but this has been annoying me, and I thought it might help someone. If you're running OS X 10.5, you may have noticed that screen destroys your path when you start it. This can easily be remedied by putting the following in your ~/.screenrc.

shell -/bin/bash

Thursday, June 4, 2009

Vim + Eclipse = Eclim

I know some of you may consider this to sacrilegious, but a lot of programmers are subjected to using Eclipse from time to time for various reasons. For those of you that need Eclipse for a given plugin, debugging session, or what have you, the Eclim project provides a flexible solution for integrating Vim with Eclipse.

Using Eclim gives you three options for how you'd like to integrate Vim and Eclipse. The least intrusive allows you to run a headless Eclipse and control it via Vim. This makes Eclipse act as sort of an app server, which Vim can pipe to and from.

The second option allows you to run both programs side by side. This way, Vim is still running standalone, but you can control Eclipse directly should you need to.

The final option allows you to embed Vim directly into Eclipse. You'll lose some screen real estate when using this option, but it may suit certain people's needs.

I'm not really a fan of Eclipse by any stretch of the imagination, but for things like Java debugging, it does offer some utility, so if you're in the same boat, you should give Eclim a try.

Wednesday, June 3, 2009

Recursively Replace Ctrl-M

Ctrl-M's are a plague inflicted upon programmers everywhere. I've mentioned a number of ways to deal with them in the past, and some readers have also contributed helpful advice as well. Today I ran into a situation where I needed to do a huge source diff on two different directory trees. My preprocessor happened to strip out all Ctrl-M leading to a bunch of false positives on files that differed. Some Google'ing around lead me to find this gem, which recursively strips Ctrl-M on all files within a given directory.


for file in $(find /path/to/dir -type f); do
tr -d '\r' <$file >temp.$$ && mv temp.$$ $file
done


In order to give credit where it's due, a user named blowtorch gave the tip at the following forum.

Disable Comment Autocompletion

There are times when Vim's autocompletion of comments gets in my way more than it helps me. Fortunately, disabling comment autocomplete is easy. Just add the following to your vimrc.

au FileType * setl fo-=cro

Tuesday, June 2, 2009

Snippit Support

Next time someone who uses TextMate starts blabbering on about how awesome snippits are, politely remind them that Vim supports snippits as well. You can download the snippitsEmu plugin here, and it works quite well. For those unfamilar with snippits, they allow tab-style completion of boilerplate code. For example, you might type class, hit tab, and then a template for a class will be expanded based on the current filetype Vim is set to.

Update: Several readers have cited snipMate as a preferred alternative to snippitsEmu. Thanks guys!

Monday, June 1, 2009

Easier Command Line Editing

Assuming you're using the bash shell, the following can be helpful when composing long command lines.

Start typing on the command line and then type Ctrl-x Ctrl-e, it should drop you into your system's default editor (hopefully Vim) and allow you to edit the command line from there. Once finished, save the command line, and bash will run the command.

Monday, May 18, 2009

Vim Cookbook

Run Paint Run Run has contacted me to share a Vim Cookbook he has been working on. It's a creative commons work, and although it's a work in progress, it appears that it's already chock full of useful information. The cookbook is forumulated in a Problem/Solution type format, and I highly recommend giving it a look.

Vim Recipes - Free cookbook for the Vim text editor

Wednesday, April 29, 2009

Vim Sugar

Chris Sutter writes:

I have a script and mapping in my ~/.vimrc:


function! CheckForShebang()

   if (match( getline(1) , '^\#!') == 0)

       map <F5> :!./%<CR>

   else

       unmap <F%>

   end

endfunction

map <F5> :call CheckForShebang()



This way, if i'm editing a script with a shebang at the top and i hit <F5>, it maps <F5> to run the script (if not, <F5> is unmapped, so that it doesn't keep checking if I hit it again). I always found myself mapping <F5> by hand to run the current script while i was editting/debugging and I'd frequently lose track of whether I had mapped it or not. You could, of course, replace <F5> with your favorite run/compile/debug/etc key, it just happens to be my standard (from my QBasic days hehe).

Thanks for the tip Chris!

Wednesday, April 15, 2009

i_Ctrl-O

Derek Wyatt shared this in a recent comment, and I thought it deserved it's own tip.

If you're in insert mode, and you hit ctrl-o, Vim will accept one normal mode command and then return you to insert mode. Two examples given showed some typical usage:

<C-o>ma - Mark the current position and then keep typing.

<C-o>gql - Format the current line and keep typing

A final blurb from the comment:

"The next type you do <Esc>(thing)a you might remember that you could have done that with <C-o>".

Thanks Derek!

Tuesday, April 14, 2009

Set Hidden

If you've ever tried to type :only and had Vim refuse to hide existing buffers because they contain changes, you can use :set hidden to override this behavior. Just remember to keep the possibility of hidden modified buffers in mind when you're doing a :q!.

Monday, April 13, 2009

Yank S-Exp

If you're hacking a Lisp dialect in Vim, you can do type ya( to yank the current s-exp into the default buffer.

Friday, April 10, 2009

Pull Into Ex

If you position your cursor over a given word and type :<ctrl-r><ctrl-w> it will pull the value into your current ex mode command line. This is great for yanking long values into substitutions among other things.

Thanks to Nate for the tip!

Wednesday, April 8, 2009

bashreduce

I stumbled across this project recently. It's a program that allows you to apply standard shell tools in a map reduce style fashion. Large memory hungry tasks like sorting can be distributed across machines to maximize throughput. As a bonus, it's written in bash, so it's highly portable and works with a combination of vanilla shell utilities and ssh shared-key authentication.

The bashreduce project.

Insert Mode Shortcuts

Here are some handy shortcuts that you can utilize while you're in insert mode.

ctrl-t - adjust current line one indent right
ctrl-d - adjust current line one indent left
ctrl-w - backspace over a word
ctrl-u - delete to beginning of indent

Monday, April 6, 2009

Why Functional Programming Matters

I'm always trying to sharpen my skills as a programmer. One approach I've been using to become a better programmer is to learn as many development methodologies as possible. In the past few years, I've become a big fan of functional programming. The basic idea behind functional programming is to compose your programs using functions that return a single value and avoid side effects whenever possible. A side effect is an action that is not required for a function to do it's work. An example of a function with a side effect would be:

function sum(a, b) {
    print "a + b = " + (a + b)
    return a + b
}

In this case, the print statement wouldn't be required to accurately calculate the sum, so it would be considered a side effect. A pure functional language prohibits side effects altogether; although, most functional languages allow some level of impurity for convenience.

Another common feature of functional programming is the use of higher order functions. Higher order functions are functions that take functions as their arguments; thereby, providing an additional level of abstraction. An example of a higher order function included in most modern languages would be the map function.

function square(x) { return x * x }
numbers = [1, 2, 3, 4, 5]
squares = map(square, numbers)
print squares
[1, 4, 9, 16, 25]

Higher order functions can typically take anonymous functions as their arguments as well leading to increased flexibility.

I can already hear you groaning as you read this article and saying, "yeah yeah, my language can do all that too... what's the point?" Well, in the typical zen fashion of functional languages, it's not always what you can do that matters; rather it's what you can't do. A striking difference between a number of functional languages and their imperative counterparts is how mutability is handled.

A number of functional languages such as Haskell, Erlang, and Clojure address the majority of their built-in types as immutable. This means that once a value is assigned to a local variable, it cannot be changed. At face value, this may seem like a huge disadvantage and might even lead one to believe that certain types of programs might be impossible to write. The truth is that any imperative program can be rewritten in a functional style but doing so requires the adoption of a new set of tools. Specifically, recursion must be adopted in lieu of traditional iteration. Things like closures can be used to simulate state, and objects are generally thrown by the wayside.

At this point, the resounding question in your mind is probably, "why bother?" Well, fortunately there's a very strong reason behind all this shifting of methodology, and that's concurrency. Anybody that's written a non-trivial multi-threaded program in an imperative language has dealt with the difficult issues of synchronization, locking, and sharing of state. The larger and more complex the program, the more difficult it becomes to avoid subtle errors and race conditions. For most programmers writing traditional multi-threaded applications, there are more things that can go wrong than right.

Functional programs that operate on immutable data don't have to deal with any of these issues. Since nothing is shared, there's no potential for race conditions, multiple threads stomping on one another's data, or any of the other trappings one might traditionally succumb to. Freeing the programmer from worrying about such things allows focus to be shifted to solving the actual problem at hand instead of dealing with the fine grained details of threading semantics.

Why should you care about threading? I believe the introduction to Java Concurrency in Practice puts it well when they say, "For the past 30 years, computer performance has been driven by Moore's Law; from now on, it will be driven by Amdahl's Law." Basically, processors aren't getting any faster. For many years, programmers have written code under the assumption that performance wasn't an issue because the next generation of processors would pick up the slack. We've reached the point where we'll never be able to assume this again. From this point on, things will become increasingly parallel, which means that learning to work with multi-core machines will become an increasingly marketable skill.

Traditionally relegated to academia, theorem proving, and compiler writing, functional languages are finally becoming mainstream by filling the multi-core niche. Even if you don't adopt a functional language for your day job, taking the time to learn a different method of problem solving will make you a better programmer and provide valuable techniques you can use in your day to day work.

This being said, there are some really nice languages out there to play around with. I will briefly highlight a handful of them for your perusal. Please take note, that not all of these adhere explicitly to the immutable state share nothing model previously mentioned; although, most provide exceptional facilities for multi-core programming.

Clojure - A modern Lisp running on the JVM. Clojure throws out all the cruft of old world Lisp and provides a lean and mean core with immutable data structures. One of Clojure's core features is excellent concurrency performance, and it also provides seamless access to Java libraries whenever desired.

Scala - Adpoted by Twitter to solve their initial concurrency issues that Ruby could not handle, Scala runs on the JVM, which makes deployment a breeze and provides a multi-paradigm approach to development.

Erlang - Initially developed as a proprietary language by Ericcson, Erlang was open sourced some years back. Erlang makes use of immutable state and sends data back and forth between managed processes using a built-in messaging system. The process model allows code to be seamlessly distributed across several cores, servers, or networks. Ericcson has successfully used Erlang to manage their telco switching on massive networks for many years.

Haskell - A purely functional language with an advanced type system. Haskell provides a robust feature set and an extremely advanced compiler. The ability to introduce arbitrary operators and a non-standard syntax can make Haskell intimidating at first glance, but it's concurrency peformance rivals any other language. Notable projects written in Haskell include the Xmonad window manager and Pugs, a Perl 6 compiler.

OCaml - Numerous wins in the ICFP helped OCaml gain initial notoriety. Native code compilers allow OCaml programs to run at blazing speeds, and a sophisticated type system provides both safety and flexibility.

F# - Developed by Microsoft Research, F# is a variant of ML with a core that is similar to OCaml. It runs on .Net and will be a fully supported language in the .NET Framework and Visual Studio ecosystem as part of Visual Studio 2010.

PLT Scheme - A functional language with a history in academia. The ubiquitious MIT book, how to design programs, uses PLT as it's host language. Excellent documentation makes PLT a great way to cut your teeth on functional programming, and it's concurrency features are actually pretty good as well. Threading in PLT is based on the mechanism used in Concurrent ML.

New Lisp - Although including the word "New" in the name of any product might not be the best idea, New Lisp fills a nice niche in the scripted functional language domain. It seems to be at least partially inspired by Paul Graham's Arc, and it provides a good number of modern features out of the box.

SBCL - One of the de-facto standard Common Lisp implementations. I haven't done any concurrency stuff in Lisp, but I do know that SBCL provides a high quality Lisp implementation for your general Lisp-ing needs. If SBCL doesn't meet your needs, Clisp is another very solid Lisp distribution.

Javascript - The ubiquitous Javascript language now has a JVM port and runs everywhere. It's one of the most widely deployed programming languages on earth and allows the application of higher order functions, lambdas, closures, currying, etc. Who would've thought there was a functional language right under your nose?

Wednesday, April 1, 2009

Goodbye Daily Vim, Hello Emacs

After some careful consideration, I've come to realize that it's time to switch editors. Vim has been a good friend, but like an old horse with a broken leg, it's time to put it down. A few days ago, a strange thing happened. Richard Stallman caught wind of this blog and sent me a DMCA takedown notice for documenting patented proprietary Emacs features (copy and paste). I tried to explain that these features were part of Vim as well, but he insisted that Emacs had prior art (implemented in 1953) and that the blog must be taken down at once. Determined to fight back, I decided to take a hard look at the Emacs internals to find some hidden weakness. After days of wanding through the Elisp forest, it happened... I fell in LOVE! Who would've thought that I could send email, surf the web, and play tetris all inside of my text editor? ZOMFG! I'm sorry folks, but if I would've realized what we've been missing, I wouldn't have wasted your time with all these silly Vim tips. This being said, I'll be shutting down this blog in the next 24 hours and dedicating my life to the Church of Emacs. I feel so seriously about this that I'm quitting my job here at Grooveshark and focusing my professional career on writing Emacs kernel modules and improving Emacs boot time. To any earthings that might be reading this, I've enjoyed my time on your planet, but the spaceship has landed, and I must return home. Farewell.

Tuesday, March 31, 2009

Windows Key Re-maps

On Windows, Vim has slightly different behavior for a few basic keys. Namely, ctrl-v, ctrl-x, and ctrl-z are re-mapped to make them more familiar to Windows users. Ctrl-v, which is probably the most widely used of these, is re-mapped to ctrl-q. To get the equivalent of a ctrl-z (background process), you can issue the :suspend ex command. I don't believe there are re-mappings for ctrl-a (add) and ctrl-x (subtract); although, you can probably override them in mswin.vim.

Survival Hacks

Many years back when I was first starting to get savvy with Linux, a co-worker approached me with a problem. He had yanked the harddrive out of his old Linux router and placed it in a different machine. The old machine had on-board ethernet and used a different driver than the new machine's PCI ethernet card. His only other computer was a laptop, which was currently offline due to the router issue. Thinking it would be an easy job, I downloaded a binary copy of the PCI driver and copied it onto a floppy at work. When I got to his house, I realized there was a bigger issue. My friend didn't have a monitor of any sort for the machine we'd be working on. We could have just given up and borrowed one from work the next day, but we decided to see how far we could get without one. We hooked up a keyboard and booted the machine waiting a few extra minutes to be sure we had a login prompt. From there, we very carefully logged in as root and mounted the floppy. The light on the floppy drive gave us a good indication that we were good so far. Not being able to remember the name of the driver forced me to do a glob copy based on the file extension to the /tmp directory, but again, the light on the floppy drive showed things were working. From there, we had another problem. We weren't sure if modprobe, the command to load a kernel module, would accept wildcards, so the globbing was no good this time. Still totally blind, I typed the following into the command line:

for I in *.ko; do modprobe ./$I; done

Fingers crossed, I hoped for the best and typed:

ifconfig eth0 192.168.0.1 netmask 255.255.255.0

From there, we plugged in his laptop, and tried to ping the machine. Much to our surprise, it was up and responding. Feeling accomplished, we did an ssh login from there, and got everything setup as it should be. Now, I'm not saying this was totally elite or anything, but it does go to show that a little creative thinking can get you pretty far. Feel free to share your own survival hacks in the comments if you have a similar story.

Friday, March 20, 2009

Out of the box Autocompletion

Thanks to Chris Sutter for contributing the following tip:

(The following applies to versions of vim higher than 7.0)

If you are editing a file in vim which ends with .php, .html, .css, .js, .sql, .rb, or .py, you can type (while in insert mode) ctrl-x followed by ctrl-o and vim's "omnifunc" feature combines with its built-in autocomplete feature to show autocomplete options specific to the corresponding language/markup. You can subsequently press ctrl-n and ctrl-p to browse through this list. In short, vim has autocomplete functionality for all common web development contexts (and probably some others) out of the box. But it's not just autocomplete.

If you are editing php (or, i imagine, ruby/python but i didn't try) and the text on which you are autocompleting is the beginning of a valid (builtin) function name, a small window will open at the top of your vim screen showing the method signature with argument names! No more jumping over to php.net to see if it's (needle, haystack) or (haystack, needle)...

Example:
Edit a file called foo.php, enter insert mode, type

<?php
str_r

Now press ctrl-x ctrl-o and vim shows a box below the cursor containing the following, with the first entry highlighted:

str_repeat( f
str_replace( f
str_rot13( f

The "f"s indicate that each entry is a function. If you had entered $_ and pressed c-x c-o, the results would have been "$_COOKIE", "$_ENV", and so on, labeled with "v" for variable)

The window opened above (since the selection is a function) shows:

str_repeat(string input, int multiplier | string

telling you the full function name, the argument types and names and finally the return type.

Admittedly, the c-x c-o and c-n/c-p stuff is awkward. I imagine you could remap to tab/shift-tab which is more common for autocompletion browsing in unix environments. The SuperTab plugin for vim does this for normal file-wise autocompletion (otherwise done in insert mode with c-n and c-p). It could probably be hacked to incorporate omnifunc stuff, too. If I see anything like that out there, I'll send something about it.

Please let me know if there's anything you think vim can't do and I'll see to ensuring you that, in fact, it can and it's easier than you think!

Tuesday, March 17, 2009

Vim + Cygwin Improvements

I've been stuck in a Windows environment at work for the last month or so doing Blackberry development. To try and make things more tolerable, I've been doing most of my work in a Cygwin environment; however, the Cygwin Vim build is sub-optimal compared to the native Windows build. This lead me to try and find a way to use Windows Vim seamlessly from inside Cygwin. The following alias worked out nicely:

[bash-fu borrowed from this tip]

alias vim='VIM=`cygpath -d "$VIM"` HOME=`cygpath -d "$HOME"` "`cygpath -u "$VIM"`/vim72/vim.exe"'

In this case, the $VIM environment variable is initially set to C:\Program Files\Vim. It's also important to change the vim72 version number to whatever matches your install.

The second thing I did, which is making life a lot easier, is switch to using Console2 as a replacement for the standard Windows cmd.exe. The combo of Console2, Cygwin, and a decent Vim build is a good bet if you're committed to Windows for whatever reason.

Tuesday, March 10, 2009

Change Last, First to First Last

Here's a tip borrowed from the Vim help file. Say that you have a list of names like:

Doe, John
Smith, Peter

and you want to change that to:

John Doe
Peter Smith

You can use the following substitute pattern to easily do so:

:%s/\([^,]*\), \(.*\)/\2 \1/

Basically, you're capturing zero or more NOT commas followed by a comma and space and then capturing zero or more of anything. The comma and space are outside the parens, so they're not stored. The parens store the captured groups in the special variables \1, \2, \3, \N from left to right, so the replacement pattern is substituting in the groups in the reverse order they were captured.

Monday, March 9, 2009

Tab Buffer Browsing

Using the following mappings in normal mode provides a convenient way to easily switch between the next and previous buffers.

nmap <tab> :bn<cr>
nmap <s-tab> :bp<cr>

Thanks to Chris for the tip!

Monday, February 9, 2009

Twistem.FM

Ok, this is not Vim related, but it is something I'm very excited about. Here at Grooveshark, the startup company I work at, we've just launched a new service. It's called Twisten (a play on tweet + listen), and it uses the Twitter API to aggregate tweets about music. For any song it can identify, it adds the tweet to a public timeline and allows you to play the song.

My primary role on the team was designing the parsers which identify meaningful bits of information inside a tweet and then converting them to actual songs. Fun stuff!

If you're a fan of Twitter (or music), check out Twisten.FM.

Autocommands

You can add an auto command to your vimrc to have it automatically executed when a certain type of file is loaded. As an example, I use the following to convert tabs to spaces when a PHP file is loaded.

auto BufReadPost *.php retab!

See :help auto for the full info.

Wednesday, February 4, 2009

Editor Comparison



A friend sent this to me, and I thought it was pretty funny. I'm not sure of the original source. Thanks Nate!

UPDATE: The comic is from this blog. Good stuff!

Tuesday, January 27, 2009

Ignore the Modified Flag

There are times when I'm working on a temporary buffer, and I want to do something like a `gf' (go to file), but Vim insists that the buffer is modified and refuses to abandon the file. You can get around this by telling Vim the file isn't modified.

:set hidden

This effectively makes Vim treat the file like it's already saved. Please avoid using this for any production files as it can make Vim think that the file on disk is different than it actually is.

Make Windows Equal Height

If you have a bunch of split windows of disproportionate sizes, you can make them all equal by doing a `ctrl-w =' in normal mode.

Tuesday, January 20, 2009

Converting Tabs to Spaces

Here's a quick way to convert a tab-stopped file to a space-formatted file.

:set expandtab
:retab!

Thursday, January 15, 2009

Last Changed Text

Here are two helpful commands to get to the last changed or yanked text.

`[ - First character of previously changed or yanked text
`] - Last character of previously changed or yanked text

Wednesday, January 14, 2009

Extending History

You can allow Vim to store more history than the default (last 20 commands) by setting history as follows.

:set history=N (where N is how much history you want to keep)

Tuesday, January 13, 2009

Delete to End of Page

Typing `dL' in normal mode will delete to the end of the current page. In other words, everything visible to the bottom of the window.

Monday, January 12, 2009

Remap Backtick

I find it convenient to remap the backtick key "`" to single-quote "'". Functionally, they are very similar. Backtick takes you to an exact mark location while single-quote simply takes you to the beginning of the marked line. I don't use the single-quote functionality much, and it's much easier to reach than backtick, so the following mapping saves some finger stretching.

nnoremap ' `
nnoremap ` '

Saturday, January 10, 2009

Reformat a Paragraph

Say you have the following text:

> someone said
> > someone else said
> > > long quoted message
> > blah blah
> blah

Place the cursor on the first line and do `gqip'. I often use this combo to conveniently reformat paragraphs.

Friday, January 9, 2009

Modelines

Vim allows you to insert modelines to specify options you'd like for a specific file. For example, you could have a perl script as follows:

#!/usr/bin/perl
# vim: set expandtab:
use strict;

This would tell Vim to expand tabs in the current file. See :help modeline for more info.

Thursday, January 8, 2009

Removing Ctrl-M

There are quite a few ways of doing this, but a quick way to remove ^M scattered around your file is as follows:

:%s/C-vC-m//g

Where C-v is Ctrl-v and C-m is Ctrl-m.

Wednesday, January 7, 2009

Command on All Windows

Here's a neat trick. If you want to execute an ex command on all windows, you can do the following:

:windo command

so...

:windo %s/foo/bar/g would find and replace foo with bar in all windows.

Monday, January 5, 2009

Only RSS Vim Tips

For those of you that would prefer to exclude any tips from this blog that aren't directly related to Vim from your RSS, I have an easy solution. Blogger allows feed URLs to be filtered based on tags. I only use the vim tag on posts directly related to Vim, so the following RSS URL should be a convenient solution.

http://dailyvim.blogspot.com/feeds/posts/default/-/vim