Class: CLIMarkdown::Converter

Inherits:
Object
  • Object
show all
Includes:
Colors
Defined in:
lib/mdless/converter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Colors

#c, #size_clean, #uncolor, #uncolor!, #wrap, #xc

Constructor Details

#initialize(args) ⇒ Converter

Returns a new instance of Converter.



11
12
13
14
15
16
17
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
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
135
136
137
138
139
140
# File 'lib/mdless/converter.rb', line 11

def initialize(args)
  @log = Logger.new(STDERR)
  @log.level = Logger::FATAL

  @options = {}
  optparse = OptionParser.new do |opts|
    opts.banner = "#{version} by Brett Terpstra\n\n> Usage: #{CLIMarkdown::EXECUTABLE_NAME} [options] [path]\n\n"

    @options[:section] = nil
    opts.on( '-s', '--section=TITLE', 'Output only a headline-based section of the input (numeric from -l)' ) do |section|
      @options[:section] = section.to_i
    end

    @options[:width] = %x{tput cols}.strip.to_i
    opts.on( '-w', '--width=COLUMNS', 'Column width to format for (default terminal width)' ) do |columns|
      @options[:width] = columns.to_i
    end

    @options[:pager] = true
    opts.on( '-p', '--[no-]pager', 'Formatted output to pager (default on)' ) do |p|
      @options[:pager] = p
    end

    opts.on( '-P', 'Disable pager (same as --no-pager)' ) do
      @options[:pager] = false
    end

    @options[:color] = true
    opts.on( '-c', '--[no-]color', 'Colorize output (default on)' ) do |c|
      @options[:color] = c
    end

    @options[:links] = :inline
    opts.on( '--links=FORMAT', 'Link style ([inline, reference], default inline)' ) do |format|
      if format =~ /^r/i
        @options[:links] = :reference
      end
    end

    @options[:list] = false
    opts.on( '-l', '--list', 'List headers in document and exit' ) do
      @options[:list] = true
    end

    @options[:local_images] = false
    @options[:remote_images] = false

    if exec_available('imgcat') && ENV['TERM_PROGRAM'] == 'iTerm.app'
      opts.on('-i', '--images=TYPE', 'Include [local|remote (both)] images in output (requires imgcat and iTerm2, default NONE)' ) do |type|
        if type =~ /^(r|b|a)/i
          @options[:local_images] = true
          @options[:remote_images] = true
        elsif type =~ /^l/i
          @options[:local_images] = true
        end
      end
      opts.on('-I', '--all-images', 'Include local and remote images in output (requires imgcat and iTerm2)' ) do
        @options[:local_images] = true
        @options[:remote_images] = true
      end
    end


    opts.on( '-d', '--debug LEVEL', 'Level of debug messages to output' ) do |level|
      if level.to_i > 0 && level.to_i < 5
        @log.level = 5 - level.to_i
      else
        $stderr.puts "Log level out of range (1-4)"
        Process.exit 1
      end
    end

    opts.on( '-h', '--help', 'Display this screen' ) do
      puts opts
      exit
    end

    opts.on( '-v', '--version', 'Display version number' ) do
      puts version
      exit
    end
  end

  optparse.parse!

  @cols = @options[:width]
  @output = ''
  @header_arr = []

  input = ''
  @ref_links = {}
  @footnotes = {}

  if args.length > 0
    files = args.delete_if { |f| !File.exists?(f) }
    files.each {|file|
      @log.info(%Q{Processing "#{file}"})
      @file = file
      begin
        input = IO.read(file).force_encoding('utf-8')
      rescue
        input = IO.read(file)
      end
      input.gsub!(/\r?\n/,"\n")
      if @options[:list]
        list_headers(input)
      else
        convert_markdown(input)
      end
    }
    printout
  elsif ! STDIN.tty?
    @file = nil
    begin
      input = STDIN.read.force_encoding('utf-8')
    rescue
      input = STDIN.read
    end
    input.gsub!(/\r?\n/,"\n")
    if @options[:list]
      list_headers(input)
    else
      convert_markdown(input)
    end
    printout
  else
    $stderr.puts "No input"
    Process.exit 1
  end
end

Instance Attribute Details

#helpersObject (readonly)

Returns the value of attribute helpers.



5
6
7
# File 'lib/mdless/converter.rb', line 5

def helpers
  @helpers
end

#logObject (readonly)

Returns the value of attribute log.



5
6
7
# File 'lib/mdless/converter.rb', line 5

def log
  @log
end

Instance Method Details

#clean_markers(input) ⇒ Object



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

def clean_markers(input)
  input.gsub!(/^(\e\[[\d;]+m)?[%~] ?/,'\1')
  input
end

#cleanup_tables(input) ⇒ Object



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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/mdless/converter.rb', line 218

def cleanup_tables(input)
  in_table = false
  header_row = false
  all_content = []
  this_table = []
  orig_table = []
  input.split(/\n/).each {|line|
    if line =~ /(\|.*?)+/ && line !~ /^\s*~/
      in_table = true
      table_line = line.to_s.uncolor.strip.sub(/^\|?\s*/,'|').gsub(/\s*([\|:])\s*/,'\1')

      if table_line.strip.gsub(/[\|:\- ]/,'') == ''
        header_row = true
      end
      this_table.push(table_line)
      orig_table.push(line)
    else
      if in_table
        if this_table.length > 2
          # if there's no header row, add one, cleanup requires it
          unless header_row
            cells = this_table[0].sub(/^\|/,'').scan(/.*?\|/).length
            cell_row = '|' + ':-----|'*cells
            this_table.insert(1, cell_row)
          end

          table = this_table.join("\n").strip
          begin
            formatted = MDTableCleanup.new(table)
            res = formatted.to_md
            res = color_table(res)
          rescue
            res = orig_table.join("\n")
          end
          all_content.push(res)
        else
          all_content.push(orig_table.join("\n"))
        end
        this_table = []
        orig_table = []
      end
      in_table = false
      header_row = false
      all_content.push(line)
    end
  }
  all_content.join("\n")
end

#color_image(line, text, url) ⇒ Object



304
305
306
307
308
# File 'lib/mdless/converter.rb', line 304

def color_image(line, text, url)
  text.gsub!(/\e\[0m/,c([:x,:cyan]))

  "#{c([:x,:red])}!#{c([:b,:black])}[#{c([:x,:cyan])}#{text}#{c([:b,:black])}](#{c([:u,:yellow])}#{url}#{c([:b,:black])})" + find_color(line)
end


291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/mdless/converter.rb', line 291

def color_link(line, text, url)
  out = c([:b,:black])
  out += "[#{c([:u,:blue])}#{text}"
  out += c([:b,:black])
  out += "]("
  out += c([:x,:cyan])
  out += url
  out += c([:b,:black])
  out += ")"
  out += find_color(line)
  out
end

#color_table(input) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/mdless/converter.rb', line 203

def color_table(input)
  first = true
  input.split(/\n/).map{|line|
    if first
      first = false
      line.gsub!(/\|/, "#{c([:d,:black])}|#{c([:x,:yellow])}")
    elsif line.strip =~ /^[|:\- ]+$/
      line.gsub!(/^(.*)$/, "#{c([:d,:black])}\\1#{c([:x,:white])}")
      line.gsub!(/([:\-]+)/,"#{c([:b,:black])}\\1#{c([:d,:black])}")
    else
      line.gsub!(/\|/, "#{c([:d,:black])}|#{c([:x,:white])}")
    end
  }.join("\n")
end

#convert_markdown(input) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
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
600
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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
# File 'lib/mdless/converter.rb', line 342

def convert_markdown(input)
  @headers = get_headers(input)
  # yaml/MMD headers
  in_yaml = false
  if input.split("\n")[0] =~ /(?i-m)^---[ \t]*?(\n|$)/
    @log.info("Found YAML")
    # YAML
    in_yaml = true
    input.sub!(/(?i-m)^---[ \t]*\n([\s\S]*?)\n[\-.]{3}[ \t]*\n/) do |yaml|
      m = Regexp.last_match

      @log.warn("Processing YAML Header")
      m[0].split(/\n/).map {|line|
        if line =~ /^[\-.]{3}\s*$/
          line = c([:d,:black,:on_black]) + "% " + c([:d,:black,:on_black]) + line
        else
          line.sub!(/^(.*?:)[ \t]+(\S)/, '\1 \2')
          line = c([:d,:black,:on_black]) + "% " + c([:d,:white]) + line
        end
        if @cols - line.uncolor.size > 0
          line += " "*(@cols-line.uncolor.size)
        end
      }.join("\n") + "#{xc}\n"
    end
  end

  if !in_yaml && input.gsub(/\n/,' ') =~ /(?i-m)^\w.+:\s+\S+ /
    @log.info("Found MMD Headers")
    input.sub!(/(?i-m)^([\S ]+:[\s\S]*?)+(?=\n\n)/) do |mmd|
      puts mmd
      mmd.split(/\n/).map {|line|
        line.sub!(/^(.*?:)[ \t]+(\S)/, '\1 \2')
        line = c([:d,:black,:on_black]) + "% " + c([:d,:white,:on_black]) + line
        if @cols - line.uncolor.size > 0
          line += " "*(@cols - line.uncolor.size)
        end
      }.join("\n") + " "*@cols + "#{xc}\n"
    end

  end


  # Gather reference links
  input.gsub!(/^\s{,3}(?<![\e*])\[\b(.+)\b\]: +(.+)/) do |m|
    match = Regexp.last_match
    @ref_links[match[1]] = match[2]
    ''
  end

  # Gather footnotes (non-inline)
  input.gsub!(/^ {,3}(?<!\*)(?:\e\[[\d;]+m)*\[(?:\e\[[\d;]+m)*\^(?:\e\[[\d;]+m)*\b(.+)\b(?:\e\[[\d;]+m)*\]: *(.*?)\n/) do |m|
    match = Regexp.last_match
    @footnotes[match[1].uncolor] = match[2].uncolor
    ''
  end

  if @options[:section]
    in_section = false
    top_level = 1
    new_content = []

    input.split(/\n/).each {|graf|
      if graf =~ /^(#+) *(.*?)( *#+)?$/
        level = $1.length
        title = $2

        if in_section
          if level >= top_level
            new_content.push(graf)
          else
            in_section = false
            break
          end
        elsif title.downcase == "#{@headers[@options[:section] - 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
    }

    input = new_content.join("\n")
  end

  h_adjust = highest_header(input) - 1
  input.gsub!(/^(#+)/) do |m|
    match = Regexp.last_match
    "#" * (match[1].length - h_adjust)
  end

  # code block parsing
  input.gsub!(/(?i-m)([`~]{3,})([\s\S]*?)\n([\s\S]*?)\1/) do
    m = Regexp.last_match
    if m[2].strip !~ /^\s*$/
      language = m[2].split(/ /)[0].downcase
      code_block = m[3].to_s.strip
      leader = language ? language.upcase : 'CODE'
    else
      first_line = m[3].to_s.split(/\n/)[0]

      if first_line =~ /^#!/
        @log.warn('Code block contains Shebang')
        shebang = first_line.match(/^(#!.*\/(?:env )?)([^\/]+)$/)
        language = shebang[2]
        code_block = m[3].to_s.strip
        leader = shebang[2] ? shebang[2].upcase : 'CODE'
      else
        code_block = m[3].to_s.split(/\n/).map do |l|
          new_code_line = l.gsub(/\t/, '    ')
          orig_length = new_code_line.size + 4
          new_code_line.gsub!(/ /, "#{c(%i[x white on_black])} ")
          pad_count = [@cols - orig_length, 0].max
          [
            "#{c(%i[x black])}~ #{c(%i[x white on_black])} ",
            new_code_line,
            c(%i[x white on_black]),
            ' ' * pad_count,
            xc
          ].join
        end.join("\n")
        leader = language ? language.upcase : 'CODE'
      end
    end
    leader += xc
    hiliteCode(language, code_block, leader, m[0])
  end

  # remove empty links
  input.gsub!(/\[(.*?)\]\(\s*?\)/, '\1')
  input.gsub!(/\[(.*?)\]\[\]/, '[\1][\1]')

  lines = input.split(/\n/)

  # previous_indent = 0

  lines.map!.with_index do |aLine, i|
    line = aLine.dup
    clean_line = line.dup.uncolor


    if clean_line.uncolor =~ /(^[%~])/ # || clean_line.uncolor =~ /^( {4,}|\t+)/
      ## TODO: find indented code blocks and prevent highlighting
      ## Needs to miss block indented 1 level in lists
      ## Needs to catch lists in code
      ## Needs to avoid within fenced code blocks
      # if line =~ /^([ \t]+)([^*-+]+)/
      #   indent = $1.gsub(/\t/, "    ").size
      #   if indent >= previous_indent
      #     line = "~" + line
      #   end
      #   p [indent, previous_indent]
      #   previous_indent = indent
      # end
    else
      # Headlines
      line.gsub!(/^(#+) *(.*?)(\s*#+)?\s*$/) do |match|
        m = Regexp.last_match
        pad = ""
        ansi = ''
        case m[1].length
        when 1
          ansi = c([:b, :black, :on_intense_white])
          pad = c([:b,:white])
          pad += m[2].length + 2 > @cols ? "*"*m[2].length : "*"*(@cols - (m[2].length + 2))
        when 2
          ansi = c([:b, :green, :on_black])
          pad = c([:b,:black])
          pad += m[2].length + 2 > @cols ? "-"*m[2].length : "-"*(@cols - (m[2].length + 2))
        when 3
          ansi = c([:u, :b, :yellow])
        when 4
          ansi = c([:x, :u, :yellow])
        else
          ansi = c([:b, :white])
        end

        "\n#{xc}#{ansi}#{m[2]} #{pad}#{xc}\n"
      end

      # place footnotes under paragraphs that reference them
      if line =~ /\[(?:\e\[[\d;]+m)*\^(?:\e\[[\d;]+m)*(\S+)(?:\e\[[\d;]+m)*\]/
        key = $1.uncolor
        if @footnotes.key? key
          line += "\n\n#{c([:b,:black,:on_black])}[#{c([:b,:cyan,:on_black])}^#{c([:x,:yellow,:on_black])}#{key}#{c([:b,:black,:on_black])}]: #{c([:u,:white,:on_black])}#{@footnotes[key]}#{xc}"
          @footnotes.delete(key)
        end
      end

      # color footnote references
      line.gsub!(/\[\^(\S+)\]/) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match, true)
        counter = i
        while last.nil? && counter > 0
          counter -= 1
          find_color(lines[counter])
        end
        "#{c([:b,:black])}[#{c([:b,:yellow])}^#{c([:x,:yellow])}#{match[1]}#{c([:b,:black])}]" + (last ? last : xc)
      end

      # blockquotes
      line.gsub!(/^(\s*>)+( .*?)?$/) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match, true)
        counter = i
        while last.nil? && counter > 0
          counter -= 1
          find_color(lines[counter])
        end
        "#{c([:b,:black])}#{match[1]}#{c([:x,:magenta])} #{match[2]}" + (last ? last : xc)
      end

      # make reference links inline
      line.gsub!(/(?<![\e*])\[(\b.*?\b)?\]\[(\b.+?\b)?\]/) do |m|
        match = Regexp.last_match
        title = match[2] || ''
        text = match[1] || ''
        if match[2] && @ref_links.key?(title.downcase)
          "[#{text}](#{@ref_links[title]})"
        elsif match[1] && @ref_links.key?(text.downcase)
          "[#{text}](#{@ref_links[text]})"
        else
          if input.match(/^#+\s*#{Regexp.escape(text)}/i)
            "[#{text}](##{text})"
          else
            match[1]
          end
        end
      end

      # color inline links
      line.gsub!(/(?<![\e*!])\[(\S.*?\S)\]\((\S.+?\S)\)/) do |m|
        match = Regexp.last_match
        color_link(match.pre_match, match[1], match[2])
      end



      # inline code
      line.gsub!(/`(.*?)`/) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match, true)
        "#{c([:b,:black])}`#{c([:b,:white])}#{match[1]}#{c([:b,:black])}`" + (last ? last : xc)
      end

      # horizontal rules
      line.gsub!(/^ {,3}([\-*] ?){3,}$/) do |m|
        c([:x,:black]) + '_'*@cols + xc
      end

      # bold, bold/italic
      line.gsub!(/(?<pre>^|\s)(?<open>[\*_]{2,3})(?<content>[^\*_\s][^\*_]+?[^\*_\s])[\*_]{2,3}/) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match, true)
        counter = i
        while last.nil? && counter > 0
          counter -= 1
          last = find_color(lines[counter])
        end
        emph = match['open'].length == 2 ? c([:b]) : c(%i[b u i])
        "#{match['pre']}#{emph}#{match['content']}" + (last ? last : xc)
      end

      # italic
      line.gsub!(/(^|\s)[\*_]([^\*_\s][^\*_]+?[^\*_\s])[\*_]/) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match, true)
        counter = i
        while last.nil? && counter > 0
          counter -= 1
          last = find_color(lines[counter])
        end
        "#{match[1]}#{c(%i[u i])}#{match[2]}" + (last ? last : xc)
      end

      # equations
      line.gsub!(/((\\\\\[)(.*?)(\\\\\])|(\\\\\()(.*?)(\\\\\)))/) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match)
        if match[2]
          brackets = [match[2], match[4]]
          equat = match[3]
        else
          brackets = [match[5], match[7]]
          equat = match[6]
        end
        "#{c([:b, :black])}#{brackets[0]}#{xc}#{c([:b,:blue])}#{equat}#{c([:b, :black])}#{brackets[1]}" + (last ? last : xc)
      end

      # list items
      # TODO: Fix ordered list numbering, pad numbers based on total number of list items
      line.gsub!(/^(\s*)([*\-+]|\d+\.) /) do |m|
        match = Regexp.last_match
        last = find_color(match.pre_match)
        indent = match[1] || ''
        "#{indent}#{c([:d, :red])}#{match[2]} " + (last ? last : xc)
      end

      # definition lists
      line.gsub!(/^(:\s*)(.*?)/) do |m|
        match = Regexp.last_match
        "#{c([:d, :red])}#{match[1]} #{c([:b, :white])}#{match[2]}#{xc}"
      end

      # misc html
      line.gsub!(/<br\/?>/, "\n")
      line.gsub!(/(?i-m)((<\/?)(\w+[\s\S]*?)(>))/) do |tag|
        match = Regexp.last_match
        last = find_color(match.pre_match)
        "#{c([:d,:yellow,:on_black])}#{match[2]}#{match[3]}#{match[4]}" + (last ? last : xc)
      end
    end

    line
  end

  input = lines.join("\n")

  # images
  input.gsub!(/^(.*?)!\[(.*)?\]\((.*?\.(?:png|gif|jpg))( +.*)?\)/) do |m|
    match = Regexp.last_match
    if match[1].uncolor =~ /^( {4,}|\t)+/
      match[0]
    else
      tail = match[4].nil? ? '' : " "+match[4].strip
      result = nil
      if exec_available('imgcat') && @options[:local_images]
        if match[3]
          img_path = match[3]
          if img_path =~ /^http/ && @options[:remote_images]
            begin
              res, s = Open3.capture2(%Q{curl -sS "#{img_path}" 2> /dev/null | imgcat})

              if s.success?
                pre = match[2].size > 0 ? "    #{c([:d,:blue])}[#{match[2].strip}]\n" : ''
                post = tail.size > 0 ? "\n    #{c([:b,:blue])}-- #{tail} --" : ''
                result = pre + res + post
              end
            rescue => e
              @log.error(e)
            end
          else
            if img_path =~ /^[~\/]/
              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.exists?(img_path)
              pre = match[2].size > 0 ? "    #{c([:d,:blue])}[#{match[2].strip}]\n" : ''
              post = tail.size > 0 ? "\n    #{c([:b,:blue])}-- #{tail} --" : ''
              img = %x{imgcat "#{img_path}"}
              result = pre + img + post
            end
          end
        end
      end
      if result.nil?
        match[1] + color_image(match.pre_match, match[2], match[3] + tail) + xc
      else
        match[1] + result + xc
      end
    end
  end

  @footnotes.each {|t, v|
    input += "\n\n#{c([:b,:black,:on_black])}[#{c([:b,:yellow,:on_black])}^#{c([:x,:yellow,:on_black])}#{t}#{c([:b,:black,:on_black])}]: #{c([:u,:white,:on_black])}#{v}#{xc}"
  }

  @output += input

end

#exec_available(cli) ⇒ Object



719
720
721
722
723
724
725
# File 'lib/mdless/converter.rb', line 719

def exec_available(cli)
  if File.exists?(File.expand_path(cli))
    File.executable?(File.expand_path(cli))
  else
    system "which #{cli}", :out => File::NULL
  end
end

#find_color(line, nullable = false) ⇒ Object



281
282
283
284
285
286
287
288
289
# File 'lib/mdless/converter.rb', line 281

def find_color(line,nullable=false)
  return line if line.nil?
  colors = line.scan(/\e\[[\d;]+m/)
  if colors && colors.size > 0
    colors[-1]
  else
    nullable ? nil : xc
  end
end

#get_headers(input) ⇒ Object



142
143
144
145
146
147
# File 'lib/mdless/converter.rb', line 142

def get_headers(input)
  unless @headers && @headers.length > 0
    @headers = input.scan(/^(#+)\s*(.*?)( #+)?\s*$/)
  end
  @headers
end

#highest_header(input) ⇒ Object



194
195
196
197
198
199
200
201
# File 'lib/mdless/converter.rb', line 194

def highest_header(input)
  headers = input.scan(/^(#+)/)
  top = 6
  headers.each {|h|
    top = h[0].length if h[0].length < top
  }
  top
end

#hiliteCode(language, codeBlock, leader, block) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/mdless/converter.rb', line 310

def hiliteCode(language, codeBlock, leader, block)
  if exec_available('pygmentize')
    lexer = language.nil? ? '-g' : "-l #{language}"
    begin
      hilite, s = Open3.capture2(%Q{pygmentize #{lexer} 2> /dev/null}, :stdin_data=>codeBlock)

      if s.success?
        hilite = hilite.split(/\n/).map{|l| "#{c([:x,:black])}~ #{xc}" + l}.join("\n")
      end
    rescue => e
      @log.error(e)
      hilite = block
    end
  else
    hilite = codeBlock.split(/\n/).map do |line|
      new_code_line = line.gsub(/\t/, '    ')
      orig_length = new_code_line.size + 3
      new_code_line.gsub!(/ /, "#{c(%i[x white on_black])} ")

      [
        "#{c(%i[x black])} ~#{c(%i[x white on_black])} ",
        new_code_line,
        c(%i[x white on_black]),
        ' ' * [@cols - orig_length, 0].max,
        xc
      ].join
    end.join("\n")
  end

  "#{c(%i[x blue]) + '--[ '}#{c(%i[x magenta])}#{leader}#{c(%i[x blue]) + ' ]' + '-'*(@cols-6-leader.size) + xc}\n#{hilite}\n#{c(%i[x blue]) + '--[ '}#{c(%i[x magenta])}END #{leader}#{c(%i[x blue]) + ' ]' + '-'*(@cols-10-leader.size) + xc}"
end

#list_headers(input) ⇒ Object



150
151
152
153
154
155
156
157
158
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
187
188
189
190
191
192
# File 'lib/mdless/converter.rb', line 150

def list_headers(input)
  h_adjust = highest_header(input) - 1
  input.gsub!(/^(#+)/) do |m|
    match = Regexp.last_match
    new_level = match[1].length - h_adjust
    if new_level > 0
      "#" * new_level
    else
      ''
    end
  end

  @headers = get_headers(input)
  last_level = 0
  headers_out = []
  @headers.each_with_index do |h,idx|

    level = h[0].length - 1
    title = h[1]

    if level - 1 > last_level
      level = last_level + 1
    end
    last_level = level

    subdoc = case level
    when 0
      ''
    when 1
      '- '
    when 2
      '+ '
    when 3
      '* '
    else
      '  '
    end
    line_no = '%2d: ' % (idx + 1)
    headers_out.push(%Q{#{line_no}#{c([:x, :black])}#{".."*level}#{c([:x, :yellow])}#{subdoc}#{title.strip}#{xc}}.strip)
  end

  @output += headers_out.join("\n")
end

#page(text, &callback) ⇒ Object



727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/mdless/converter.rb', line 727

def page(text, &callback)
  read_io, write_io = IO.pipe

  input = $stdin

  pid = Kernel.fork do
    write_io.close
    input.reopen(read_io)
    read_io.close

    # Wait until we have input before we start the pager
    IO.select [input]

    pager = which_pager
    begin
      exec(pager.join(' '))
    rescue SystemCallError => e
      @log.error(e)
      exit 1
    end
  end

  read_io.close
  write_io.write(text)
  write_io.close

  _, status = Process.waitpid2(pid)
  status.success?
end

#printoutObject



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

def printout
  out = @output.strip.split(/\n/).map {|p|
    p.wrap(@cols)
  }.join("\n")


  unless out && out.size > 0
    $stderr.puts "No results"
    Process.exit
  end

  out = cleanup_tables(out)
  out = clean_markers(out)
  out = out.gsub(/\n+{2,}/m,"\n\n") + "\n#{xc}\n\n"

  unless @options[:color]
    out.uncolor!
  end

  if @options[:pager]
    page("\n\n" + out)
  else
    $stdout.puts ("\n\n" + out)
  end
end


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

def update_inline_links(input)
  links = {}
  counter = 1
  input.gsub!(/(?<=\])\((.*?)\)/) do |m|
    links[counter] = $1.uncolor
    "[#{counter}]"
  end
end

#versionObject



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

def version
  "#{CLIMarkdown::EXECUTABLE_NAME} #{CLIMarkdown::VERSION}"
end

#which_pagerObject



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'lib/mdless/converter.rb', line 783

def which_pager
  pagers = [ENV['GIT_PAGER'], ENV['PAGER'],
            `git config --get-all core.pager || true`.split.first,
            'less', 'more', 'cat', 'pager']
  pagers.select! do |f|
    if f
      if f.strip =~ /[ |]/
        f
      else
      system "which #{f}", :out => File::NULL
      end
    else
      false
    end
  end

  pg = pagers.first
  args = case pg
  when 'more'
    ' -r'
  when 'less'
    ' -r'
  else
    ''
  end

  [pg, args]
end