Fetch-Line-Range is a plugin for Prism.js

It allows you to easily define a source code file and a line range to display, and it will automatically retrieve the file and display the specified range. For example, the highlighted block below is the first 5 lines of this plugins source, which was fetched locally, and displayed using the markup:

<pre data-fetch="../prism-line-range.js" data-range="1,5" class="language-js line-numbers"> results in:


    

Hey! What happened to line 5 as specified in the markup? Well, as also shown below, leading and trailing blank lines that end up in codechunks are stripped. This does not affect the line numbering.

This makes it much easier to do with Prism what many of us use it for: breaking down code files in to logical chunks for explanation. Fetch-Line-Range also requests each file only once, and uses cache to provide the information to the markup rather than making a request each time the file is used. This minimizes network requests. Fetch-Line-Range uses the fetch() method to make requests, and so can load external source files as long as the request destination is CORS enabled. Here is the rest of the plugins code:


    

The splitLines() function does the work of reading the data range and retrieving the codechunk from cache. Then it inserts it in to the proper place and highlights it. If you are using the line numbers plugin with Prism, it will appropriately adjust the data-start value so that your line numbers display properly.


    

lineRange() is where the magic happens. It grabs all the pre elements with a data-fetch property, creates a list of unique source files used, sends them to the init() function to be fetched and cached to be used by splitLines().


    

Here are the hooks to register with Prism as a plugin, and also the execution of the main function once Prism has loaded


    

Here is the CSS file used to center my codechunks, broken in two parts just for demonstrating a bit further:


    

The second chunk! Notice line 13 got skipped. That is because it is blank and was a leading line in the codechunk, so the Normalize Whitespace plugin baked in to the Prism.js source that this demo is using affected it.