Class: Mdlint::Renderer::MdRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/mdlint/renderer/md_renderer.rb,
sig/internal.rbs

Constant Summary collapse

BULLET_MARKERS =
["-"].freeze
HORIZONTAL_RULE =
"_" * 70
LINE_START_PROHIBITED =
/\A[、。,.!?!?、)]|\A[)】」』〉》〕]}…]/
LINE_END_PROHIBITED =
/[「『(【〈《〔[{]\z/

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ MdRenderer

Returns a new instance of MdRenderer.

Parameters:

  • options (Object) (defaults to: {})


14
15
16
17
18
19
# File 'lib/mdlint/renderer/md_renderer.rb', line 14

def initialize(options = {})
  @options = options
  @bullet_list_depth = 0
  @reference_definitions = {}
  @used_references = Set.new
end

Instance Method Details

#append_reference_definitions(output) ⇒ Object

Parameters:

  • output (Object)

Returns:

  • (Object)


74
75
76
77
# File 'lib/mdlint/renderer/md_renderer.rb', line 74

def append_reference_definitions(output)
  # mdformat converts reference links to inline links, so no definitions needed
  # This method is kept for potential future use or configuration options
end

#apply_end_of_line(text) ⇒ String

Parameters:

  • text (Object)

Returns:

  • (String)


47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mdlint/renderer/md_renderer.rb', line 47

def apply_end_of_line(text)
  eol = @options[:end_of_line] || :lf
  case eol
  when :lf
    text.gsub(/\r\n/, "\n")
  when :crlf
    text.gsub(/\r?\n/, "\r\n")
  when :keep
    text
  else
    text.gsub(/\r\n/, "\n")
  end
end

#collect_paragraph_content(tokens, start_index, content_array) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • content_array (Object)

Returns:

  • (Object)


383
384
385
386
387
388
389
390
391
392
# File 'lib/mdlint/renderer/md_renderer.rb', line 383

def collect_paragraph_content(tokens, start_index, content_array)
  i = start_index + 1
  while i < tokens.length && tokens[i].type != :paragraph_close
    if tokens[i].type == :inline
      content_array << render_inline(tokens[i])
    end
    i += 1
  end
  i + 1
end

#collect_reference_definitions(tokens) ⇒ Object

Parameters:

  • tokens (Object)

Returns:

  • (Object)


61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/mdlint/renderer/md_renderer.rb', line 61

def collect_reference_definitions(tokens)
  tokens.each do |token|
    next unless token.type == :reference_definition

    label = token.attrs[:label]
    # Only keep the first definition for each label (remove duplicates)
    @reference_definitions[label] ||= {
      url: token.attrs[:url],
      title: token.attrs[:title]
    }
  end
end

#find_close_token(tokens, start_index, close_type) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • close_type (Object)

Returns:

  • (Object)


572
573
574
575
576
577
578
579
580
# File 'lib/mdlint/renderer/md_renderer.rb', line 572

def find_close_token(tokens, start_index, close_type)
  i = start_index + 1
  while i < tokens.length
    return i if tokens[i].type == close_type

    i += 1
  end
  tokens.length
end

Parameters:

  • url (Object)

Returns:

  • (String)


582
583
584
585
586
587
588
589
590
591
# File 'lib/mdlint/renderer/md_renderer.rb', line 582

def format_link_url(url)
  # Remove angle brackets if present and not needed
  url = url.gsub(/^<|>$/, "")
  # Add angle brackets only if URL contains spaces or parentheses
  if url.match?(/[\s()]/)
    "<#{url}>"
  else
    url
  end
end

#render(tokens) ⇒ String

Parameters:

  • tokens (Object)

Returns:

  • (String)


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
# File 'lib/mdlint/renderer/md_renderer.rb', line 21

def render(tokens)
  @bullet_list_depth = 0
  @reference_definitions = {}
  @used_references = Set.new
  @ordered_list_counter = 0

  # First pass: collect all reference definitions
  collect_reference_definitions(tokens)

  output = []
  render_tokens(tokens, output)

  # Append used reference definitions at the end, sorted by label
  append_reference_definitions(output)

  result = output.join
  result.gsub!(/\n{3,}/, "\n\n")

  # Apply end of line setting
  result = apply_end_of_line(result)

  result.chomp!
  result += "\n" unless result.empty?
  result
end

#render_blockquote(tokens, start_index, output) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • output (Object)

Returns:

  • (Object)


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/mdlint/renderer/md_renderer.rb', line 394

def render_blockquote(tokens, start_index, output)
  open_token = tokens[start_index]
  i = start_index + 1
  inner_output = []

  while i < tokens.length && tokens[i].type != :blockquote_close
    token = tokens[i]
    case token.type
    when :paragraph_open
      i = render_paragraph(tokens, i, inner_output)
    when :heading_open
      i = render_heading(tokens, i, inner_output)
    when :blockquote_open
      i = render_blockquote(tokens, i, inner_output)
    else
      i += 1
    end
  end

  quoted = inner_output.join.chomp.split("\n").map { |l| "> #{l}".rstrip }.join("\n")
  if open_token.attrs[:alert]
    label = open_token.attrs[:alert].upcase
    quoted = "> [!#{label}]\n#{quoted}" unless quoted.empty?
    quoted = "> [!#{label}]" if quoted.empty?
  end
  output << "#{quoted}\n\n"
  i + 1
end

#render_bullet_list(tokens, start_index, output) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • output (Object)

Returns:

  • (Object)


250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/mdlint/renderer/md_renderer.rb', line 250

def render_bullet_list(tokens, start_index, output)
  marker = BULLET_MARKERS[@bullet_list_depth % BULLET_MARKERS.length]
  @bullet_list_depth += 1
  i = start_index + 1

  while i < tokens.length && tokens[i].type != :bullet_list_close
    if tokens[i].type == :list_item_open
      i = render_list_item(tokens, i, output, "#{marker} ")
    else
      i += 1
    end
  end

  @bullet_list_depth -= 1
  output << "\n" unless output.last&.end_with?("\n\n")
  i + 1
end

#render_code_block(token, output) ⇒ Object

Parameters:

  • token (Object)
  • output (Object)

Returns:

  • (Object)


440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/mdlint/renderer/md_renderer.rb', line 440

def render_code_block(token, output)
  # Convert indented code blocks to fenced code blocks (mdformat style)
  content = token.content.chomp

  # Determine the minimum number of backticks needed
  backtick_count = 3
  content.scan(/`+/) do |match|
    backtick_count = [backtick_count, match.length + 1].max
  end

  marker = "`" * backtick_count

  output << "#{marker}\n"
  output << "#{content}\n"
  output << "#{marker}\n\n"
end

#render_fence(token, output) ⇒ Object

Parameters:

  • token (Object)
  • output (Object)

Returns:

  • (Object)


423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/mdlint/renderer/md_renderer.rb', line 423

def render_fence(token, output)
  info = token.info || ""
  content = token.content.chomp

  # Determine the minimum number of backticks needed
  backtick_count = 3
  content.scan(/`+/) do |match|
    backtick_count = [backtick_count, match.length + 1].max
  end

  marker = "`" * backtick_count

  output << "#{marker}#{info}\n"
  output << "#{content}\n"
  output << "#{marker}\n\n"
end

#render_heading(tokens, start_index, output) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • output (Object)

Returns:

  • (Object)


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/mdlint/renderer/md_renderer.rb', line 136

def render_heading(tokens, start_index, output)
  open_token = tokens[start_index]
  level = open_token.tag[1].to_i
  markup = "#" * level

  inline_content = ""
  i = start_index + 1
  while i < tokens.length && tokens[i].type != :heading_close
    if tokens[i].type == :inline
      inline_content = render_inline(tokens[i])
    end
    i += 1
  end

  output << "#{markup} #{inline_content}\n\n"
  i + 1
end

#render_inline(token) ⇒ String

Parameters:

  • token (Object)

Returns:

  • (String)


457
458
459
460
461
# File 'lib/mdlint/renderer/md_renderer.rb', line 457

def render_inline(token)
  return token.content if token.children.empty?

  render_inline_tokens(token.children)
end

#render_inline_tokens(tokens) ⇒ String

Parameters:

  • tokens (Object)

Returns:

  • (String)


463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/mdlint/renderer/md_renderer.rb', line 463

def render_inline_tokens(tokens)
  output = []
  i = 0

  while i < tokens.length
    token = tokens[i]
    case token.type
    when :text
      output << token.content
    when :code_inline
      content = token.content
      # Strip unnecessary leading/trailing spaces (unless content contains backticks)
      unless content.include?("`")
        content = content.strip
      end
      # Determine minimum backticks needed
      backtick_count = 1
      content.scan(/`+/) do |match|
        backtick_count = [backtick_count, match.length + 1].max
      end
      backticks = "`" * backtick_count
      # Add space padding if content starts/ends with backtick
      if content.start_with?("`") || content.end_with?("`")
        output << "#{backticks} #{content} #{backticks}"
      else
        output << "#{backticks}#{content}#{backticks}"
      end
    when :math_inline
      output << "$#{token.content}$"
    when :footnote_ref
      output << "[^#{token.attrs[:label]}]"
    when :strong_open
      markup = token.markup.empty? ? "**" : token.markup
      close_index = find_close_token(tokens, i, :strong_close)
      inner = render_inline_tokens(tokens[(i + 1)...close_index])
      output << "#{markup}#{inner}#{markup}"
      i = close_index
    when :em_open
      markup = token.markup.empty? ? "*" : token.markup
      close_index = find_close_token(tokens, i, :em_close)
      inner = render_inline_tokens(tokens[(i + 1)...close_index])
      output << "#{markup}#{inner}#{markup}"
      i = close_index
    when :s_open
      close_index = find_close_token(tokens, i, :s_close)
      inner = render_inline_tokens(tokens[(i + 1)...close_index])
      output << "~~#{inner}~~"
      i = close_index
    when :link_open
      close_index = find_close_token(tokens, i, :link_close)
      inner = render_inline_tokens(tokens[(i + 1)...close_index])

      if token.markup == "autolink"
        href = token.attrs[:href] || ""
        output << "<#{href}>"
      elsif token.markup == "reference"
        # Reference link - resolve from definitions
        label = token.attrs[:reference_label]
        ref = @reference_definitions[label]
        if ref
          @used_references << label
          formatted_href = format_link_url(ref[:url])
          if ref[:title]
            output << "[#{inner}](#{formatted_href} \"#{ref[:title]}\")"
          else
            output << "[#{inner}](#{formatted_href})"
          end
        else
          # Reference not found, keep as-is
          output << "[#{inner}]"
        end
      else
        href = token.attrs[:href] || ""
        title = token.attrs[:title]
        formatted_href = format_link_url(href)
        if title
          output << "[#{inner}](#{formatted_href} \"#{title}\")"
        else
          output << "[#{inner}](#{formatted_href})"
        end
      end
      i = close_index
    when :image
      alt = token.attrs[:alt] || token.content || ""
      reference = @reference_definitions[token.attrs[:reference_label]]
      src = token.attrs[:src] || reference&.fetch(:url, nil)
      unless src
        output << "![#{alt}]"
      else
        title = token.attrs[:title] || reference&.fetch(:title, nil)
        if title
          output << "![#{alt}](#{src} \"#{title}\")"
        else
          output << "![#{alt}](#{src})"
        end
      end
    when :softbreak
      output << "\n"
    when :hardbreak
      output << "\\\n"
    when :html_inline
      output << token.content
    end
    i += 1
  end

  output.join
end

#render_list_item(tokens, start_index, output, prefix) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • output (Object)
  • prefix (Object)

Returns:

  • (Object)


293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/mdlint/renderer/md_renderer.rb', line 293

def render_list_item(tokens, start_index, output, prefix)
  open_token = tokens[start_index]
  i = start_index + 1
  item_content = []

  while i < tokens.length && tokens[i].type != :list_item_close
    token = tokens[i]
    case token.type
    when :paragraph_open
      i = collect_paragraph_content(tokens, i, item_content)
    when :bullet_list_open
      nested_output = []
      i = render_bullet_list(tokens, i, nested_output)
      nested = nested_output.join.split("\n").map { |l| "   #{l}" }.join("\n")
      item_content << nested
    when :ordered_list_open
      nested_output = []
      i = render_ordered_list(tokens, i, nested_output)
      nested = nested_output.join.split("\n").map { |l| "   #{l}" }.join("\n")
      item_content << nested
    else
      i += 1
    end
  end

  content = item_content.join("\n").strip
  task_prefix = if open_token.attrs[:task]
                  checked = open_token.attrs[:checked] ? "x" : " "
                  "[#{checked}] "
                else
                  ""
                end
  output << "#{prefix}#{task_prefix}#{content}\n"
  i + 1
end

#render_ordered_list(tokens, start_index, output) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • output (Object)

Returns:

  • (Object)


268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/mdlint/renderer/md_renderer.rb', line 268

def render_ordered_list(tokens, start_index, output)
  open_token = tokens[start_index]
  start_num = open_token.attrs[:start] || 1
  current_num = start_num
  i = start_index + 1

  while i < tokens.length && tokens[i].type != :ordered_list_close
    if tokens[i].type == :list_item_open
      if @options[:number]
        # Consecutive numbering mode
        i = render_list_item(tokens, i, output, "#{current_num}. ")
        current_num += 1
      else
        # mdformat default: all items use the same number (start number)
        i = render_list_item(tokens, i, output, "#{start_num}. ")
      end
    else
      i += 1
    end
  end

  output << "\n" unless output.last&.end_with?("\n\n")
  i + 1
end

#render_paragraph(tokens, start_index, output) ⇒ Object

Parameters:

  • tokens (Object)
  • start_index (Object)
  • output (Object)

Returns:

  • (Object)


154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/mdlint/renderer/md_renderer.rb', line 154

def render_paragraph(tokens, start_index, output)
  inline_content = ""
  i = start_index + 1
  while i < tokens.length && tokens[i].type != :paragraph_close
    if tokens[i].type == :inline
      inline_content = render_inline(tokens[i])
    end
    i += 1
  end

  wrapped_content = wrap_text(inline_content)
  output << "#{wrapped_content}\n\n"
  i + 1
end

#render_table(token, output) ⇒ Object

Parameters:

  • token (Object)
  • output (Object)

Returns:

  • (Object)


329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/mdlint/renderer/md_renderer.rb', line 329

def render_table(token, output)
  rows = token.meta.fetch(:rows, [])
  return if rows.empty?

  alignments = token.meta.fetch(:alignments, [])
  if @options.fetch(:table_align, true)
    column_count = rows.map(&:length).max || 0
    widths = column_count.times.map do |index|
      [rows.map { |row| TextWidth.measure(row[index].to_s) }.max || 0, 3].max
    end
    output << "| #{render_table_row(rows.first, widths, alignments)} |\n"
    separators = widths.each_index.map { |index| table_separator(alignments[index], widths[index]) }
    output << "| #{separators.join(" | ")} |\n"
    rows.drop(1).each { |row| output << "| #{render_table_row(row, widths, alignments)} |\n" }
  else
    header = rows.first
    output << "| #{header.join(" | ")} |\n"
    separators = header.each_index.map { |index| table_separator(alignments[index], 3) }
    output << "| #{separators.join(" | ")} |\n"
    rows.drop(1).each { |row| output << "| #{row.join(" | ")} |\n" }
  end
  output << "\n"
end

#render_table_row(row, widths, alignments) ⇒ String

Parameters:

  • row (Object)
  • widths (Object)
  • alignments (Object)

Returns:

  • (String)


353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/mdlint/renderer/md_renderer.rb', line 353

def render_table_row(row, widths, alignments)
  widths.each_index.map do |index|
    value = row[index].to_s
    padding = widths[index] - TextWidth.measure(value)
    case alignments[index]
    when :right
      " " * padding + value
    when :center
      left = padding / 2
      " " * left + value + " " * (padding - left)
    else
      value + " " * padding
    end
  end.join(" | ")
end

#render_tokens(tokens, output) ⇒ Object

Parameters:

  • tokens (Object)
  • output (Object)

Returns:

  • (Object)


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/mdlint/renderer/md_renderer.rb', line 81

def render_tokens(tokens, output)
  i = 0
  while i < tokens.length
    token = tokens[i]
    case token.type
    when :heading_open
      i = render_heading(tokens, i, output)
    when :paragraph_open
      i = render_paragraph(tokens, i, output)
    when :bullet_list_open
      i = render_bullet_list(tokens, i, output)
    when :ordered_list_open
      i = render_ordered_list(tokens, i, output)
    when :blockquote_open
      i = render_blockquote(tokens, i, output)
    when :fence
      render_fence(token, output)
      i += 1
    when :code_block
      render_code_block(token, output)
      i += 1
    when :hr
      output << "#{HORIZONTAL_RULE}\n\n"
      i += 1
    when :html_block
      output << token.content
      output << "\n" unless token.content.end_with?("\n")
      i += 1
    when :front_matter
      output << token.content
      output << "\n" unless token.content.end_with?("\n")
      output << "\n"
      i += 1
    when :directive
      output << token.content
      output << "\n" unless token.content.end_with?("\n")
      output << "\n"
      i += 1
    when :table
      render_table(token, output)
      i += 1
    when :math_block, :footnote_definition
      output << token.content
      output << "\n" unless token.content.end_with?("\n")
      output << "\n"
      i += 1
    when :reference_definition
      # Skip - will be output at the end
      i += 1
    else
      i += 1
    end
  end
end

#split_to_width(text, width) ⇒ Array[String]

Parameters:

  • text (Object)
  • width (Object)

Returns:

  • (Array[String])


216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/mdlint/renderer/md_renderer.rb', line 216

def split_to_width(text, width)
  return [text] if TextWidth.measure(text) <= width

  chunks = []
  remaining = text
  while !remaining.empty?
    chunk = TextWidth.take(remaining, width).to_s
    break if chunk.empty?

    if remaining.length > chunk.length && chunk.match?(LINE_END_PROHIBITED)
      moved = chunk[-1].to_s
      chunk = chunk[0...-1].to_s
      remaining = moved + (remaining[chunk.length + 1..] || "")
    end

    if remaining.match?(LINE_START_PROHIBITED)
      first = remaining[0].to_s
      first_width = TextWidth.measure(first)
      if TextWidth.measure(chunk) + first_width <= width
        chunk = chunk.to_s + first
        remaining = remaining[1..] || ""
      elsif chunk.length > 1
        moved = chunk[-1].to_s
        chunk = chunk[0...-1].to_s
        remaining = moved + remaining.to_s
      end
    end

    chunks << chunk
    remaining = remaining[chunk.length..] || ""
  end
  chunks
end

#table_separator(alignment, width) ⇒ String

Parameters:

  • alignment (Object)
  • width (Object)

Returns:

  • (String)


369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/mdlint/renderer/md_renderer.rb', line 369

def table_separator(alignment, width)
  width = [width, 3].max
  case alignment
  when :center
    ":#{"-" * width}:"
  when :left
    ":#{"-" * width}"
  when :right
    "#{"-" * width}:"
  else
    "-" * width
  end
end

#wrap_at_width(text, width) ⇒ String

Parameters:

  • text (Object)
  • width (Object)

Returns:

  • (String)


186
187
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
# File 'lib/mdlint/renderer/md_renderer.rb', line 186

def wrap_at_width(text, width)
  return text if width <= 0

  lines = []
  paragraphs = text.split(/\n\n+/)

  paragraphs.each_with_index do |paragraph, idx|
    # Join lines within paragraph
    paragraph = paragraph.gsub(/\n(?!\n)/, " ")
    words = paragraph.split(/\s+/)
    current_line = ""

    words.each do |word|
      if current_line.empty?
        current_line = word
      elsif (TextWidth.measure(current_line) + 1 + TextWidth.measure(word)) <= width
        current_line += " " + word
      else
        lines.concat(split_to_width(current_line, width))
        current_line = word
      end
    end

    lines.concat(split_to_width(current_line, width)) unless current_line.empty?
    lines << "" if idx < paragraphs.length - 1
  end

  lines.join("\n")
end

#wrap_text(text) ⇒ String

Parameters:

  • text (Object)

Returns:

  • (String)


169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/mdlint/renderer/md_renderer.rb', line 169

def wrap_text(text)
  wrap_mode = @options[:wrap] || :keep

  case wrap_mode
  when :keep
    text
  when :no
    # Remove soft line breaks, join lines
    text.gsub(/\n(?!\n)/, " ")
  when Integer
    # Wrap at specified width
    wrap_at_width(text, wrap_mode)
  else
    text
  end
end