Linking to Highlighted Lines of Code on GitHub

Highlighted lines of code on GitHub

GitHub, a Git repository web-based hosting service, is a great tool for source code management and version control. I use it for all of my web projects and even for management of files that are not necessarily website-related.

From time to time I like to share links to files in my GitHub repository. But instead of just sharing a vanilla URL, I like to share a link that takes someone to a specific part of the page with a specific part of code highlighted.

This is very simple to do. On any GitHub page, click on a line number to the left of the code. Notice the URL is now appended with the line number you selected (e.g.…/functions.php#L117). Visiting this link will take you to the exact line of highlighted code.

Highlight of one line of code

To link to multiple lines of highlighted code, select your first line of code and then CTRL+SHIFT click on the last line of code you want to highlight. Notice the URL is now appended with a range of line numbers (e.g.…/functions.php#L117-L148). Visiting this link will take you to the beginning of the highlighted block of code.

One thing to keep in mind is that these links are not anchored to the code but to the line numbers. That means if you make a change to the file’s code the links may no longer highlight the lines of code you had originally intended to highlight.

To link to the code, as opposed to line numbers, highlight the code you want to link to then click the “y” key. Notice the URL changes again (e.g.…/blob/deffc216c5ac5ed6807289ca1fe8cf6f773e2447/…/functions.php#L117-L148). You are now linking to lines of code stored in a unique version of the file’s history. So now, even if the file is altered in subsequent commits, your link will still point to the lines of code you originally intended to highlight.

There are lots of fantastic GitHub features like this. My second favorite feature is the File Finder, which you can open by hitting the “t” key. And don’t forget, you can always hit the “?” key on any GitHub page to open the Keyboard Shortcuts window. There’s also Owen Ou’s article “Ten Things You Didn’t Know Git And GitHub Could Do” which is a good starting point for learning about other GitHub tips and tricks.

What’s your favorite GitHub feature? Let me know in the comments below!

2 responses to “Linking to Highlighted Lines of Code on GitHub”

  1. GitHub rules! 🙂 Thanks for sharing the tip about ‘y’ and ‘t’. I didn’t know about those useful features!

  2. Lucas says:

    Nice. Might be worth adding that it’s cmd-shift-click on the end line number for mac, rather than ctrl-shift-click.

Leave a Reply

Your email address will not be published. Required fields are marked *