Source Code Typography

When you run a blog such as this one you usually learn to live with writers block or you quit early. Or perhaps not “writers block” itself but just lack of good ideas for blog posts. My usual way of dealing with it is to go trawling the web for inspiration. When you stay cooped inside your own head for a while you sort of get into a self referential funk that might be hard to break out of unless you get some fresh perspectives and ideas from the outside. So I usually hit programming subs on Reddit, Hacker News and/or my RSS feeds to see if I can get excited about something enough to get a blog post of two out of it.

The side effect of such a fishing expedition is that you sometimes find blog posts that are exactly up your alley, but which tackle the subject so well that they leave precious little for you to add to. So then you are left with a choice of either linking to said block and saying “I agree with what that guy said” or blatantly plagiarizing it and hoping no one finds out. The other day I stumbled onto just that kind of article: one that I would love to have written.

The funny thing is that a lot of the ideas in that post were sort of in the back of my mind lately. I have been doing a lot of thinking about code readability, formatting rules and style guidelines for a lot of languages. I have been doing a lot of jumping around between PHP, Python and Ruby lately and I’ve been noticing how each of these languages approaches code style. Python for example strictly enforces proper indentation by making it part of the language syntax, coercing you to write code certain way. This of course doesn’t mean you can’t write atrocious python code, but it is generally harder to do than with say PHP.

The way code is presented definitely impacts it’s readability. I’m not just talking about the usual code guidelines such as using descriptive variable names and structuring your code the right way. I’m talking about purely aesthetic properties of code: consistent indentation style, short line length, alignment of elements in declarative blocks and etc.. go a long way in making the code easier to digest understand. This is the gist of the argument put forth in Dave Copeland’s recent Source Code Typography post: the way you indent and align your code matters.

For the lazy, let me re-use one of his examples: a snippet of a pretty common code you could find in a Ruby on Rails application:

1
2
3
def text_field_tag(name, value = nil, options = {})
  tag :input, { :type => "text", :name => name, :id => sanitize_to_id(name), :value => value }.update(options.stringify_keys)
end

This is fairly concise, albeit ugly code that scrolls off the page in most editors. Unless you have a decent sized screen you can’t actually look at the whole line without scrolling – and even then the length of it makes it impossible to figure out what is going on here at a glance. Dave argues that a very simple re-formatting can drastically increase the readability of the above code:

1
2
3
4
5
6
7
8
9
10
def text_field_tag(name, value = nil, options = {})
  tag :input,
      {
           :type  => "text",
           :name  => name,
           :id    => sanitize_to_id(name),
           :value => value
 
      }.update(options.stringify_keys)
end

I’m not going to re-iterate the entire post here – I recommend you just go and read it yourself. Dave makes some excellent points, especially with regards to the annoying leading comma convention that has become fashionable in the JavaScript community lately. What I want to do is add to his article by pointing out that there are tools you can use to make formatting code easier.

For example, to keep your code lines relatively short it is a good idea to set up your editor or IDE to highlight column 80 giving you a visual indication as to how wide your code ought to be. This provides a soft boundary that you can go over if needed. In Vim this can be done via a single line added to your .vimrc:

hilight ColorColumn guibg=lightyellow ctermbg=227

You can of course substitute lightyellow and 227 to your choice of colors – I picked these because light yellow goes well with my Solarized Light theme: it is visible, distinct but not too jarring:

Column 80

Column 80 Highlighted

Similarly, when you need to re-align some code (as in the example above) there exist two plugins that will do the job for you: Vim-Align and Vim-Tabular. The later is the newer, more feature rich plugin and there is an excellent Vimcast on it that you can watch here. Both essentially help you align blocks of code based on some sort of a token. They make a task that can be quite labor intensive (a lot of moving around and tabbing) into a two step process: select block to be aligned, then issue the alignment command such as:

" tabular.vim
:Tab /=>
 
" align.vim
:Align =>

In both cases alignment is usually done while respecting your tabs/spaces settings ensuring that things don’t completely break apart next time you re-tab your file (using g g = G).

How do you ensure that your code is optimized of maximum readability? Do you have any plugins or tricks for your favorite text editor you would like to share? Let us know in the comments.

Posted in programming | Tagged | Leave a comment

Status Line in Vim

If you are following the recent trends in the Vim community you have probably noted the ever growing popularity of Powerline. As the name suggests, it is a very powerful status line generation plugin, but I don’t think that’s why most people use it. I believe its popularity has a lot to do with how sexy it looks on the bottom of your screen.

To be honest, I was never that fond of that particular extension for a variety of reasons. One of my chief gripes with it is directly related to the way it looks. Powerline uses non-standard patched fonts in order to achieve that segmented look which is not something Vim supports natively. Without them the extension looses a lot if it’s sex-appeal and starts looking a bit plain. To configure it, you don’t just add entries to your .vimrc but instead you need to create a separate dot-folder where it’s settings files are kept. While this neatly separates the Powerline setup from general Vim settings it also adds maintenance headaches. I like to keep all my Vim related config files in a single directory under source control so you can imagine this is less than optimal.

Finally, I have never really felt like I would use any of it’s advanced features. Most of the power-line setups I see on screenshots and in screen-casts are very basic: mode indcation, file path, some file and cursor position info. All of that can be easily set up in just a few lines of VimL. Powerline on the other hand is a monstrous semi-framework that can let you do really frivolous and complex things. For example, it has support for hooking into your power management module by the way of python and displaying battery status in Vim. It can also pull weather notifications from the web and display them in your status line… Though why would you ever want that is beyond me.

It is really a nice an powerful plugin, but it doesn’t seem like something I would necessarily need. For years I have been pretty happy using a very simple status line with just the name of the file and some positioning info along side the excellent Obvious-Mode plugin. It covered most of my needs – my status line would be red in insert mode, gray/cyan in normal mode, depending on whether or not the file had any unsaved changes.

Lately however I decided that I could use more informative status line. I briefly flirted with the concept of using Powerline but since I’m a system nomad who drags his .vim folder wherever he goes that idea died pretty quickly. Instead I decided to create my own status line which displays the information that I care about in a Powerline-like way but without any fancy fonts.

The killer feature for me is that I wrote it. By that I mean that if something breaks or doesn’t work correctly can easily figure out why, and fix it. Power line is pretty big and has a lot of moving parts, whereas my status line is just a dozen lines of very basic VimL so if it breaks, I can easily handle it without loosing too much time.

The result looks like this:

vim-neatstatus

Vim-NeatStatus Plugin

The mode indicator on the left changes color depending on the mode: green in normal, red in insert and blue in replace mode. I also had it turn purple in visual mode but it was kinda buggy (always lagged one keystroke behind) so at the moment it doesn’t do that. I still use Obvious-Mode so this functionality isn’t strictly necessary, but I included it so that it could be used as a stand-alone plugin.

The black box next to mode indicator shows you the server name (which in my case is treated as session name). This may not be useful to everyone, but since I set up my Vim to save sessions on exit I actually like to see that information somewhere.

To the left of the file path I have file type (ie. what language vim thinks this file is written in), file format (important if you jump between systems as much as me) and encoding (as in utf8 or not). The last may not seem fairly relevant to you, but sometimes it does matter: especially if you are trying to parse files in a certain way, or if you create a script that doesn’t run properly because the non-vim text editor decided to insert a BOM in it for shits and giggles.

Next I have the buffer number (which is useful when you have a lot of buffers open) and cursor positioning info with the current line highlighted in pink to stand out and be easily readable. There is also one more bit that is not visible in the picture above: whenever you edit a file, a little pink notification appears in the right corner of your status bar to let you know that the file has unsaved changes. Once again this is a duplication of Obvious-Mode functionality but it can be useful if you decide to install it as a stand-alone.

The colors work both in the graphical Vim as well as in the console (though you may need one that supports 256 colors). I tested it in in Gvim, MacVim and using Gnome-Console as well as Cygwin MinTTY on Windows.

I made the entire thing available as a plugin that can be easily installed via Pathogen like this:

cd ~/.vim/bundle
git clone git://github.com/maciakl/vim-neatstatus.git

If you have your .vim under source control like me then do:

cd ~/.vim
git submodule add git://github.com/maciakl/vim-neatstatus.git bundle/vim-neatstatus
git submodule init
git submodule update

At the moment the colors are hard coded and the plugin is not very configurable as a whole, but that will likely change in the future. If something is broken or the colors look atrocious under some setups let me know and I will try fixing it.

Are you able to change the status line in your favorite text editor? If yes, what kind of information do you put there? Have you written your own status line or are you using a plugin written by someone else?

Posted in programming | Tagged | 2 Comments

Iron Man 3

Iron Man 3 is the first of the post-Avenger era Marvel movie. Joss Whedon’s epic super hero romp is a tough act to follow, both in terms of quality and box office success (which are not the same thing mind you). Before he helmed the big Marvel Universe cross-over the singular hero movies were all we got and we liked them. However, once the audiences got a taste of having Iron Man, Captain America, Thor and The Hulk in the same movie, one must wonder if they will still enjoy watching them adventure on their own. So the first post-Avengers film has to prove that a single hero story-line can still carry a movie.. And that it can do it without Joss Whedon’s writing and direction.

That’s not the only reason why Iron Man was a tough gig though. It also had a difficult task of reconciling the Iron Man continuity with the events that happened during the Avengers. Whedon didn’t really need to worry as much about reconciling all the plot threads from all the different movies because he was building something new and something bold and he could just pluck the heroes from their element and put them on a flying aircraft carrier. However, Iron Man 3 returns Tony Stark to his own established setting, with a cast of established characters (Pepper Pots, Happy Hogan, Col. Rhodes, etc..). It needs to tie the old with the new somehow, and this is especially difficult in terms of Iron Man mythos.

Iron Man 3

Iron Man 3

Thor is an alien space-god who fights frost giants and sorcerers with Clarktech magic so it is easy to hand-wave anything on his continuity. Captain is a displaced fish out of water character so anything that happens to him is essentially a blank slate – you can go anywhere with this hero right now and no one will probably make fuss about it. But Iron Man had two movies to establish his own setting. There is a thematic continuity and certain kind of feel to the Iron Man movies and you sort of must at least try to maintain that in order to make a successful sequel because that’s what people want to see. The problem is that in the last two movies Tony Stark fought relatively low powered (at least compared to Loki) rivals in power armors, and magic alien space gods were not even on his map. Going back to that place would be counter-productive.

I must say that Drew Pierce and Shane Black did an admirable job tying the two continuities into one by addressing the dissonance between them directly. Instead of ignoring the world changing events that happened in New York, they become a central point of Tony Stark’s character arc (yes, Tony has an arc in this film – this is new and definitely a welcome addition to the Iron Man franchise). After fighting alongside gods and monsters, the hero feels somewhat inadequate. Thor, Cap and Hulk all have super powers and can fight alien space monster with their bare hands if need be. Iron Man on the other hand is powerless without his armor, and Stark is all too keenly aware of that. Events of Avengers have shook him to the core, and he is still suffering night terrors and panic attacks triggered by memories of the giant wormhole in the sky. As if to compensate, he fills his house with ever more powerful variants of his armor and finding new ways to get the armor deployed and combat ready as fast as possible. Of course it is all for nothing, and he is soon stripped from his high-tech weapons and forced to overcome his insecurities fighting super-powered villains with nothing but the power of his intellect.

This is a solid character arc, and a solid foundation for a plot: something the previous two Iron Man movies didn’t really have. The second installment especially was rather aimless, directionless mess and the third movie is definitely an improvement over that.

A lot of people seem to be upset about the Mandarin bit, but lets face it: was anyone really expecting him to show up looking like Lo Pan from Big Trouble in Little China in this day and age? As much as comic book readers might be fond of the character, the truth is that the original character concept was somewhat racist. The updated movie version (a middle-eastern terrorist with oriental flair trappings) seems not only much more timely but also quite subversive. When Ben Kingsley showed up on the screen I couldn’t believe how calculated his character design was: this Mandarin was the sum of all post 9/11 fears made flesh. Part Bin-Laden, part Kim Jung Il, part super-villain mastermind he was the picture-perfect boogeyman that proponents of the war on terror have nightmares about.

Speaking of Mandarin, let’s talk about the big twist. If you haven’t seen the movie and don’t want to get spoiled I suggest you skip over the stuff in the gray box below.

Did I like the twist? Did you like it?

At first I didn’t really know how to feel about the non-Mandarin. The more I think about it, the more I like it. Perhaps it is because I was never that attached to Iron Man comics and I don’t really care about Mandarin as a villain. So tweaking his back-story and his powers in an amusing way didn’t really rub me the wrong way. At the same time as I was watching the movie, I felt that Kingsley’s version of Mandarin was just a little bit too on the nose. It was too calculated and cartoonish in all the wrong ways so it was a relief to find out he was a decoy – and a brilliant one at that. Not to mention the fact that Kingsley is wickedly funny as the washed up actor.

You also have to keep in mind that the last two Iron Man movies completely bastardized and ruined other prominent Iron Man villains so expecting this installment to do any different seemed silly. It looks like Joss Whedon is the only super-hero writer in Hollywood who can currently write fun, compelling and enduring villains and I did not expect that to change overnight.


The acting was pretty decent in this one: Kingsley was great, Downey was doing his thing as he always does, Gweneth Paltrow actually got to punch things… Though only after prolonged session of damsel in distress bondage. The kid was quite terrible, as all children in movies are but at least he was able to set up one of the funniest Downey lines in the movie.

Guy Pierce however was kinda annoying. I can’t really put my finger on it, but something about his performance bothered me. I didn’t necessarily hate him – when an actor can actually make you hate his villain then he is actually doing his job well (see Jack Gleeson, aka Joffrey Lanister – the most hated kid in America and Westeros right now). Pierce’s character just felt a bit boring. Granted it might just be that he was completely eclipsed and overshadowed by Kingsley and Downey in terms of the on-screen presence.

All in all, I think the movie was pretty solid. It might be one of the best installments in the Iron Man franchise so far – or at the very least, better than the second movie. It had a good character arc, some fun plot twists and pretty decent dialogue. Granted, it was not without flaws (movie children usually ruin shit pretty fiercely) and plot holes… For example: can someone explain to me why didn’t Tony open up his indestructible bunker that contained an army of remote operated Iron Man suits earlier? Like right away after crashing in the snow? Or when he got his suit powered up again? Because I can’t fucking figure it out.

Posted in movies | Tagged , | 6 Comments