← til

Building emphasized code blocks in Jekyll

January 10, 2020
jekyll

Code blocks in these articles support emphasizing specific lines which helps to direct a reader's attention.

Here's an example from Deep dive into Minitest:

{% source ruby location="https://github.com/seattlerb/minitest/blob/1f2b1328f286967926a381d7a34e0eadead0722d/lib/minitest.rb#L52-L66" 
               cssclass=emphasized
               hl_lines="1 2 3 4 13 14 15" %}
def self.autorun
  at_exit {
    next if $! and not ($!.kind_of? SystemExit and $!.success?)

    exit_code = nil

    at_exit {
      @@after_run.reverse_each(&:call)
      exit exit_code || false
    }

    exit_code = Minitest.run ARGV
  } unless @@installed_at_exit
  @@installed_at_exit = true
end
{% endsource %}

Which renders:

def self.autorun
  at_exit {
    next if $! and not ($!.kind_of? SystemExit and $!.success?)

    exit_code = nil

    at_exit {
      @@after_run.reverse_each(&:call)
      exit exit_code || false
    }

    exit_code = Minitest.run ARGV
  } unless @@installed_at_exit
  @@installed_at_exit = true
end

The key is using specific CSS classes and passing hl_lines option to Pygments which specifies line numbers to be emphasized. This instructs the code highlighter to wrap the emphasized line in an element that has hll as its class, so some CSS needs to be added to achieve the opacity effect seen above.

Here's the CSS that makes this happen:

.highlight .emphasized {
  & span {
    opacity: 0.3;
  }

  & span.hll {
    opacity: 1;

    & span {
      opacity: 1;
    }
  }
}

This simply lowers the opacity of non-emphasized lines in a code block.

These code blocks have additional functionality of linking to the source location on Github with the location attribute. This is achieved by patching the original highlight plugin from Jekyll and appending the element when rendering the block.

The source code for this is open source and can be found at shime/deep-dive.