Module: MarkdownServer::Helpers::MarkdownHelpers

Defined in:
lib/markdown_server/helpers/markdown_helpers.rb

Constant Summary collapse

CALLOUT_TYPES =

Obsidian-style callouts: ‘> [!TYPE] Optional Title` at the start of a blockquote becomes a styled .callout panel. `[!TYPE]+` makes it a foldable <details open>; `[!TYPE]-` makes it foldable and collapsed.

{
  "note"     => { label: "Note",     color: "#448aff" },
  "abstract" => { label: "Abstract", color: "#00b0ff" },
  "summary"  => { label: "Summary",  color: "#00b0ff" },
  "tldr"     => { label: "TL;DR",    color: "#00b0ff" },
  "info"     => { label: "Info",     color: "#00b8d4" },
  "todo"     => { label: "Todo",     color: "#00b8d4" },
  "tip"      => { label: "Tip",      color: "#00bfa5" },
  "hint"     => { label: "Hint",     color: "#00bfa5" },
  "important"=> { label: "Important",color: "#00bfa5" },
  "success"  => { label: "Success",  color: "#00c853" },
  "check"    => { label: "Check",    color: "#00c853" },
  "done"     => { label: "Done",     color: "#00c853" },
  "question" => { label: "Question", color: "#64dd17" },
  "help"     => { label: "Help",     color: "#64dd17" },
  "faq"      => { label: "FAQ",      color: "#64dd17" },
  "warning"  => { label: "Warning",  color: "#ff9100" },
  "caution"  => { label: "Caution",  color: "#ff9100" },
  "attention"=> { label: "Attention",color: "#ff9100" },
  "failure"  => { label: "Failure",  color: "#ff5252" },
  "fail"     => { label: "Fail",     color: "#ff5252" },
  "missing"  => { label: "Missing",  color: "#ff5252" },
  "danger"   => { label: "Danger",   color: "#ff1744" },
  "error"    => { label: "Error",    color: "#ff1744" },
  "bug"      => { label: "Bug",      color: "#f50057" },
  "example"  => { label: "Example",  color: "#7c4dff" },
  "quote"    => { label: "Quote",    color: "#9e9e9e" },
  "cite"     => { label: "Cite",     color: "#9e9e9e" }
}.freeze
CALLOUT_ICONS =
{
  "note"     => '<path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4z"/>',
  "abstract" => '<path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 12h6M9 16h6"/>',
  "info"     => '<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>',
  "todo"     => '<circle cx="12" cy="12" r="10"/><polyline points="9 12 11 14 15 10"/>',
  "tip"      => '<path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>',
  "success"  => '<polyline points="20 6 9 17 4 12"/>',
  "question" => '<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
  "warning"  => '<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
  "failure"  => '<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>',
  "danger"   => '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>',
  "bug"      => '<rect x="8" y="6" width="8" height="14" rx="4"/><path d="M19 7l-3 2M5 7l3 2M19 13h-3M8 13H5M19 19l-3-2M5 19l3-2M9 2l1 2M15 2l-1 2"/>',
  "example"  => '<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>',
  "quote"    => '<path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/>'
}.freeze
CALLOUT_ICON_ALIASES =
{
  "summary" => "abstract", "tldr" => "abstract",
  "hint" => "tip", "important" => "tip",
  "check" => "success", "done" => "success",
  "help" => "question", "faq" => "question",
  "caution" => "warning", "attention" => "warning",
  "fail" => "failure", "missing" => "failure",
  "error" => "danger",
  "cite" => "quote"
}.freeze

Instance Method Summary collapse

Instance Method Details

#callout_icon_svg(type) ⇒ Object



153
154
155
156
157
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 153

def callout_icon_svg(type)
  key = CALLOUT_ICON_ALIASES[type] || type
  body = CALLOUT_ICONS[key] || CALLOUT_ICONS["note"]
  %(<svg class="callout-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">#{body}</svg>)
end

#callout_meta(type) ⇒ Object



149
150
151
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 149

def callout_meta(type)
  CALLOUT_TYPES[type] || { label: type.capitalize, color: "#888888" }
end

#detect_source_language(real_path, content) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 305

def detect_source_language(real_path, content)
  ext = File.extname(real_path).downcase
  by_ext = case ext
           when ".py" then "python"
           when ".rb" then "ruby"
           when ".csv" then "text"
           when ".sh" then "bash"
           when ".yaml", ".yml" then "yaml"
           when ".erb" then "html"
           when ".html" then "html"
           when ".js" then "javascript"
           when ".css" then "css"
           when ".json" then "json"
           end
  return by_ext if by_ext

  if content.is_a?(String) && content.start_with?("#!")
    shebang = content.lines.first.to_s
    return "ruby"       if shebang.match?(/\bruby\b/)
    return "python"     if shebang.match?(/\bpython[\d.]*\b/)
    return "bash"       if shebang.match?(/\b(bash|zsh|dash|ksh|sh)\b/)
    return "javascript" if shebang.match?(/\bnode\b/)
    return "perl"       if shebang.match?(/\bperl\b/)
  end

  "text"
end

#extract_toc(html) ⇒ Object



333
334
335
336
337
338
339
340
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 333

def extract_toc(html)
  headings = []
  html.scan(/<h([1-6])\s[^>]*id="([^"]*)"[^>]*>(.*?)<\/h\1>/mi) do |level, id, text|
    clean_text = text.gsub(/<sup[^>]*id="fnref:[^"]*"[^>]*>.*?<\/sup>/i, "").gsub(/<[^>]+>/, "").strip
    headings << { level: level.to_i, id: id, text: clean_text }
  end
  headings
end

#parse_frontmatter(content) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 4

def parse_frontmatter(content)
  if content =~ /\A---\s*\n(.*?\n)---\s*\n(.*)/m
    begin
      meta = YAML.safe_load($1, permitted_classes: [Date, Time])
      body = $2
      [meta, body]
    rescue => e
      [nil, content]
    end
  else
    [nil, content]
  end
end

#render_frontmatter_value(value) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 269

def render_frontmatter_value(value)
  case value
  when Array
    value.map { |v|
      str = v.to_s
      if str.include?("[[")
        render_inline_wiki_links(str)
      else
        %(<span class="tag">#{h(str)}</span>)
      end
    }.join(" ")
  when String
    if value =~ /\Ahttps?:\/\//
      %(<a href="#{h(value)}" target="_blank" rel="noopener">#{h(value)}</a>)
    elsif value.include?("[[")
      render_inline_wiki_links(value)
    elsif value.length > 120
      render_markdown(value)
    else
      h(value)
    end
  when Numeric, TrueClass, FalseClass
    h(value.to_s)
  when NilClass
    %(<span class="empty">—</span>)
  else
    h(value.to_s)
  end
end


240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 240

def render_inline_wiki_links(str)
  result = ""
  last_end = 0
  str.scan(/\[\[([^\]]+)\]\]/) do |match|
    raw = match[0]
    m_start = $~.begin(0)
    m_end = $~.end(0)
    result += h(str[last_end...m_start])
    target, display = raw.include?("|") ? raw.split("|", 2) : [raw, nil]
    label = display || target
    if target.start_with?("#")
      anchor = target[1..].downcase.gsub(/\s+/, "-").gsub(/[^\w-]/, "")
      result += %(<a class="wiki-link" href="##{h(anchor)}">#{h(label)}</a>)
    else
      file_part, anchor_part = target.split("#", 2)
      anchor_suffix = anchor_part ? "##{anchor_part.downcase.gsub(/\s+/, '-').gsub(/[^\w-]/, '')}" : ""
      resolved = resolve_wiki_link(file_part)
      if resolved
        result += %(<a class="wiki-link" href="/browse/#{encode_path_component(resolved).gsub('%2F', '/')}#{anchor_suffix}">#{h(label)}</a>)
      else
        result += %(<span class="wiki-link broken">#{h(label)}</span>)
      end
    end
    last_end = m_end
  end
  result += h(str[last_end..])
  result
end

#render_markdown(text) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 18

def render_markdown(text)
  # Convert mermaid code fences to raw HTML divs before Kramdown so Rouge
  # never touches them and the content is preserved exactly for Mermaid.js.
  text = text.gsub(/^```mermaid[ \t]*\r?\n([\s\S]*?)^```[ \t]*(\r?\n|\z)/m) do
    "<div class=\"mermaid\">\n#{h($1.rstrip)}\n</div>\n\n"
  end

  # Run plugin markdown transformations (e.g. Bible citation auto-linking)
  settings.plugins.each { |p| text = p.transform_markdown(text) }

  # Process wiki links BEFORE Kramdown so that | isn't consumed as
  # a GFM table delimiter.
  text = text.gsub(/\[\[([^\]]+)\]\]/) do
    raw = $1
    if raw.include?("|")
      target, display = raw.split("|", 2)
    else
      target = raw
      display = nil
    end

    if target.start_with?("#")
      heading_text = target[1..]
      anchor = heading_text.downcase.gsub(/\s+/, "-").gsub(/[^\w-]/, "")
      label = display || heading_text
      %(<a class="wiki-link" href="##{h(anchor)}">#{h(label)}</a>)
    else
      file_part, anchor_part = target.split("#", 2)
      anchor_suffix = anchor_part ? "##{anchor_part.downcase.gsub(/\s+/, '-').gsub(/[^\w-]/, '')}" : ""
      resolved = resolve_wiki_link(file_part)
      label = display || target
      if resolved
        %(<a class="wiki-link" href="/browse/#{encode_path_component(resolved).gsub('%2F', '/')}#{anchor_suffix}">#{h(label)}</a>)
      else
        %(<span class="wiki-link broken">#{h(label)}</span>)
      end
    end
  end

  html = Kramdown::Document.new(
    text,
    input: "GFM",
    syntax_highlighter: "rouge",
    syntax_highlighter_opts: { default_lang: "text" },
    hard_wrap: settings.hard_wrap
  ).to_html

  # Restore non-numeric footnote labels: Kramdown converts all footnote
  # references to sequential numbers, but we want [^abc] to display "abc".
  html = html.gsub(%r{<sup id="fnref:([^"]+)"[^>]*>\s*<a href="#fn:\1"[^>]*>\d+</a>\s*</sup>}m) do
    full_match = $&
    name = $1
    if name =~ /\A\d+\z/
      full_match
    else
      %(<sup id="fnref:#{name}" role="doc-noteref"><a href="#fn:#{name}" class="footnote" rel="footnote">#{h(name)}</a></sup>)
    end
  end
  html = html.gsub(%r{<li id="fn:([^"]+)"[^>]*>\s*<p>}m) do
    full_match = $&
    name = $1
    if name =~ /\A\d+\z/
      full_match
    else
      %(<li id="fn:#{name}"><p><strong>#{h(name)}:</strong> )
    end
  end

  transform_callouts(html)
end


188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 188

def resolve_wiki_link(name)
  filename = "#{name}.md"
  base = File.realpath(root_dir)
  # On case-sensitive filesystems (Linux/Docker), FNM_CASEFOLD doesn't help
  # with directory listings. Try exact filename first, then lowercased variant.
  candidates = [filename]
  candidates << filename.downcase if filename != filename.downcase

  # Check the current file's directory first (exact case, then case-insensitive)
  if @current_wiki_dir
    local_exact = nil
    local_ci = nil
    candidates.each do |fn|
      Dir.glob(File.join(@current_wiki_dir, fn)).each do |path|
        real = File.realpath(path) rescue next
        next unless real.start_with?(base)
        relative = real.sub("#{base}/", "")
        next unless MarkdownServer::Unhide.visible?(relative.split("/"), Array(settings.unhide_rules))
        if File.basename(real) == filename
          local_exact = relative
          break
        else
          local_ci ||= relative
        end
      end
      break if local_exact
    end
    return local_exact if local_exact
    return local_ci if local_ci
  end

  # Fall back to global recursive search
  exact_match = nil
  ci_match = nil
  candidates.each do |fn|
    Dir.glob(File.join(base, "**", fn)).each do |path|
      real = File.realpath(path) rescue next
      next unless real.start_with?(base)
      relative = real.sub("#{base}/", "")
      next unless MarkdownServer::Unhide.visible?(relative.split("/"), Array(settings.unhide_rules))
      if File.basename(real) == filename
        exact_match ||= relative
      else
        ci_match ||= relative
      end
    end
    break if exact_match
  end

  exact_match || ci_match
end

#syntax_highlight(code, language) ⇒ Object



299
300
301
302
303
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 299

def syntax_highlight(code, language)
  formatter = Rouge::Formatters::HTML.new
  lexer = Rouge::Lexer.find_fancy(language) || Rouge::Lexers::PlainText.new
  formatter.format(lexer.lex(code))
end

#transform_callouts(html) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/markdown_server/helpers/markdown_helpers.rb', line 159

def transform_callouts(html)
  html.gsub(
    %r{<blockquote>\s*<p>\[!(\w+)\]([+-])?[ \t]*([^\n<]*?)[ \t]*(?:<br\s*/?>\n?|\n)?(.*?)</p>(.*?)</blockquote>}m
  ) do
    type = $1.downcase
    fold = $2
    custom_title = $3.to_s.strip
    first_p_rest = $4.to_s.strip
    rest = $5.to_s.strip

    meta = callout_meta(type)
    title = custom_title.empty? ? meta[:label] : custom_title

    body = +""
    body << "<p>#{first_p_rest}</p>" unless first_p_rest.empty?
    body << rest

    icon = callout_icon_svg(type)
    title_html = %(#{icon}<span class="callout-title-inner">#{h(title)}</span>)

    if fold
      open_attr = fold == "+" ? " open" : ""
      %(<div class="callout callout-#{type}" data-callout="#{type}" style="--callout-color: #{meta[:color]}"><details#{open_attr}><summary class="callout-title">#{title_html}</summary><div class="callout-content">#{body}</div></details></div>)
    else
      %(<div class="callout callout-#{type}" data-callout="#{type}" style="--callout-color: #{meta[:color]}"><div class="callout-title">#{title_html}</div><div class="callout-content">#{body}</div></div>)
    end
  end
end