Class: Redcarpet::Render::Console

Inherits:
Base
  • Object
show all
Includes:
CLIMarkdown::Colors, CLIMarkdown::Theme
Defined in:
lib/mdless/console.rb

Constant Summary collapse

@@listitemid =
0
@@listid =
0
@@elementid =
0
@@footnotes =
[]
@@headers =
[]
[]
[]

Constants included from CLIMarkdown::Theme

CLIMarkdown::Theme::THEME_DEFAULTS

Constants included from CLIMarkdown::Colors

CLIMarkdown::Colors::COLORS, CLIMarkdown::Colors::ESCAPE_REGEX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CLIMarkdown::Theme

#load_theme, #load_theme_file

Methods included from CLIMarkdown::Colors

#blackout, #c, #last_color_code, #size_clean, #uncolor, #uncolor!, #wrap

Instance Attribute Details

#cols=(value) ⇒ Object (writeonly)

Sets the attribute cols

Parameters:

  • value

    the value to set the attribute cols to.



7
8
9
# File 'lib/mdless/console.rb', line 7

def cols=(value)
  @cols = value
end

#file=(value) ⇒ Object (writeonly)

Sets the attribute file

Parameters:

  • value

    the value to set the attribute file to.



7
8
9
# File 'lib/mdless/console.rb', line 7

def file=(value)
  @file = value
end

#log=(value) ⇒ Object (writeonly)

Sets the attribute log

Parameters:

  • value

    the value to set the attribute log to.



7
8
9
# File 'lib/mdless/console.rb', line 7

def log=(value)
  @log = value
end

#options=(value) ⇒ Object (writeonly)

Sets the attribute options

Parameters:

  • value

    the value to set the attribute options to.



7
8
9
# File 'lib/mdless/console.rb', line 7

def options=(value)
  @options = value
end

#theme=(value) ⇒ Object (writeonly)

Sets the attribute theme

Parameters:

  • value

    the value to set the attribute theme to.



7
8
9
# File 'lib/mdless/console.rb', line 7

def theme=(value)
  @theme = value
end

Instance Method Details



280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/mdless/console.rb', line 280

def autolink(link, _)
  [
    pre_element,
    color('link brackets'),
    '<',
    color('link url'),
    link,
    color('link brackets'),
    '>',
    xc,
    post_element
  ].join('')
end

#block_code(code, language) ⇒ Object



146
147
148
# File 'lib/mdless/console.rb', line 146

def block_code(code, language)
  "\n\n#{hilite_code(code, language)}#{xc}\n\n"
end

#block_html(raw_html) ⇒ Object



164
165
166
# File 'lib/mdless/console.rb', line 164

def block_html(raw_html)
  "#{color('html color')}#{color_tags(raw_html)}#{xc}"
end

#block_quote(quote) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/mdless/console.rb', line 150

def block_quote(quote)
  ret = "\n\n"
  quote.split("\n").each do |line|
    ret += [
      color('blockquote marker color'),
      @theme['blockquote']['marker']['character'],
      color('blockquote color'),
      line,
      "\n"
    ].join('')
  end
  "#{ret}\n\n"
end

#codespan(code) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/mdless/console.rb', line 294

def codespan(code)
  [
    pre_element,
    color('code_span marker'),
    @theme['code_span']['character'],
    color('code_span color'),
    code,
    color('code_span marker'),
    @theme['code_span']['character'],
    xc,
    post_element
  ].join('')
end

#color(key) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/mdless/console.rb', line 120

def color(key)
  val = nil
  keys = key.split(/[ ,>]/)
  if @theme.key?(keys[0])
    val = @theme[keys.shift]
  else
    @log.error("Invalid theme key: #{key}") unless keys[0] =~ /^text/
    return c([:reset])
  end
  keys.each do |k|
    if val.key?(k)
      val = val[k]
    else
      @log.error("Invalid theme key: #{k}")
      return c([:reset])
    end
  end
  if val.is_a? String
    val = "x #{val}"
    res = val.split(/ /).map(&:to_sym)
    c(res)
  else
    c([:reset])
  end
end

#color_dd_def(input) ⇒ Object



667
668
669
670
671
672
673
674
675
676
677
678
# File 'lib/mdless/console.rb', line 667

def color_dd_def(input)
  input.gsub(/(?<=\n|\A)(?::)\s+(.*)/) do
    m = Regexp.last_match
    [
      color('dd marker'),
      ": ",
      color('dd color'),
      m[1],
      xc
    ].join
  end
end

#color_footnote_def(idx) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/mdless/console.rb', line 468

def color_footnote_def(idx)
  text = @@footnotes[idx]
  [
    color('footnote brackets'),
    "[",
    color('footnote caret'),
    "^",
    color('footnote title'),
    idx,
    color('footnote brackets'),
    "]:",
    color('footnote note'),
    ' ',
    text.uncolor.strip,
    xc,
    "\n"
  ].join('')
end

#color_image_tag(link, title, alt_text) ⇒ Object



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/mdless/console.rb', line 350

def color_image_tag(link, title, alt_text)
  [
    color('image bang'),
    '!',
    color('image brackets'),
    '[',
    color('image title'),
    alt_text,
    color('image brackets'),
    '](',
    color('image url'),
    link,
    title.nil? ? '' : %( "#{title}"),
    color('image brackets'),
    ')',
    xc,
  ].join
end


377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/mdless/console.rb', line 377

def color_link(link, title, content)
  [
    pre_element,
    color('link brackets'),
    '[',
    color('link text'),
    content,
    color('link brackets'),
    '](',
    color('link url'),
    link,
    title.nil? ? '' : %( "#{title}"),
    color('link brackets'),
    ')',
    xc,
    post_element
  ].join
end


396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/mdless/console.rb', line 396

def color_link_reference(link, idx, content)
  [
    pre_element,
    color('link brackets'),
    '[',
    color('link text'),
    content,
    color('link brackets'),
    '][',
    color('link url'),
    idx,
    color('link brackets'),
    ']',
    xc,
    post_element
  ].join
end


680
681
682
683
684
685
# File 'lib/mdless/console.rb', line 680

def color_links(input)
  input.gsub(/(?mi)(?<!\\e)\[(?<text>[^\[]+)\]\((?<url>\S+)(?: +"(?<title>.*?)")?\)/) do
    m = Regexp.last_match
    color_link(m['url'].uncolor, m['title']&.uncolor, m['text'].uncolor)
  end
end

#color_meta(text) ⇒ Object



554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/mdless/console.rb', line 554

def color_meta(text)
  input = text.dup
  first_line = input.split("\n").first
  if first_line =~ /(?i-m)^---[ \t]*?$/
    @log.info('Found YAML')
    # YAML
    in_yaml = true
    input.sub!(/(?i-m)^---[ \t]*\n([\s\S]*?)\n[-.]{3}[ \t]*\n/m) do
      m = Regexp.last_match
      @log.info('Processing YAML Header')
      lines = m[0].split(/\n/)
      longest = lines.inject { |memo, word| memo.length > word.length ? memo : word }.length
      longest = longest < @cols ? longest + 1 : @cols
      lines.map do |line|
        if line =~ /^[-.]{3}\s*$/
          line = "#{color('metadata marker')}#{'%' * longest}"
        else
          line.sub!(/^(.*?:)[ \t]+(\S)/, '\1 \2')
          line = "#{color('metadata color')}#{line}"
        end

        line += "\u00A0" * (longest - line.uncolor.strip.length) + xc
        line
      end.join("\n") + "#{xc}\n"
    end
  end

  if !in_yaml && first_line =~ /(?i-m)^[\w ]+:\s+\S+/
    @log.info('Found MMD Headers')
    input.sub!(/(?i-m)^([\S ]+:[\s\S]*?)+(?=\n\n)/) do |mmd|
      lines = mmd.split(/\n/)
      return mmd if lines.count > 20

      longest = lines.inject { |memo, word| memo.length > word.length ? memo : word }.length
      longest = longest < @cols ? longest + 1 : @cols
      lines.map do |line|
        line.sub!(/^(.*?:)[ \t]+(\S)/, '\1 \2')
        line = "#{color('metadata color')}#{line}"
        line += "\u00A0" * (longest - line.uncolor.strip.length)
        line + xc
      end.join("\n") + "#{"\u00A0" * longest}#{xc}\n"
    end
  end

  input
end


414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/mdless/console.rb', line 414

def color_reference_link(link, title, content)
  [
    color('link brackets'),
    '[',
    color('link text'),
    content,
    color('link brackets'),
    ']:',
    color('text'),
    ' ',
    color('link url'),
    link,
    title.nil? ? '' : %( "#{title}"),
    xc
  ].join
end

#color_table(input) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mdless/console.rb', line 34

def color_table(input)
  first = true
  input.split(/\n/).map do |line|
    if first
      if line =~ /^\+-+/
        line.gsub!(/^/, color('table border'))
      else
        first = false
        line.gsub!(/\|/, "#{color('table border')}|#{color('table header')}")
      end
    elsif line.strip =~ /^[|:\- +]+$/
      line.gsub!(/^(.*)$/, "#{color('table border')}\\1#{color('table color')}")
      line.gsub!(/([:\-+]+)/, "#{color('table divider')}\\1#{color('table border')}")
    else
      line.gsub!(/\|/, "#{color('table border')}|#{color('table color')}")
    end
  end.join("\n")
end

#color_tags(html) ⇒ Object



442
443
444
# File 'lib/mdless/console.rb', line 442

def color_tags(html)
  html.gsub(%r{(<\S+( [^>]+)?>)}, "#{color('html brackets')}\\1#{xc}")
end

#double_emphasis(text) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
# File 'lib/mdless/console.rb', line 308

def double_emphasis(text)
  [
    pre_element,
    color('emphasis bold'),
    @theme['emphasis']['bold_character'],
    text,
    @theme['emphasis']['bold_character'],
    xc,
    post_element
  ].join
end

#emphasis(text) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
# File 'lib/mdless/console.rb', line 320

def emphasis(text)
  [
    pre_element,
    color('emphasis italic'),
    @theme['emphasis']['italic_character'],
    text,
    @theme['emphasis']['italic_character'],
    xc,
    post_element
  ].join
end

#exec_available(cli) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/mdless/console.rb', line 53

def exec_available(cli)
  if File.exist?(File.expand_path(cli))
    File.executable?(File.expand_path(cli))
  else
    TTY::Which.exist?(cli)
  end
end

#fix_colors(input) ⇒ Object



725
726
727
728
729
730
731
732
# File 'lib/mdless/console.rb', line 725

def fix_colors(input)
  input.gsub(/<<pre(?<id>\d+)>>(?<content>.*?)<<post\k<id>>>/m) do
    m = Regexp.last_match
    pre = m.pre_match
    last_color = pre.last_color_code
    "#{fix_colors(m['content'])}#{last_color}"
  end.gsub(/<<(pre|post)\d+>>/, '')
end

#fix_equations(input) ⇒ Object



808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
# File 'lib/mdless/console.rb', line 808

def fix_equations(input)
  input.gsub(/((\\\\\[|\$\$)(.*?)(\\\\\]|\$\$)|(\\\\\(|\$)(.*?)(\\\\\)|\$))/) do
    m = Regexp.last_match
    if m[2]
      brackets = [m[2], m[4]]
      equat = m[3]
    else
      brackets = [m[5], m[7]]
      equat = m[6]
    end
    [
      pre_element,
      color('math brackets'),
      brackets[0],
      xc,
      color('math equation'),
      equat,
      color('math brackets'),
      brackets[1],
      xc,
      post_element
    ].join
  end
end

#fix_lists(input, indent = 0) ⇒ Object



513
514
515
516
517
518
519
520
521
522
523
# File 'lib/mdless/console.rb', line 513

def fix_lists(input, indent = 0)
  input.gsub(%r{(?<line><<list(?<id>\d+)>>(?<content>.*?)<</list\k<id>>>)}m) do
    m = Regexp.last_match
    fix_lists(m['content'].split(/\n/).map do |l|
      outdent = l.scan(%r{<</list\d+>>}).count
      indent += l.scan(/<<list\d+>>/).count
      indent -= outdent
      "#{' ' * indent}#{l}"
    end.join("\n"), indent)
  end + "\n"
end

#footnote_def(text, idx) ⇒ Object



487
488
489
# File 'lib/mdless/console.rb', line 487

def footnote_def(text, idx)
  @@footnotes[idx] = text
end

#footnote_ref(text) ⇒ Object



491
492
493
494
495
496
497
498
499
# File 'lib/mdless/console.rb', line 491

def footnote_ref(text)
  [
    pre_element,
    color('footnote title'),
    "[^#{text}]",
    xc,
    post_element
  ].join('')
end

#footnotes(text) ⇒ Object



458
459
460
461
462
463
464
465
466
# File 'lib/mdless/console.rb', line 458

def footnotes(text)
  # [
  #   color('footnote note'),
  #   text,
  #   "\n",
  #   xc,
  # ].join('')
  nil
end

#get_headers(input) ⇒ Object



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
# File 'lib/mdless/console.rb', line 525

def get_headers(input)
  unless @@headers && !@@headers.empty?
    @@headers = []
    headers = input.scan(/^((?!#!)(\#{1,6})\s*([^#]+?)(?: #+)?\s*|(\S.+)\n([=-]+))$/i)

    headers.each do |h|
      hlevel = 6
      title = nil
      if h[4] =~ /=+/
        hlevel = 1
        title = h[3]
      elsif h[4] =~ /-+/
        hlevel = 2
        title = h[3]
      else
        hlevel = h[1].length
        title = h[2]
      end
      @@headers << [
        '#' * hlevel,
        title,
        h[0]
      ]
    end
  end

  @@headers
end

#header(text, header_level) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/mdless/console.rb', line 168

def header(text, header_level)
  pad = ''
  ansi = ''
  case header_level
  when 1
    ansi = color('h1 color')
    pad = color('h1 pad')
    char = @theme['h1']['pad_char'] || '='
    pad += text.length + 2 > @cols ? char * text.length : char * (@cols - (text.length + 1))
  when 2
    ansi = color('h2 color')
    pad = color('h2 pad')
    char = @theme['h2']['pad_char'] || '-'
    pad += text.length + 2 > @cols ? char * text.length : char * (@cols - (text.length + 1))
  when 3
    ansi = color('h3 color')
  when 4
    ansi = color('h4 color')
  when 5
    ansi = color('h5 color')
  else
    ansi = color('h6 color')
  end

  # If we're in iTerm and not paginating, add
  # iTerm Marks for navigation on h1-3
  if header_level < 4 &&
     ENV['TERM_PROGRAM'] =~ /^iterm/i &&
     @options[:pager] == false
    ansi = "\e]1337;SetMark\a#{ansi}"
  end

  "\n#{xc}#{ansi}#{text} #{pad}#{xc}\n\n"
end

#highlight(text) ⇒ Object



346
347
348
# File 'lib/mdless/console.rb', line 346

def highlight(text)
  "#{pre_element}#{color('highlight')}#{text}#{xc}#{post_element}"
end

#highlight_tags(input) ⇒ Object



833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
# File 'lib/mdless/console.rb', line 833

def highlight_tags(input)
  tag_color = color('at_tags tag')
  value_color = color('at_tags value')
  input.gsub(/(?<pre>\s|m)(?<tag>@[^ ("']+)(?:(?<lparen>\()(?<value>.*?)(?<rparen>\)))?/) do
    m = Regexp.last_match
    last_color = m.pre_match.last_color_code
    [
      m['pre'],
      tag_color,
      m['tag'],
      m['lparen'],
      value_color,
      m['value'],
      tag_color,
      m['rparen'],
      xc,
      last_color
    ].join
  end
end

#hilite_code(code_block, language) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
# File 'lib/mdless/console.rb', line 66

def hilite_code(code_block, language)
  @log.error('Syntax highlighting requested by pygmentize is not available') if @options[:syntax_higlight] && !exec_available('pygmentize')

  if @options[:syntax_higlight] && exec_available('pygmentize')
    lexer = language && valid_lexer?(language) ? "-l #{language}" : '-g'
    begin
      cmd = [
        'pygmentize -f terminal256',
        "-O style=#{@theme['code_block']['pygments_theme']}",
        lexer,
        '2> /dev/null'
      ].join(' ')
      hilite, s = Open3.capture2(cmd,
                                 stdin_data: code_block)
      if s.success?
        hilite = xc + hilite.split(/\n/).map do |l|
          [
            color('code_block marker'),
            '> ',
            "#{color('code_block bg')}#{l.strip}#{xc}"
          ].join
        end.join("\n").blackout(@theme['code_block']['bg']) + "#{xc}\n"
      end
    rescue StandardError => e
      @log.error(e)
      hilite = code_block
    end
  else
    hilite = code_block.split(/\n/).map do |line|
      [
        color('code_block marker'),
        '> ',
        color('code_block color'),
        line,
        xc
      ].join
    end.join("\n").blackout(@theme['code_block']['bg']) + "#{xc}\n"
  end

  [
    xc,
    color('code_block border'),
    '-' * @cols,
    xc,
    "\n",
    color('code_block color'),
    hilite.chomp,
    "\n",
    color('code_block border'),
    '-' * @cols,
    xc
  ].join
end

#hruleObject



203
204
205
# File 'lib/mdless/console.rb', line 203

def hrule()
  "\n\n#{color('hr color')}#{'_' * @cols}#{xc}\n\n"
end

#image(link, title, alt_text) ⇒ Object



369
370
371
# File 'lib/mdless/console.rb', line 369

def image(link, title, alt_text)
  "<<img>>#{link}||#{title}||#{alt_text}<</img>>"
end

#insert_footnotes(input) ⇒ Object



501
502
503
504
505
506
507
508
509
510
511
# File 'lib/mdless/console.rb', line 501

def insert_footnotes(input)
  input.split(/\n/).map do |line|
    notes = line.to_enum(:scan, /\[\^(?<ref>\d+)\]/).map { Regexp.last_match }
    if notes.count.positive?
      footnotes = notes.map { |n| color_footnote_def(n['ref'].to_i) }.join("\n")
      "#{line}\n\n#{footnotes}\n\n"
    else
      line
    end
  end.join("\n")
end

#linebreakObject



373
374
375
# File 'lib/mdless/console.rb', line 373

def linebreak
  "  \n"
end


431
432
433
434
435
436
437
438
439
440
# File 'lib/mdless/console.rb', line 431

def link(link, title, content)
  res = color_link(link, title, content)
  @@links << {
    link: res,
    url: link,
    title: title,
    content: content
  }
  res
end

#list(contents, list_type) ⇒ Object



207
208
209
210
211
# File 'lib/mdless/console.rb', line 207

def list(contents, list_type)
  @@listitemid = 0
  @@listid += 1
  "<<list#{@@listid}>>#{contents}<</list#{@@listid}>>"
end

#list_item(text, list_type) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/mdless/console.rb', line 213

def list_item(text, list_type)
  case list_type
  when :unordered
    [
      "#{color('list bullet')}",
      color('list color'),
      text,
      xc
    ].join('')
  when :ordered
    @@listitemid += 1
    [
      color('list number'),
      "#{@@listitemid}. ",
      color('list color'),
      text,
      xc
    ].join('')
  end
end

#paragraph(text) ⇒ Object



234
235
236
# File 'lib/mdless/console.rb', line 234

def paragraph(text)
  "#{xc}#{text}#{xc}#{x}\n\n"
end

#post_elementObject



22
23
24
# File 'lib/mdless/console.rb', line 22

def post_element
  "<<post#{@@elementid}>>"
end

#postprocess(input) ⇒ Object



854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'lib/mdless/console.rb', line 854

def postprocess(input)
  input.scrub!

  if @options[:inline_footnotes]
    input = insert_footnotes(input)
  else
    footnotes = @@footnotes.map.with_index do |fn, i|
      next if fn.nil?

      color_footnote_def(i)
    end.join("\n")
    input = "#{input}\n\n#{footnotes}"
  end
  # escaped characters
  input.gsub!(/\\(\S)/, '\1')
  # equations
  input = fix_equations(input)
  # misc html
  input.gsub!(%r{<br */?>}, "#{pre_element}\n#{post_element}")
  # format links
  input = reference_links(input) if @options[:links] == :reference || @options[:links] == :paragraph
  # lists
  input = fix_lists(input, 0)
  input = render_images(input) if @options[:local_images]
  input = highlight_tags(input) if @options[:at_tags] || @options[:taskpaper]
  fix_colors(input)
end

#pre_elementObject



17
18
19
20
# File 'lib/mdless/console.rb', line 17

def pre_element
  @@elementid += 1
  "<<pre#{@@elementid}>>"
end

#preprocess(input) ⇒ Object



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'lib/mdless/console.rb', line 601

def preprocess(input)
  in_yaml = false

  input = color_meta(input)

  ## Replace setex headers with ATX
  input.gsub!(/^([^\n]+)\n={2,}\s*$/m, "# \\1\n")
  input.gsub!(/^([^\n]+?)\n-{2,}\s*$/m, "## \\1\n")

  @@headers = get_headers(input)

  if @options[:section]
    new_content = []
    @options[:section].each do |sect|
      in_section = false
      top_level = 1
      input.split(/\n/).each do |graf|
        if graf =~ /^(#+) *(.*?)( *#+)?$/
          m = Regexp.last_match
          level = m[1].length
          title = m[2]
          if in_section
            if level >= top_level
              new_content.push(graf)
            else
              in_section = false
              break
            end
          elsif title.downcase == @@headers[sect - 1][1].downcase
            in_section = true
            top_level = level + 1
            new_content.push(graf)
          else
            next
          end
        elsif in_section
          new_content.push(graf)
        end
      end
    end
    input = new_content.join("\n")
  end

  # definition lists
  input.gsub!(/(?mi)(?<=\n|\A)(?<term>(?!<:)[^\n]+)(?<def>(\n+: [^\n]+)+)/) do
    m = Regexp.last_match
    "#{color('dd term')}#{m['term']}#{xc}#{color('dd color')}#{color_dd_def(m['def'])}"
  end

  if @options[:taskpaper] == :auto
    @options[:taskpaper] = if @file =~ /\.taskpaper/
                             @log.info('TaskPaper extension detected')
                             true
                           elsif CLIMarkdown::TaskPaper.is_taskpaper?(input)
                             @log.info('TaskPaper document detected')
                             true
                           else
                             false
                           end
  end

  input = CLIMarkdown::TaskPaper.highlight(input, @theme) if @options[:taskpaper]

  input
end

#raw_html(raw_html) ⇒ Object



446
447
448
# File 'lib/mdless/console.rb', line 446

def raw_html(raw_html)
  "#{pre_element}#{color('html color')}#{color_tags(raw_html)}#{xc}#{post_element}"
end


687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/mdless/console.rb', line 687

def reference_links(input)
  grafs = input.split(/\n{2,}/)
  counter = 1

  grafs.map! do |graf|
    next if graf =~ /^$/

    links_added = false

    @@links.each do |link|
      if graf =~ /#{Regexp.escape(link[:link])}/
        url = link[:url].uncolor
        content = link[:content]
        title = link[:title]&.uncolor
        graf.gsub!(/#{Regexp.escape(link[:link])}/, color_link_reference(url, counter, content))
        if @options[:links] == :paragraph
          if links_added
            graf += "\n#{color_reference_link(url, title, counter)}"
          else
            graf = "#{graf}\n\n#{color_reference_link(url, title, counter)}"
            links_added = true
          end
        else
          @@footer_links << color_reference_link(url, title, counter)
        end
        counter += 1
      end
    end
    "\n#{graf}\n"
  end

  if @options[:links] == :paragraph
    grafs.join("\n")
  else
    grafs.join("\n") + "\n#{@@footer_links.join("\n")}\n"
  end
end

#render_images(input) ⇒ Object



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/mdless/console.rb', line 734

def render_images(input)
  input.gsub(%r{<<img>>(.*?)<</img>>}) do
    link, title, alt_text = Regexp.last_match(1).split(/\|\|/)

    if (exec_available('imgcat') || exec_available('chafa')) && @options[:local_images]
      if exec_available('imgcat')
        @log.info('Using imgcat for image rendering')
      elsif exec_available('chafa')
        @log.info('Using chafa for image rendering')
      end
      img_path = link
      if img_path =~ /^http/ && @options[:remote_images]
        if exec_available('imgcat')
          @log.info('Using imgcat for image rendering')
          begin
            res, s = Open3.capture2(%(curl -sS "#{img_path}" 2> /dev/null | imgcat))

            if s.success?
              pre = !alt_text.nil? ? "    #{c(%i[d blue])}[#{alt_text.strip}]\n" : ''
              post = !title.nil? ? "\n    #{c(%i[b blue])}-- #{title} --" : ''
              result = pre + res + post
            end
          rescue StandardError => e
            @log.error(e)
          end
        elsif exec_available('chafa')
          @log.info('Using chafa for image rendering')
          term = '-f sixels'
          term = ENV['TERMINAL_PROGRAM'] =~ /iterm/i ? '-f iterm' : term
          term = ENV['TERMINAL_PROGRAM'] =~ /kitty/i ? '-f kitty' : term
          FileUtils.rm_r '.mdless_tmp', force: true if File.directory?('.mdless_tmp')
          Dir.mkdir('.mdless_tmp')
          Dir.chdir('.mdless_tmp')
          `curl -SsO #{img_path} 2> /dev/null`
          tmp_img = File.basename(img_path)
          img = `chafa #{term} "#{tmp_img}"`
          pre = alt_text ? "    #{c(%i[d blue])}[#{alt_text.strip}]\n" : ''
          post = title ? "\n    #{c(%i[b blue])}-- #{tail} --" : ''
          result = pre + img + post
          Dir.chdir('..')
          FileUtils.rm_r '.mdless_tmp', force: true
        else
          @log.warn('No viewer for remote images')
        end
      else
        if img_path =~ %r{^[~/]}
          img_path = File.expand_path(img_path)
        elsif @file
          base = File.expand_path(File.dirname(@file))
          img_path = File.join(base, img_path)
        end
        if File.exist?(img_path)
          pre = !alt_text.nil? ? "    #{c(%i[d blue])}[#{alt_text.strip}]\n" : ''
          post = !title.nil? ? "\n    #{c(%i[b blue])}-- #{title} --" : ''
          if exec_available('imgcat')
            img = `imgcat "#{img_path}"`
          elsif exec_available('chafa')
            term = '-f sixels'
            term = ENV['TERMINAL_PROGRAM'] =~ /iterm/i ? '-f iterm' : term
            term = ENV['TERMINAL_PROGRAM'] =~ /kitty/i ? '-f kitty' : term
            img = `chafa #{term} "#{img_path}"`
          end
          result = pre + img + post
        end
      end
    end
    if result.nil?
      color_image_tag(link, title, alt_text)
    else
      "#{pre_element}#{result}#{xc}#{post_element}"
    end
  end
end

#strikethrough(text) ⇒ Object



450
451
452
# File 'lib/mdless/console.rb', line 450

def strikethrough(text)
  "#{pre_element}#{color('strikethrough')}#{text}#{xc}#{post_element}"
end

#superscript(text) ⇒ Object



454
455
456
# File 'lib/mdless/console.rb', line 454

def superscript(text)
  "#{pre_element}#{color('super')}^#{text}#{xc}#{post_element}"
end

#table(header, body) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
# File 'lib/mdless/console.rb', line 255

def table(header, body)
  formatted = CLIMarkdown::MDTableCleanup.new([
    "#{header}",
    table_header_row,
    "|\n",
    "#{body}\n\n"
  ].join(''))
  res = formatted.to_md
  "#{color_table(res)}\n"
  # res
end

#table_cell(content, alignment) ⇒ Object



272
273
274
275
276
277
278
# File 'lib/mdless/console.rb', line 272

def table_cell(content, alignment)
  @header_row ||= []
  if @table_cols && @header_row.count < @table_cols
    @header_row << alignment
  end
  %(#{content} |)
end

#table_header_rowObject



240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/mdless/console.rb', line 240

def table_header_row
  @header_row.map do |alignment|
    case alignment
    when :left
      '|:---'
    when :right
      '|---:'
    when :center
      '|:--:'
    else
      '|----'
    end
  end.join('') + '|'
end

#table_row(content) ⇒ Object



267
268
269
270
# File 'lib/mdless/console.rb', line 267

def table_row(content)
  @table_cols = content.scan(/\|/).count
  %(#{content}\n)
end

#triple_emphasis(text) ⇒ Object



332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/mdless/console.rb', line 332

def triple_emphasis(text)
  [
    pre_element,
    color('emphasis bold-italic'),
    @theme['emphasis']['italic_character'],
    @theme['emphasis']['bold_character'],
    text,
    @theme['emphasis']['bold_character'],
    @theme['emphasis']['italic_character'],
    xc,
    post_element
  ].join
end

#valid_lexer?(language) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
64
# File 'lib/mdless/console.rb', line 61

def valid_lexer?(language)
  lexers = %w(Clipper XBase Cucumber cucumber Gherkin gherkin RobotFramework robotframework abap ada ada95ada2005 ahk antlr-as antlr-actionscript antlr-cpp antlr-csharp antlr-c# antlr-java antlr-objc antlr-perl antlr-python antlr-ruby antlr-rb antlr apacheconf aconf apache applescript as actionscript as3 actionscript3 aspectj aspx-cs aspx-vb asy asymptote autoit Autoit awk gawk mawk nawk basemake bash sh ksh bat bbcode befunge blitzmax bmax boo brainfuck bf bro bugs winbugs openbugs c-objdump c ca65 cbmbas ceylon cfengine3 cf3 cfm cfs cheetah spitfire clojure clj cmake cobol cobolfree coffee-script coffeescript common-lisp cl console control coq cpp c++ cpp-objdump c++-objdumb cxx-objdump croc csharp c# css+django css+jinja css+erb css+ruby css+genshitext css+genshi css+lasso css+mako css+myghty css+php css+smarty css cuda cu cython pyx d-objdump d dart delphi pas pascal objectpascal dg diff udiff django jinja dpatch dtd duel Duel Engine Duel View JBST jbst JsonML+BST dylan-console dylan-repl dylan-lid lid dylan ec ecl elixir ex exs erb erl erlang evoque factor fan fancy fy felix flx fortran fsharp gas genshi kid xml+genshi xml+kid genshitext glsl gnuplot go gooddata-cl gosu groff nroff man groovy gst haml HAML haskell hs haxeml hxml html+cheetah html+spitfire html+django html+jinja html+evoque html+genshi html+kid html+lasso html+mako html+myghty html+php html+smarty html+velocity html http hx haXe hybris hy idl iex ini cfg io ioke ik irc jade JADE jags java jlcon js+cheetah javascript+cheetah js+spitfire javascript+spitfire js+django javascript+django js+jinja javascript+jinja js+erb javascript+erb js+ruby javascript+ruby js+genshitext js+genshi javascript+genshitext javascript+genshi js+lasso javascript+lasso js+mako javascript+mako js+myghty javascript+myghty js+php javascript+php js+smarty javascript+smarty js javascript json jsp julia jl kconfig menuconfig linux-config kernel-config koka kotlin lasso lassoscript lhs literate-haskell lighty lighttpd live-script livescript llvm logos logtalk lua make makefile mf bsdmake mako maql mason matlab matlabsession minid modelica modula2 m2 monkey moocode moon moonscript mscgen msc mupad mxml myghty mysql nasm nemerle newlisp newspeak nginx nimrod nim nsis nsi nsh numpy objdump objective-c++ objectivec++ obj-c++ objc++ objective-c objectivec obj-c objc objective-j objectivej obj-j objj ocaml octave ooc opa openedge abl progress perl pl php php3 php4 php5 plpgsql postgresql postgres postscript pot po pov powershell posh ps1 prolog properties protobuf psql postgresql-console postgres-console puppet py3tb pycon pypylog pypy pytb python py sage python3 py3 qml Qt Meta Language Qt modeling Language racket rkt ragel-c ragel-cpp ragel-d ragel-em ragel-java ragel-objc ragel-ruby ragel-rb ragel raw rb ruby duby rbcon irb rconsole rout rd rebol redcode registry rhtml html+erb html+ruby rst rest restructuredtext rust sass SASS scala scaml SCAML scheme scm scilab scss shell-session smali smalltalk squeak smarty sml snobol sourceslist sources.list sp spec splus s r sql sqlite3 squidconf squid.conf squid ssp stan systemverilog sv tcl tcsh csh tea tex latex text trac-wiki moin treetop ts urbiscript vala vapi vb.net vbnet velocity verilog v vgl vhdl vim xml+cheetah xml+spitfire xml+django xml+jinja xml+erb xml+ruby xml+evoque xml+lasso xml+mako xml+myghty xml+php xml+smarty xml+velocity xml xquery xqy xq xql xqm xslt xtend yaml)
  lexers.include? language.strip
end

#xObject



30
31
32
# File 'lib/mdless/console.rb', line 30

def x
  c([:reset])
end

#xcObject



26
27
28
# File 'lib/mdless/console.rb', line 26

def xc
  x + color('text')
end