How to mark search phrase in syntax highlighted markdown code?
In my rails blog app, I may author the post body markdown (I am using redcarpet for markdown parsing with CodeRay for syntax highlighting).
I have a search page, which returns posts containing the search query string.
I use the rails helper to highlight queries:
@post.body = highlight(@post.body, @query_phrase, highlighter: '<span class=\'highlighted\'>\1</span>'))
And I use css to set the background to yellow on the highlighted class.
The post body is stored as entered in the textarea (as markdown, unconverted), and the markdown is processed while rendering readonly views like posts#show and search results.
The problem is when I search for the word 'ruby', where the entered markdown uses fenced code blocks with language name for syntax highlighting, the search result gets messed up.
Here is the body markdown:
ruby ```ruby puts "Hello, world" ```
And here is the search result screenshot:
This is understandable, since the match 'ruby' after the fenced code block gets wrapped with the span and class for highlighting, but the markdown now sees
and outputs the span as is.
And similar problems occur within code as well, where matches within the code also get wrapped and outputted with the span in the search result.
How do I avoid this, and have the search highlight the actual phrase in the outputted markdown, preferably without having to persist the markdown's html output?
You should turn it into HTML first, and then pass it through