docbrown/app/labor/markdown_traverser.rb
Juanito Fatas cc09ed7cd1
Do not escape underscored username in code or codeblocks (#5785) [deploy]
It only runs when markdown has underscored usernames.

Skip escaping underscore when content is in code or codeblock. It works by
going through all lines of a markdown content. Find underscored username.
Escape if we are not in the codeblock.

The (?<!) is negative lookbehind which rules out the case
when a underscored username is present in code, e.g., `@_dev_` will not be escaped.
2020-02-25 17:30:08 -05:00

37 lines
786 B
Ruby

# To go through a markdown document. Mainly used to decide if we are in
# code blocks to decide if we should escape underscored usernames.
class MarkdownTraverser
def initialize(markdown)
@lines = markdown.dup.lines
init_position
end
def each
lines.each do |line|
update_position(line.include?(CODEBLOCK_MARKER))
yield(line)
end
end
def in_codeblock?
prev == true && current == false
end
private
CODEBLOCK_MARKER = "```".freeze
private_constant :CODEBLOCK_MARKER
attr_reader :lines
attr_accessor :prev, :current
def init_position
self.prev = false
self.current = lines.first.include?(CODEBLOCK_MARKER)
end
def update_position(current)
self.current = current
self.prev = current ? !prev : prev
end
end