urvanov-ru / crayon-syntax-highlighter

Syntax Highlighter supporting multiple languages, themes, fonts, highlighting from a URL, local file or post text.
https://wordpress.org/plugins/urvanov-syntax-highlighter/
GNU General Public License v3.0
60 stars 11 forks source link

Ruby heredocs aren't properly formatted #48

Open RobertRodes opened 1 year ago

RobertRodes commented 1 year ago

I have this Ruby code:

  def closing_screen_message_lose
    <<~BLOCK
      You have lost $#{GAMBLER_STAKE - @gambler.cash}.#{SPACE}

      But not to worry. Just spend a year washing dishes in our kitchen and \
      we'll call it even.#{SPACE}

      See you tomorrow at 5 a.m. Don't be late!#{SPACE}
    BLOCK
  end

The part of the string between the apostrophe in "we'll" and the apostrophe in "Don't" is formatted as a string. The rest is formatted as code. Also, the string interpolations are formatted as comments, except for the #{SPACE} between the apostrophes, which is formatted as string. (Tested with both Github and Obsidian Light themes.)

FWIW, here's the hack I used to work around the problem. This hack still treats interpolated expressions as strings, which isn't ideal. But it's an improvement on treating them as comments!

  function fixRubyHeredocs() {
    const codeBlock = document.getElementById('ruby-code').querySelectorAll('.crayon-pre')[0].children;
    const docLines = [[374, 378], [391, 397], [402, 406], [411, 426]];
    for(let heredoc of docLines) {
      for (let i=heredoc[0]; i<heredoc[1]; i++) {
        for (let span of codeBlock[i].children) {
          span.className = 'crayon-s';
        }
      }  
    }
  }
  1. This assumes a div with the id ruby-code that contains the prethat contains the code.
  2. docLines is an array of arrays that marks the blocks to be changed. Each inner array contains the start and stop indexes from the collection of div elements that crayon assigns to the individual lines of code.
  3. Each line is a collection of spans with formatting classes assigned to them; this hack just replaces each class with the one for string.
  4. The fixed code window is at https://robertrodes.com/work-samples/#blackjack. The fixed lines of code can be seen at the line numbers specified in the docLines array with an offset of 1.