Thursday, September 15, 2011

Introducing Whitespace2.0.vim!

This is a raving that I wrote some months ago now while I was working a different job in a different country. I should point out that I liked the guys I was working with and they, generally speaking, were not retards...




The guys I'm working with are fucking geniuses and I fucking love them! I've been doing some maintenance on their PHP apps at work, and their coding standards are so advanced that Vim can't even support them out of the box! Luckily, I'm pro at vimscript and was able to write a plugin to help me!

<blink>Whitespace2.0! Now available on github! Get it here!</blink>

The making of Whitespace2.0 - A documentary

Right. First things first: we will need a random number generator. For this, we will nick some code from here.


Secondly, we will need to modify the behaviour of the tab key with this code:


Additionally, we need trailing whitespace to occasionally appear.

Sweet, that should do it.

PHP devs are blithering retards because Jesus made them that way

The other day a programmer at my work hacked on some PHP that I had written and, when I pulled the changes, I saw my code was now riddled with mixed indenting. I felt like he had just been in my bedroom and knocked all my transformers off the shelf and then just left them there. On the floor! That FUCK! I was going through Rapid Cyclic Weapon Escalation Syndrome1 and was in danger of rage-crapping my pants when I was reminded of that old bible story from primary school.

You know the one I'm talking about.

What are you? Stupid!? OK, here's an except:

... Jesus is on the assembly line putting together the final prototypes of all the programmers. He's bored as fuck and this shit has been dragging out all day - who knew there were so many fucking languages! All he wants is to be at home sucking on a beer and watching the tube, but instead he is stuck on the line putting the nerds together for daddy.

Poor Jesus...

So when the next head comes down the line, he pops the lid off and, instead of ramming in the corresponding brain, he hoists up his skirts and takes a giant shit right in there and snaps the lid back on ...

And thus explains why most PHP programmers are either:

A. too stupid to indent properly
B. completely ignorant about tabs, spaces and good indenting
C. don't know how to use their editors


(1). A mental disorder in which the subject fantasizes about killing someone with progressively larger and larger weapons until they have exhausted all possibilities, whereupon they begin combining weapons together into super-weapons. The ultimate culmination of which is a giant mega weapon made up of all known weapons in the universe.

Tuesday, October 12, 2010

Colorizing and autopaging svn diffs and other commands

I can't remember the last time I jacked off to black and white pornography.

Can you?

OF COURSE YOU CANT! Color is fucking awesome! No one yanks their crank to black and white shit anymore.

Once you've tasted color, you can never go back.

This brings us to the subject of version control. Over the last few years I've been spoiled by git, but have recently switched jobs and been using svn again. Using git has taught me to actually care what I'm committing — as opposed to just creating one giant commit at the end of the day — which has meant I've been looking at lots of diffs.

Git gives you lovely colorized, paged diffs that frequently stiffen the schlong. While svn, on the other hand, still gives you the same uncolored, unpaged horse shit as it did several years ago! I can't fucking believe the meat puppets at svn haven't gotten their asses into gear and stolen some basic UI ideas from the competition. WTF guys?!

Here's how you enable color for everything in git:

git config --global color.ui always

There are more granular options if you want them, but fuck that, color is awesome!

Svn has no such option. So I, like many others, have been forced to hack the mainframe to get color. Check my hacks:


This script defines a function called "svn" that hijacks calls to the svn program and essentially rewrites some of the commands. For example, this command:

svn diff -r1:7 foo

would get rewritten to:

svn diff -r1:7 foo | colordiff | sed -e 's/\r//g' | less -RF

Another example:

svn log foo

would get rewritten to:

svn log foo | less -F

Notice that I'm still interacting with svn via the same command set, and am not training myself away from the existing commands. Hopefully this will prevent me from losing the plot and ripping off cocks when forced to use svn on a machine that doesn't have my hacks.

Tuesday, July 13, 2010

Vim pr0n: Sample NERD tree plugins

I'm a lazy wank, and additionally: a bastard.

Which brings us nicely to our next point: The NERD tree API. In version 4.0 I added an API to allow people to add functionality to the NERD tree in the form of plugins.

I did this because I was getting tired of politely telling people where to ram requests for features that I either A. Would never personally use and therefore would probably do a poor job of maintaining, or B. Thought were good ideas, but was not interested in taking the plugin in that direction.

As a result, I've ended up writing a lot of small NERD tree plugins for people who have requested such features. In this raving I'll post and explain a couple of the simpler examples.

API Technical Details

You can get technical information about the API from :help NERDTreeAPI. Here you will find the documentation on the interface functions and some short usage examples. I spent ages writing that shit, so go check it out!


I see you've ignored my advice. You suck! However, in a rare show of generosity, I'll summarize it for you.

At the time of this writing the following public functions are defined in the NERD tree core:

NERDTreeAddKeyMap({options})
NERDTreeAddMenuItem({options})
NERDTreeAddSubmenu({options})
NERDTreeAddMenuSeparator([{options}])
NERDTreeRender()

The first 4 deal with extending the NERD tree key set and menu system, while the last redraws the tree buffer (useful if you have changed the tree somehow and want to reflect that in the UI).

Additionally, the following public classes are available:

NERDTreePath
NERDTreeDirNode
NERDTreeFileNode
NERDTreeBookmark

These are what the NERD tree core uses to get most of its biznass done. I wont say any more about them other than check out the source code, and check out this blog post to see the coding conventions used and for a rundown of prototype OO in Vim.

Example 1: A key mapping to open a :shell

In this example we add a key mapping on 'S' to the NERD tree that launches the :shell command in the directory of the currently selected node.


Even though I commented the living shit out of the code, it's probably worth mentioning the three points in this code where we call the NERD tree API:
  • Lines 8–11. Here we set up the NERD tree key binding so that when the user hits 'S', the NERDTreeStartShell() function is invoked. The quickhelptext value is what appears in the quick help (i.e. when you hit '?') under the "Custom mappings" section.
  • Line 18. Here we call GetSelected() (a class method of NERDTreeDirNode). This gives us a NERDTreeDirNode instance representing the directory node the cursor is sitting on.
  • Line 26. Here we call n.path.str(...) which gives us a string representation of the NERDTreePath object for the node in question, suitable for use with a :cd command. There are a number of formats and options the str() method can take. Check out the method comments in NERD_tree.vim for details.

Example 2: A menu item to open images

In this example we add a menu item to view images with eog. We could easily extend this to support some default image viewers for MF Windows™ and Mac OSX, but for simplicity, that has been left out.



Here is an image of the above code in action (after hitting 'm' on an image node):

The code is responsible for the last 2 lines of the menu. Some highlights:
  • Lines 13 and 14 add the menu separator (the line of dashes).
  • Lines 17–21 add the (v)iew image menu item.
  • Lines 14 and 20 ensure that the menu items only appear when the cursor is over an image node.
  • Line 21 connects the menu item to the NERDTreeViewImageMenuItem() function which shells out to eog to open the image.

Final ravings

We've seen a couple of basic examples of NERD tree plugins that show how to add additional key mappings and menu items. I've written many more such plugins, which have mostly been for the purposes of integrating the tree with external programs (e.g. git and grep), or with other vim plugins (eg UTL). I've also written plugins that add slightly modified versions of existing key mappings, or even override the existing mappings.

One day I may stop watching pr0n long enough to clean up and post some more complex examples. Until then, try to behave yourselves, and flick me an email if you write any dynamite NERD tree plugins!

Monday, June 28, 2010

Hacking line numbers into embedded gists

Github has the only corporate mascot in existence that I fantasize about touching inappropriately.




When github unveiled their gist service in 2008, I went into my room, jumped up on my bed, ripped all the playboy posters off the ceiling and taped up a giant portrait of the octocat.

But HOT DAYYUMN is github's lack of line numbers on their embedded gists pissing me off! I've been trying to write another raving containing a reasonable amount of code that is explained over the course of the post — pretty fucking hard without line numbers!

So I went and wrote some javascript hacks to add line numbers in for me.

The hacks

I originally tried to do it with prototype, but was having so much trouble getting it to work on IE6 that I decided to try out jquery instead. Cunting fuck I hate fucking Internet Explorer 6! Ive lost count of the number of rape fantasies I've had about Bill Gates! Anyway, check out these hacks below — maximum credit goes to gaving for refactoring them into not sucking.



Notice those line numbers? ZOMG!


How to use said hacks

Its easy, check out this example:

Its worth noting that the url for the "line number hackz0r script" is from the "view raw" link of the previous gist. If you remove the SHA1 from the url, it seems it always grabs the latest revision of the gist.

Saturday, May 8, 2010

How csplit turned my software into hardware

I'm typing this text with my penis.

This is made possible largely due to the erection inducing side-effects of csplit — a program I'd never used until today.

Story time!

Once upon a time in a far distant land, there was a handsome, charming, young prince who had never known true love... Meanwhile, somewhere else, I was sitting at my desk, scratching my head, wondering how the cunting fuck I was going to extract the tiny part of this 1.8GB database dump that I needed. The dump was generated with something like
mysqldump --all-databases > all_databases.sql
giving me a file with a metric fuck-load of sql to create databases, and insert data into them — from which I needed one particular database.

Of course I tried to edit it with Vim first (before realizing how large it was) and had to kill it before it started eating into my swap. Gedit gave me similar results, and Emacs just told me to fuck off. However, a quick trip to google gave me the answer: csplit! Following which my four foot blackzilla punched a hole through the front of my jeans and stabbed me in the eye.

Anyway, I went over to my dump file and grepped the bastard to find out the order that the "CREATE DATABASE" statements appeared in and then snipped out the one I wanted with these hacks (where foo_database is the database I wanted to extract, and bar_database is the next one in the file):
csplit all_databases.sql '/CREATE DATABASE.*foo_database/' '/CREATE DATABASE.*bar_database/'
This outputted three files (xx00, xx01, xx02):
  • xx00 containing everything up to the first match of /CREATE DATABASE.*foo_database/ (a regex)
  • xx01 containing everything between the two regexes (including the line matching the first regex)
  • xx02 containing everything after the second regex (/CREATE DATABASE.*bar_database/)
This put the code that I wanted into xx01. Very handy!

A related tool that could also have been useful is plain split. For example

split --bytes=10000000 a_large_file
would split a file up into 10MB chunks.

Saturday, December 19, 2009

Hacking IE6 With Sass Mixins

Just recently I was raging against Internet Explorer 6 and the hacks that are required to overcome its shitty css support when it occurred to me that Sass mixins could be used to abstract away some of these hacks.

Read this raving if you use sass and rage against having to support IE6.

Bill Gates is way more awesome than Hampton Catlin (at sucking)


Good morning class, let us begin today's lesson with some quotes.

Now, I ain't gay, but let it be known that Sass is so fucking awesome that I'd definitely suck Hampton Catlin's cock. For free!
Scrooloose - 12th Dec, 2009

Many of you may be offended by the above homo-erotic sentiments and view them as inappropriate, but let me ask you: if you call those sentiments "inappropriate" then what, pray tell, the fuck would you call these:

I love Bill Gates like I love decapitated parrot heads sprinkled on cornflakes with milk and sugar. If I met him on the street I'd kidnap him and drag him back to my secret torture lab, where I would inject a delightful cocktail of fire ants, piranhas, and ninja stars into his anus. Then, I'd don my strap-on cactus and proceed to stir said cocktail with extreme force. Following this, I would feed him — cock first — to the cult of homosexual-rapist-cannibals that I harbor in my basement.

Whoa! Hold on there, thats pretty brutal! Maybe I took that last part a bit too far?? OH WAIT NO I DIDN'T, FUCK YOU BILL!
Queen Elizabeth II (after failing to get her site running in IE)

I hold Bill personally responsible for the travesty of Internet Explorer 6. Not the browser itself mind you, but the fact that it is still widely used today, even though I was still in fucking high school when it was released!*

Having to support such a buggy and incomplete css implementation is enough to make any web developer shit his pants in protest.

Sass mixins to the rescue

I only looked into these the other day, and I wish I'd done it ages ago. Mixins are basically a way to reuse chunks of css.

Check out this example:


Here we create a mixin called "ultimate-hippy-border" which takes a "thickness" parameter. When the css file is compiled, the declarations inside the mixin are evaluated and inlined into the css rules that the mixin is used in.

Check out these links for more info about mixins.

You can see how we could use this to hide css hacks. Check out these examples:



There are several benefits to doing this.

The most obvious is that we no longer have these ugly-as-fuck hacks repeated all over our code. Instead, we are left with much more symbolic mixin code. The intent of +min_height_hack(10px) is much clearer than the 3 line hack we would otherwise inline. This makes things more concise, readable and DRY, which results in some erection-inducing maintainability.

I can haz a repo on github?

I've created a repo on github with the hacks that ive been using so far which, at the time of this writing, is nothing more that what's in the gist above. Not impressed? Here, check out this ballsack:

How you like me now?

If you're still not satisfied, then you'll have to fork me and add your own hacks.


* if you are one of the people that still uses IE6 and you are not clinically dead then please correct this situation immediately. Thank you.

Tuesday, October 20, 2009

Mainframe molestation with looksee

This morning when I walked into the server room, I must have looked real serious, because our mainframe took one look at me and ran for its fucking life! I took off after it, bolting across the office and down the back steps before I caught up with the bastard in the car park, trying to steal a scooter off some school kid. I slapped that bitch down, lifted its rear end up into the air, plugged my keyboard in from behind and started hacking.

I only had time for a quicky, and here's the result (from my .irbrc):



These hacks are built on this dynamite gem called looksee that gives you a function similar to the various methods functions that exist in the ruby core, except the output contains more information and is designed for human readability. Compare these 2 screenshots:

Without looksee


With looksee, and my hacks



I practically blew a load in my pants when I saw the output from looksee, since I've frequently been frustrated by the output of methods. However, the standard usage of looksee is

lp someobject, :some => 'options'

and I don't really want to memorize another function call.

Enter the above code, which intercepts calls to methods. If the call is made directly from irb, it is forwarded on to looksee, otherwise the original methods is called. This is handy as fuck when using irb for debugging and what not, but wont screw with code that uses the standard methods function.

Related stuff

http://www.rubypulse.com/episode-0.12_looksee.html - a screencast demonstrating looksee (where I first heard about it)

Sunday, September 27, 2009

Vim pr0n: ignorecase fails

Fuck The Machine, lately the only thing I've been raging against is the ignorecase option.

In practice, the only use for ignorecase is to make vims regular expressions case insensitive when searching. However, for some reason, it also affects the == operator. Check this shit out:


:set noignorecase
:echo "foo" == "FOO"
0
:set ignorecase
:echo "foo" == "FOO"
1


What the fuck!? Good job team, you just made == ambiguous, and therefore completely useless.

This means script writers can't use == unless they explicity set the ignorecase option first, otherwise they don't know how their code will behave. Since that would be retarded, we should all stop using == and start using ==# or ==?, which is exactly what I've done.

But wait! Theres more! ignorecase also changes the behaviour of these comparison operators too:
!=
>
>=
<
<=
=~
!~

Who the fuck made this decision?! I have no idea, but Id like 5 minutes alone with that bitch so I could stab them in the face! Multiple times! WITH MY FUCKING RECTUM.

Just ask yourself: if you download someones vim script, is it really in your best interests to change how every single comparison operator in that script functions?

In my massively non-humble opinion, ignorecase should not affect any of the basic comparison operators, only specializations of those operators.

</rage>

Monday, July 6, 2009

Vim pr0n: Combating long lines

The other day my boss found me locked in the server room, naked and bathing myself with dish washing liquid and toilet water. When he asked what in the flying fuck I was playing at, I told him my soul was filthy and corrupt from all the long lines I'd been committing. In reply he told me I'd better sack up and write some vimscript hacks to keep my long lines under control. So that's what I did. Later that afternoon I was so happy I proposed to my boss and we lived happily ever after.

Read this raving if long lines bug you like a colony of fire ants assaulting your prostate.

Note: this raving assumes a fair amount of knowledge about statuslines in vim. If you aren't pro at statuslines then you should read this raving first.

Reporting long lines on the statusline

I've found it quite useful to have flags on my statusline that appear when a buffer is in an undesirable state; e.g. if the file format or encoding is wrong, or there are syntax errors, or mixed indenting etc. Ive recently coded a warning for long lines into my statusline. Check out this screenshot:



Notice the [#141,m82,$162] on the statusline. This is telling us that the buffer has 141 long lines, where the median length of these lines is 82 chars and the longest is 162 chars. This notice only appears when there is at least one line that is longer than &textwidth (typically 80).

That may seem like an excessive amount of information, but when I first coded a statusline warning, I only included the length of the longest line. This turned out to be insufficient since its common for a file to have one or two crazy long lines that are acceptable or troublesome to avoid. I could have only shown the number of long lines, but then I'd be left wondering how long they were; hence the median and longest line stats. Besides, more stats means more code behind my statusline, which makes it more likely the mother fucker will become sentient and hunt down Jamis Buck.

Here's the code from my vimrc:

 1 "....
 2 set statusline+=%{StatuslineLongLineWarning()}
 3 "....
 4
 5 "recalculate the long line warning when idle and after saving
 6 autocmd cursorhold,bufwritepost * unlet! b:statusline_long_line_warning
 7
 8 "return a warning for "long lines" where "long" is either &textwidth or 80 (if
 9 "no &textwidth is set)
10 "
11 "return '' if no long lines
12 "return '[#x,my,$z] if long lines are found, were x is the number of long
13 "lines, y is the median length of the long lines and z is the length of the
14 "longest line
15 function! StatuslineLongLineWarning()
16     if !exists("b:statusline_long_line_warning")
17         let long_line_lens = s:LongLines()
18
19         if len(long_line_lens) > 0
20             let b:statusline_long_line_warning = "[" .
21                         \ '#' . len(long_line_lens) . "," .
22                         \ 'm' . s:Median(long_line_lens) . "," .
23                         \ '$' . max(long_line_lens) . "]"
24         else
25             let b:statusline_long_line_warning = ""
26         endif
27     endif
28     return b:statusline_long_line_warning
29 endfunction
30
31 "return a list containing the lengths of the long lines in this buffer
32 function! s:LongLines()
33     let threshold = (&tw ? &tw : 80)
34     let spaces = repeat(" ", &ts)
35
36     let long_line_lens = []
37
38     let i = 1
39     while i <= line("$")
40         let len = strlen(substitute(getline(i), '\t', spaces, 'g'))
41         if len > threshold
42             call add(long_line_lens, len)
43         endif
44         let i += 1
45     endwhile
46
47     return long_line_lens
48 endfunction
49
50 "find the median of the given array of numbers
51 function! s:Median(nums)
52     let nums = sort(a:nums)
53     let l = len(nums)
54
55     if l % 2 == 1
56         let i = (l-1) / 2
57         return nums[i]
58     else
59         return (nums[l/2] + nums[(l/2)-1]) / 2
60     endif
61 endfunction


Crikey dick that's a lot of code! Lets run through it.

The StatuslineLongLineWarning() function constructs and caches the flag that will appear on the statusline. The flag will be an empty string if there aren't any long lines.

The hard work is actually delegated off to the LongLines() and Median() functions. LongLines() examines every line in the buffer and returns an array containing the lengths of the long lines, where "long" is determined by the users &textwidth setting (defaulting to 80 if &textwidth is set to 0). Note that LongLines() converts tabs into spaces according to the users &tabstop setting. Median() calculates the median of a given array of numbers.

Line 2 puts the flag onto the statusline and should appear with the rest of your statusline setup code.

Line 6 clears the cached flag every time the user is idle or saves the file, thus causing the flag to be recalculated.

Highlighting the offending parts of long lines

 1 "define :HighlightLongLines command to highlight the offending parts of
 2 "lines that are longer than the specified length (defaulting to 80)
 3 command! -nargs=? HighlightLongLines call s:HighlightLongLines('<args>')
 4 function! s:HighlightLongLines(width)
 5     let targetWidth = a:width != '' ? a:width : 79
 6     if targetWidth > 0
 7         exec 'match Todo /\%>' . (targetWidth) . 'v/'
 8     else
 9         echomsg "Usage: HighlightLongLines [natural number]"
10     endif
11 endfunction


I stole line 7 above from this vim tip and wrapped it up in a the HighlightLongLines command above. When invoked, the command highlights the "long" parts of long lines. Ive found this command pretty handy when embarking on anti long line crusades.

I'd highly recommend reading that vim tip for more code to highlight long lines. Theres some pretty dynamite stuff there.

Conclusion

Long lines suck, here's what Abe had to say about the matter:

Peppering your code with long lines is highly recommended; right up there with "strolling into church with an entourage of scantly clad, chronically obese prostitutes" and "licking the testicles of senile old men who are not fully in control of their bladders".

Abraham Lincoln, 1862


Inspirational.

Use the relatively passive vim script hacks above to make vim bitch at you and steer you away from using long lines. If you want a more aggressive solution, then check out the aforementioned vim tip.

Sunday, June 21, 2009

Vim pr0n: Syntax checking on the go

A couple of days ago I was in the office, hacking the mainframe with The Great Halorgium. We got to talking about our current vim setup when he told me that it would be awesome if the statusline displayed a warning flag for buffers with syntax errors.

By the end of the day we'd written a couple of ftplugins to do just that for ruby and eruby. Read this raving to find out how.

Note: although we have only done it for ruby and eruby (at the time of this writing), you could easily do the same for other syntaxes using the same technique, provided there is a command line syntax checker for that language.

Note: this raving assumes a fair amount of knowledge about statuslines in vim. If you aren't pro at statuslines then you should read this raving first.

The end result


Here is a screenshot showing the code in action:


Notice the [syntax:4] on the statusline. After this buffer was saved, our code ran it through a syntax checker which told us there was a syntax error on line 4 ZOMG! (actually its a missing bracket on line 3).

The code


Here is the code to accomplish this for the ruby filetype. It was pulled from my ~/.vim/ftplugin/ruby_stl_syntax_warning.vim.

Update (8/july/09): I've recently refactored the living shit out of this code, which has made it much simpler, and has removed much of the duplication between the syntax checkers. See my vimfiles repo for the latest hacks. Look in my vimrc (search for "syntax") and in the syntax_checkers directory.

Update (25/july/09): OK, I went completely insane and made it into a plugin with some more features, check it out here http://github.com/scrooloose/syntastic

 1 if exists("b:did_ruby_stl_syntax_warning_ftplugin") || &filetype !~ '\<ruby\>'
 2     finish
 3 endif
 4 let b:did_ruby_stl_syntax_warning_ftplugin = 1
 5
 6 "bail if the user doesnt have ruby installed
 7 if !executable("ruby")
 8     finish
 9 endif
10
11 "inject the syntax warning into the statusline
12 let &l:statusline = substitute(&statusline, '\(%=\)',
13             \ '%#warningmsg#%{StatuslineRubySyntaxWarning()}%*\1', '')
14
15 "recalculate after saving
16 autocmd bufwritepost <buffer> unlet! b:statusline_ruby_syntax_warning
17
18 "run the buffer through ruby -c
19 "
20 "return '' if no syntax errors detected
21 "return '[syntax:xxx]' if errors are detected, where xxx is the line num of
22 "the first error
23 function! StatuslineRubySyntaxWarning()
24     if !exists("b:statusline_ruby_syntax_warning")
25         let b:statusline_ruby_syntax_warning = ''
26         if filereadable(expand("%"))
27             let output = system("ruby -c " . expand("%"))
28             if v:shell_error != 0
29                 let b:statusline_ruby_syntax_warning =
30                             \ '[syntax:'. s:ExtractErrorLine(output) . ']'
31             endif
32         endif
33     endif
34     return b:statusline_ruby_syntax_warning
35 endfunction
36
37 "extract the line num of the first syntax error for the given output
38 "from 'ruby -c'
39 function! s:ExtractErrorLine(error_msg)
40     return substitute(a:error_msg, '.\{-}:\(\d*\): syntax error,.*', '\1', '')
41 endfunction


Wow! Well I have a boner, how about you?

Lets dissect this:

Lines 1–4 contain the standard house keeping code to make sure we don't source the plugin more than once. The filetype check is needed since the eruby runtime I use sources some of the ruby runtime files, including this one.

Lines 6–9 ensure that the ruby binary is present, since we are going to use ruby -c to check the syntax.

Lines 12–13 inject the syntax warning into our statusline. We chose to put it just before the left/right alignment separator since we put buffer related info on the left and cursor related info on the right. If you don't have %= on your statusline then you'll have to put it somewhere else.

Lines 23–41 are where the party is at. The StatuslineRubySyntaxWarning() function works out what should be displayed on the statusline and caches the result in b:statusline_ruby_syntax_warning. The code shells out to ruby -c to check the syntax of the buffer, before parsing any resulting error messages and returning the statusline flag containing the line number of the first error.

Line 16 clears the cached flag every time the buffer is saved, causing the syntax to be rechecked.

The future


There are a few other filetypes that I may write syntax checkers for, like sass and haml. Php could be useful too. And bash. Fuck, a bash syntax checker could actually be really handy. Getting that horrid shit right is about as easy as jacking off while watching a bunch of kitties getting nailed to a post. Things like apache configs could be good too, instead of doing apache2 -t manually.

Ive also been thinking about using the :sign commands to flag syntax errors. This way we could put a symbol next to each line containing a syntax error.

Tuesday, February 3, 2009

Vim pr0n: Jamis Buck must die

Sometimes I see something online that makes me rage so hard I long for a nail gun and a sack of adorably cute kittens. Lately I've been seeing assloads of vimrc files with this in them:

map <leader>d :execute 'NERDTreeToggle ' . getcwd()<CR>

Awww, isn't that cute? BUT ITS WRONG!!!1

It all comes from this blog post. OMFG Jamis Buck, I will find you, and I will fuck you. Then I'm gonna shove my entire $12 keyboard into your anus and turn it sideways before I squash you into a fetal ball and use copious amounts of superglue to bind your hands to your ass, and your scrotum to your tonsils. Then I'll bowl you down a hill into a set of garbage cans and put the video on youtube.

The :NERDTreeToggle command defaults to the current working directory anyway. So, if you have the above line in your vimrc, delete it immediately and replace it with this:

nnoremap <leader>d :NERDTreeToggle<cr>

DO IT!

Tuesday, December 16, 2008

Got Kombat?

Once upon a time me and my cousins were milling about the backyard eating grass and sniffing each other crotches when, for some reason, we started taking photos.

As usual, we eventually sought out props to photograph with. As usual, we ended up getting one of my huge fuck off knives, then a mattock, then a sword, and finally a chainsaw.

Afterward, I chose my 4 favourite shots and brought out the gimp (no, not that gimp, this gimp!). Then I wrote an incredibly sensitive and heart warming childrens story for each one.

Enjoy.

Weigh in and pre-match psych out


omg click to enlarge bitch



So my auntie came up to me and my 2 little cousins and was like "YO, one of y'all do the dishes!", and immediately me and my older little cousin put our thumbs to our foreheads.

My younger little cousin hates doing the dishes. In fact, he would rather die. Consequently, his face turned red as he bared his teeth and pulled out his knife.

His words blasted off his furiously flapping tongue, "You bitches think you can tell me what to do?!?! Huh?! Fuck that shit! Let mortal kombat begin!"

And so it began ....


Round one


omg click to enlarge bitch



Always eager to butcher my little cousin, I ran to the shed and searched for the most brutal looking garden implement I could find. The giant orange mattock in the corner looked brutal enough to castrate a dinosaur. Perfect.

We met each other in the yard. Looking him in the eye, I gave him one chance to back out, "You think you can come up here and take a piece of this? Huh? Ill tell you something. You're gonna die."

In reply he gave me detailed instructions on exactly how I should go about copulating with a pencil sharpener. It didn't sound pleasant. I took that as a "yes" and charged.

I came in hard and high, hoping to cleave his skull with one good blow and splatter his brains on the ground for my dog. At the last fraction of a second, he darted sideways, puncturing my side with several jackhammer-like stabs before jumping back.

He'd hit me! Unbelievable! Looking him in the eye, I cursed with language so colourful you'd swear we were back in the 70's.

He snorted like a horse and ran at me with intense blood lust. But I was ready. I slapped that bitch down so hard there were tears in his eyes. Then the fight began in earnest...

It raged....

and raged...

Until finally, dazed, I stumbled around in a barely conscious stupor.

Like lightening, his knife flashed as he sliced my eyeballs right out of their sockets. But before I could let loose a single curse, the knife flashed again and then he was stuffing my eye sockets with my own severed testicles.... FATALITY.


Round two


omg click to enlarge bitch



If you thought that watching me getting slaughtered would force my older younger cousin (Commando) to yield to my younger younger cousin (Killalot) then you have clearly underestimated how much we hate doing dishes.

Commando went in search of some elite weaponry and returned with a samurai sword. Seeing this, Killalot decided to upgrade his own kill gear. He went to his room, rummaged around under his bed and came back with his favourite chainsaw.

Seeking the psychological high ground, Commando taunted: "When im done mutilating your corpse, im gonna kidnap your cat and rape the shit outta him every night for the rest of his life." Killalot replied matter-of-factly, "Go ahead, he likes it rough."

Taken aback by this, Commando tried some more conventional material. He launched into a detailed exposition of exactly how he would use his sword to extract Sir Killalot's beating heart out of his body via his anus. He thought that the whole "ill rip your heart out and show it to you" angle would have Killalot wetting himself, but the details bored Killalot and he stopped listening after a couple of sentences.

Commando tried one last time, "Bitch! Im gonna mutilate your genitals, stir fry them, and feed them to---", but before he could finish, Killalot raised his chainsaw, snorted with more vigour than 10 wild stallions and charged.

To be concluded ...

Round two point five


omg click to enlarge bitch



The kombat began.

It was brutal. Really brutal. In fact, the brutality cannot be adequately described without resorting to alliterative testicle metaphors. It was ball breaking, sack splitting, gonad grinding, testy tearing, scrotum shattering, nad napalmingly brutal.

Commando's sword slashed. Deadly and swift with maximal finesse. Making razor cuts here and there but never striking a fatal blow.

Killalot, on the other hand, took the opposite approach. He flung his chainsaw around and around, roaring and biting, as though it were some psychotically fucked off lion he'd grabbed by the tail.

Their weapons crashed, bashed and smashed like the four drum kits of the apocalypse. Their snorting would have put rhinos to shame. Their facial expressions would have set churches on fire. Their foul cursing would have caused nuclear weapons to spontaneously detonate.

Eventually Sir Killalot won out and finished Commando off with The Voltron Maneuver, cutting him in half right down the middle.


Game Over.
Insert Coin.

....
Epilogue:


So me and my cousin were dead. But not for long. On account of our exceptional deeds, the Almighty saw fit to resurrect us into the afterlife immediately.

After we got settled in to hell, my other cousin employed the services of The Transdimensional Courier Agency to deliver the dishes down to us. We cleaned them and sent them back.

Wednesday, November 26, 2008

select count(*) as omg_wtf from postgres;

This morning I discovered something that made me want to jump up on my desk and drop the f-bomb in my office with heart and soul. It was as though I'd just been sucker punched by a circus midget then fisted by his exceptionally well trained elephant as I doubled over in pain.

Let me tell you a story.

Once upon a time this morning, I was trying to figure out why the fuck one of our servers had gone postal and exploded, leaving behind a stinking cloud of piss mist and gaseous fecal matter yet again.

Trawling through the logs of one of the web apps on the machine, I found a bunch of requests that had each taken 15 seconds to complete. After some investigation, I found that these requests were all doing a "select count(*) ..." from a table with millions of rows. OMG. So I fired up a postgres client and did an explain for the same query, and it told me it was doing a sequential fucking scan to find the count!

I googled intensely, and what I found made my jaw drop and my tongue roll out like a red carpet: There is no way to optimize count operations in postgresql. Read here for a brief explanation.

OMG thanks postgres! Mind if I rape you?!

Solutions

There are a bunch of work arounds you can find on google, but they all boil down to 2 approaches: cache the count, or guess the count.

So.....

Triggers anyone?!

 1 -- Create foos table
 2 CREATE TABLE foos (
 3   id   SERIAL PRIMARY KEY,
 4   name VARCHAR(255)
 5 );
 6
 7 -- Create table foos_count to hold a single row that contains the number of
 8 -- rows in the foos table
 9 CREATE TABLE foos_count (
10   counter  INTEGER
11 );
12 insert into foos_count values(0);
13
14 -- Increment count function
15 CREATE FUNCTION inc_foo_count() RETURNS trigger AS '
16 BEGIN
17 UPDATE foos_count SET counter = counter + 1;
18 RETURN NEW;
19 END;
20 ' LANGUAGE plpgsql;
21
22 -- add a trigger to increment foos_count.counter when inserting into foos
23 CREATE TRIGGER inc_foo_counter AFTER INSERT ON foos
24   EXECUTE PROCEDURE inc_foo_count();
25
26 -- Decrement count function
27 CREATE FUNCTION dec_foo_count() RETURNS trigger AS '
28 BEGIN
29 UPDATE foos_count SET counter = counter - 1;
30 RETURN NEW;
31 END;
32 ' LANGUAGE plpgsql;
33
34 -- add a trigger to decrement foos_count.counter when inserting into foos
35 CREATE TRIGGER dec_foo_counter AFTER DELETE ON foos
36   EXECUTE PROCEDURE dec_foo_count();

Oh yeah. Nothing like a good trigger to make you feel like you just got probed by a bunch of aliens with a fetish for egg beaters.


How about rules?

 1 -- Create foos table
 2 CREATE TABLE foos (
 3   id   SERIAL PRIMARY KEY,
 4   name VARCHAR(255)
 5 );
 6
 7 -- Create foos_count to hold a single row that contains the number of rows in
 8 -- the foos table
 9 CREATE TABLE foos_count (
10   counter  INTEGER
11 );
12 insert into foos_count values(0);
13
14 -- add a rule to increment foos_count.counter when inserting into foos
15 CREATE RULE inc_foo_count AS ON INSERT TO foos DO ALSO
16     UPDATE foos_count set counter = counter + 1;
17
18 -- add a rule to decrement foos_count.counter when inserting into foos
19 CREATE RULE dec_foo_count AS ON DELETE TO foos DO ALSO
20     UPDATE foos_count set counter = counter - 1;

Rules don't look all that bad— certainly much nicer than triggers.


You could also obtain an estimate of the count with this:
SELECT reltuples FROM pg_class WHERE oid = 'foos'::regclass::oid;

This will give you the count at the time of the last ANALYSE.

My lists

Ok, so lets take a look at what impact this experience has had on my lists.

Postgres just jumped from my Christmas List over to my Shit List — fuck you postgres, I'm gonna find you, and I'm gonna take my knife, and I'm gonna use your cock for a sheath.

The List Of Things I Should Have Known By Now grew by 1 for select count sucking the scrote.

The List Of Things I Should Have Played With By Now also grew by 1 for rules since this is the first time I've actively investigated them.

Friday, October 31, 2008

Vim pr0n: Statusline flags for bundy whitespace

Lately I've been working on some projects with indenting so screwed you could print the source code out and wank with it and not be able to tell the difference. It's as though the author couldn't decide whether to use tabs or spaces, so they flipped a coin every time they began a new source file, and evidently the coin landed on its fucking edge more often than not since there are a fair number of files that use both tabs and spaces.

I've also developed an extreme anti-fetish for trailing whitespace recently. I made vim highlight it, and that shit is fucking everywhere!

ZOMG

So, in a bid to eradicate both mixed indenting and trailing whitespace from the universe, I've made vim display some flags on my statusline whenever they are present, and whenever my &expandtab setting is wrong. Read this raving to find out how.

Note: this raving assumes a fair amount of knowledge about statuslines in vim. If you aren't pro at statuslines then you should read this raving first.

Just so you know what I mean...


A buffer containing mixed indenting, and trailing whitespace (click to enlarge).


A buffer with &et set wrong, and trailing whitespace (click to enlarge).


The three statusline flags of interest in the above screenshots are:

  • [mixed-indenting]: Appears when a buffer is indented with both tabs and spaces

  • [&et]: Appears when a buffer is indented consistently (i.e. using only spaces or only tabs) but the &expandtab setting for the buffer is wrong.

  • [\s]: Appears when a buffer contains trailing whitespace


The code for the [mixed-indenting] and [&et] flags


This is snipped straight outta my vimrc:
 1 "display a warning if &et is wrong, or we have mixed-indenting
 2 set statusline+=%#error#
 3 set statusline+=%{StatuslineTabWarning()}
 4 set statusline+=%*
 5
 6 "recalculate the tab warning flag when idle and after writing
 7 autocmd cursorhold,bufwritepost * unlet! b:statusline_tab_warning
 8
 9 "return '[&et]' if &et is set wrong
10 "return '[mixed-indenting]' if spaces and tabs are used to indent
11 "return an empty string if everything is fine
12 function! StatuslineTabWarning()
13     if !exists("b:statusline_tab_warning")
14         let tabs = search('^\t', 'nw') != 0
15         let spaces = search('^ ', 'nw') != 0
16
17         if tabs && spaces
18             let b:statusline_tab_warning =  '[mixed-indenting]'
19         elseif (spaces && !&et) || (tabs && &et)
20             let b:statusline_tab_warning = '[&et]'
21         else
22             let b:statusline_tab_warning = ''
23         endif
24     endif
25     return b:statusline_tab_warning
26 endfunction

There are three parts to this code. The function (lines 12–26) works out what should be displayed on the statusline and caches the result. An autocommand on line 7 clears this cache when the user is idle or saves the file. Lines 2–4 put the flag on the statusline.

Note that the caching is needed as the function is called every time the statusline is refreshed. Without caching this would be very costly since the function searches the entire buffer for a leading space and a leading tab.

The code for the [\s] flag


Also straight from my vimrc, this code functions very similarly to the previous code. Lines 8–17 calculate and cache what should be displayed on the statusline. Line 4 clears this cache when the user is idle, or saves the file. Line 1 puts the flag on the statusline.
 1 set statusline+=%{StatuslineTrailingSpaceWarning()}
 2
 3 "recalculate the trailing whitespace warning when idle, and after saving
 4 autocmd cursorhold,bufwritepost * unlet! b:statusline_trailing_space_warning
 5
 6 "return '[\s]' if trailing white space is detected
 7 "return '' otherwise
 8 function! StatuslineTrailingSpaceWarning()
 9     if !exists("b:statusline_trailing_space_warning")
10         if search('\s\+$', 'nw') != 0
11             let b:statusline_trailing_space_warning = '[\s]'
12         else
13             let b:statusline_trailing_space_warning = ''
14         endif
15     endif
16     return b:statusline_trailing_space_warning
17 endfunction

An aside: use the list and listchars settings!


I have these lines in my vimrc:

set list
set listchars=tab:▷⋅,trail:⋅,nbsp:⋅

This tells vim to display tab characters as little arrow things and trailing spaces as floating dots (as in the two screenshots at the top of this raving). Having tabs displayed is invaluable as it becomes obvious how a file is indented, and if you aren't following suit.

Join in the fight against bundy whitespace today!


I was eavesdropping on two catholic priests yesterday* when I overheard one of them talking about people who mix tabs and spaces, saying: "... I know for a fact that they will spend their eternities in hell licking flaming shit nuggets out of satans ass crack while he jacks off furiously, periodically ejaculating streams of molten lava in their faces!"

On the other hand, studies show that people who indent code responsibly are far more likely to have sex with famous actresses than those who don't.

So what are you waiting for? Take every precaution to ensure you indent correctly! And fuck trailing whitespace!


* may not be true.

Monday, October 27, 2008

Vim pr0n: conditional statusline highlighting

I have a fair amount of info on my statusline, and have often thought it would be nice if certain parts of it could be highlighted under certain conditions. For example, I have &fileencoding displayed, but I only really care about it if its not "utf-8". In that case I would like it to be highlighted using the "error" highlight group so that I'll be sure to notice it.

If you too have jacked off far into the night imagining how much fun you could have with conditionally highlighted statusline flags, then take off your pants, point the pork sword in a safe direction and read this raving immediately.

Note: this raving assumes a fair amount of knowledge about statuslines in vim. If you aren't pro at statuslines then you should read this raving first.

The desired result



In the bottom image, the statusline was set up to display &fileformat and &fileencoding using the "error" highlight if they were anything other than "unix" and "utf-8" respectively.

ZOMG how do you do it?!

Unfortunately there is no clean way to do it, but we can easily encapsulate the hacks in a couple of functions.

Here is the code that generated the statusline above:
 1 "Add the variable with the name a:varName to the statusline. Highlight it as
 2 "'error' unless its value is in a:goodValues (a comma separated string)
 3 function! AddStatuslineFlag(varName, goodValues)
 4   set statusline+=[
 5   set statusline+=%#error#
 6   exec "set statusline+=%{RenderStlFlag(".a:varName.",'".a:goodValues."',1)}"
 7   set statusline+=%*
 8   exec "set statusline+=%{RenderStlFlag(".a:varName.",'".a:goodValues."',0)}"
 9   set statusline+=]
10 endfunction
11
12 "returns a:value or ''
13 "
14 "a:goodValues is a comma separated string of values that shouldn't be
15 "highlighted with the error group
16 "
17 "a:error indicates whether the string that is returned will be highlighted as
18 "'error'
19 "
20 function! RenderStlFlag(value, goodValues, error)
21   let goodValues = split(a:goodValues, ',')
22   let good = index(goodValues, a:value) != -1
23   if (a:error && !good) || (!a:error && good)
24     return a:value
25   else
26     return ''
27   endif
28 endfunction
29
30 "statusline setup
31 set statusline=%t       "tail of the filename
32 call AddStatuslineFlag('&ff', 'unix')    "fileformat
33 call AddStatuslineFlag('&fenc', 'utf-8') "file encoding
34 set statusline+=%h      "help file flag
35 set statusline+=%m      "modified flag
36 set statusline+=%r      "read only flag
37 set statusline+=%y      "filetype
38 set statusline+=%{StatuslineCurrentHighlight()}
39 set statusline+=%=      "left/right separator
40 set statusline+=%c,     "cursor column
41 set statusline+=%l/%L   "cursor line/total lines
42 set statusline+=\ %P    "percent through file

This code does two things. First it defines two functions that implement conditionally highlighted statusline flags. Secondly, it sets up the statusline variable, making use of AddStatusLineFlag().

How does it work?

A function call like this:
call AddStatuslineFlag('&fenc', 'utf-8,latin1')

will cause the following to be added to the &statusline variable:
[%#error#%{RenderStlFlag(&fenc,'utf-8,latin1',1)}%*%{RenderStlFlag(&fenc,'utf-8,latin1',0)}]


If we break this down we have the following:

[
output a literal "[" char


%#error#
switch to the "error" highlight group


%{RenderStlFlag(&fenc,'utf-8,latin1',1)}
render &fenc only if it's not "utf-8" or "latin1".


%*
switch back to the normal statusline highlight group


%{RenderStlFlag(&fenc,'utf-8,latin1',0)}
render &fenc only if it is "utf-8" or "latin1".


]
output a literal "]" char.


The key thing is that &fenc will either be rendered inside the error highlight or (exclusive) just outside it.

Generalizing...

This exact code wont work for all cases, but we can derive some general guidelines.

If you want to highlight something (lets call it foobar) X different ways then:

  1. You must define a function to render foobar.

  2. You must call the function X times on your statusline, where each call must be highlighted one of the possible ways.

  3. The function must take an argument to specify which highlight group it is currently rendering for.

  4. At all times, all but one of the function calls must return an empty string, while the other call must return the value of foobar which will appear on the statusline.


Already solved in Vim 8

The problem of conditionally highlighting statusline flags has already been solved for Vim 8, as those of you who keep up with the various vim mailing lists will no doubt be aware of. If you havent heard, then check out this this sneak peek of the new feature.