Github Source Anchors

Friday, September 7th, 2012

Recently while viewing the documentation and source for Lo-Dash, I noticed an interesting Github feature which allows for linking to any line number within a source file, and highlighting the line when the page is loaded, via URL anchors.

Linking to line numbers in source files

To link to a specific line of code in a source file on Github, simply click on the line number, which updates the URL with an anchor to that particular line number, or manually append an anchor to the URL in the form #L<line-number>.

For example, here is a link to the EventRegistry in the Backbone.EventBroker.

Linking to blocks in source files

After discovering this interesting little feature, I tried out a few other things and found that a block of code can also be anchored to as well, allowing for the block to become highlighted when the page is loaded.

Creating an anchor to a code block is as simple as selecting a line and pressing CTRL+SHIFT while selecting another line. Alternately, the line numbers can be manually added in the hash by specifying start and end line numbers in the form #L<line-number-start>-<line-number-end>. For example, here is a link to the EventBroker.get method.

Considerations

Since source files are likely to change with each commit, it is important to be mindful of the potential side effect of linking to specific line numbers. This is necessary for the obvious reason that changes in source could result in links to line numbers which no longer correspond to the expected code.

That being said, the ability to link to a certain line in a source file is still a rather cool and useful feature, even if only used for sharing links quickly, or for linking to specific commits which are unlikely to change.

{ Comments are closed! }