Marius Schulz
Marius Schulz
Software Engineer

Sharing Line Highlights in GitHub Files

When you browse a repository on GitHub and open any text file, you can highlight single lines by clicking a line number on the left. Taking TypeScript's scanner.ts file as an example, a single-line highlight can look like this:

Highlight of a single line in a file on GitHub

You can also highlight multiple lines by pressing SHIFT and clicking on the last line number of the range you want to select:

Highlight of multiple lines in a file on GitHub

Your line selection will be reflected in the hash portion of the file URL, allowing you to share the URL to point somebody to your selection:

The problem with these URLs is that they're not persistent. File contents change over time, so the line numbers shift as well.

Take a look at this TypeScript issue, for example, in which the author linked to a file that had some lines highlighted. It was supposed to have a for loop on lines 272–279. When I followed the posted link at the time of writing this post, I saw the following line range, which is not the one the author intended to highlight:

Highlight of an unintended line range in a file on GitHub

Depending on when you read this post, you might see something else entirely. That's not helpful, and it gets even worse once a file has changed drastically.

Luckily, there's a way to work around this issue: GitHub listens for the y key any time you're looking at an open file. When you press y, you will be redirected to a URL that represents a permalink to the Git blob associated with that file.

The URL you're redirected to uniquely identifies that blob — and only that blob. It also doesn't change over time, which makes it suitable for sharing.

Here's the blob URL to the for loop mentioned above with correct highlighting:

Highlight of the intended line range in a file on GitHub

The next time you're about to highlight some lines in a text file on GitHub and share a link to them, remember to press y first to get a permalink!