Class: CLIMarkdown::Converter

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

Constant Summary

Constants included from Colors

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

Instance Method Summary collapse

Methods included from Colors

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

Constructor Details

#initialize(args) ⇒ Converter

Returns a new instance of Converter.



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
141
142
143
144
145
146
147
148
149
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
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
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
266
267
268
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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/mdless/converter.rb', line 16

def initialize(args)
  MDLess.log.level = Logger::WARN

  MDLess.options = {}
  config = File.expand_path('~/.config/mdless/config.yml')
  MDLess.options = YAML.load(IO.read(config)) if File.exist?(config)

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

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

    opts.on('-d', '--debug LEVEL', 'Level of debug messages to output (1-4, 4 to see all messages)') do |level|
      if level.to_i.positive? && level.to_i < 5
        MDLess.log.level = 5 - level.to_i
      else
        puts 'Error: Debug level out of range (1-4)'
        Process.exit 1
      end
    end

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

    default(:local_images, false)
    default(:remote_images, false)
    opts.on('-i', '--images=TYPE',
            'Include [local|remote (both)|none] images in output (requires chafa or imgcat, default none).') do |type|
      if exec_available('imgcat') || exec_available('chafa')
        case type
        when /^(r|b|a)/i
          MDLess.options[:local_images] = true
          MDLess.options[:remote_images] = true
        when /^l/i
          MDLess.options[:local_images] = true
        when /^n/
          MDLess.options[:local_images] = false
          MDLess.options[:remote_images] = false
        end
      else
        MDLess.log.warn('images turned on but imgcat/chafa not found')
      end
    end

    opts.on('-I', '--all-images', 'Include local and remote images in output (requires imgcat or chafa)') do
      if exec_available('imgcat') || exec_available('chafa') # && ENV['TERM_PROGRAM'] == 'iTerm.app'
        MDLess.options[:local_images] = true
        MDLess.options[:remote_images] = true
      else
        MDLess.log.warn('images turned on but imgcat/chafa not found')
      end
    end

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

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

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

    default(:section, nil)
    opts.on('-s', '--section=NUMBER[,NUMBER]',
            'Output only a headline-based section of the input (numeric from --list or text match)') do |section|
      sections = section.split(/ *, */).map(&:strip)
      MDLess.options[:section] = sections.map do |sect|
        if sect =~ /^\d+$/
          sect.to_i
        else
          sect
        end
      end
    end

    default(:theme, 'default')
    opts.on('-t', '--theme=THEME_NAME', 'Specify an alternate color theme to load') do |theme|
      MDLess.options[:theme] = theme
    end

    default(:at_tags, false)
    opts.on('-@', '--at_tags', 'Highlight @tags and values in the document') do
      MDLess.options[:at_tags] = true
    end

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

    default(:width, TTY::Screen.cols)
    opts.on('-w', '--width=COLUMNS', 'Column width to format for (default: terminal width)') do |columns|
      MDLess.options[:width] = columns.to_i
    end
    cols = TTY::Screen.cols
    MDLess.options[:width] = cols if MDLess.options[:width] > cols

    default(:autolink, true)
    opts.on('--[no-]autolink', 'Convert bare URLs and emails to <links>') do |p|
      MDLess.options[:autolink] = p
    end

    opts.on('--config', "Open the config file in #{ENV['EDITOR'] || 'default editor'}") do
      raise 'No $EDITOR defined' unless ENV['EDITOR']

      `#{ENV['EDITOR']} '#{File.expand_path('~/.config/mdless/config.yml')}'`
    end

    opts.on('--edit-theme', ["Open the default or specified theme file in #{ENV['EDITOR'] || 'default editor'}. ",
                             "If theme doesn't exist, a new theme file will be populated and opened."].join) do
      raise 'No $EDITOR defined' unless ENV['EDITOR']

      theme = MDLess.options[:theme] =~ /default/ ? 'mdless' : MDLess.options[:theme]
      theme = File.expand_path("~/.config/mdless/#{theme}.theme")
      File.open(theme, 'w') { |f| f.puts(YAML.dump(MDLess.theme)) } unless File.exist?(theme)
      `#{ENV['EDITOR']} '#{theme}'`
    end

    default(:inline_footnotes, false)
    opts.on('--[no-]inline_footnotes',
            'Display footnotes immediately after the paragraph that references them') do |p|
      MDLess.options[:inline_footnotes] = p
    end

    default(:intra_emphasis, true)
    opts.on('--[no-]intra-emphasis', 'Parse emphasis inside of words (e.g. Mark_down_)') do |opt|
      MDLess.options[:intra_emphasis] = opt
    end

    default(:lax_spacing, true)
    opts.on('--[no-]lax-spacing', 'Allow lax spacing') do |opt|
      MDLess.options[:lax_spacing] = opt
    end

    default(:links, :inline)
    opts.on('--links=FORMAT',
            'Link style ([inline, reference, paragraph], default inline,
            "paragraph" will position reference links after each paragraph)') do |fmt|
      MDLess.options[:links] = case fmt
                         when /^:?r/i
                           :reference
                         when /^:?p/i
                           :paragraph
                         else
                           :inline
                         end
    end

    default(:preserve_linebreaks, false)
    opts.on('--[no-]linebreaks', 'Preserve line breaks') do |opt|
      MDLess.options[:preserve_linebreaks] = opt
    end

    default(:syntax_higlight, false)
    opts.on('--[no-]syntax', 'Syntax highlight code blocks') do |opt|
      MDLess.options[:syntax_higlight] = opt
    end

    MDLess.options[:taskpaper] = if MDLess.options[:taskpaper]
                             case MDLess.options[:taskpaper].to_s
                             when /^[ty1]/
                               true
                             when /^a/
                               :auto
                             else
                               false
                             end
                           else
                             false
                           end
    opts.on('--taskpaper=OPTION', 'Highlight TaskPaper format (true|false|auto)') do |tp|
      MDLess.options[:taskpaper] = case tp
                             when /^[ty1]/
                               true
                             when /^a/
                               :auto
                             else
                               false
                             end
    end

    default(:update_config, false)
    opts.on('--update_config', 'Update the configuration file with new keys and current command line options') do
      MDLess.options[:update_config] = true
    end

    default(:wiki_links, false)
    opts.on('--[no-]wiki-links', 'Highlight [[wiki links]]') do |opt|
      MDLess.options[:wiki_links] = opt
    end
  end

  begin
    optparse.parse!
  rescue OptionParser::ParseError => e
    warn "error: #{e.message}"
    exit 1
  end

  if !File.exist?(config) || MDLess.options[:update_config]
    FileUtils.mkdir_p(File.dirname(config))
    File.open(config, 'w') do |f|
      opts = MDLess.options.dup
      opts.delete(:list)
      opts.delete(:section)
      opts.delete(:update_config)
      opts = opts.keys.map(&:to_s).sort.map { |k| [k.to_sym, opts[k.to_sym]] }.to_h
      f.puts YAML.dump(opts)
      warn "Config file saved to #{config}"
    end
  end

  MDLess.cols = MDLess.options[:width] - 2

  @output = ''
  @headers = []
  @setheaders = []

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

  renderer = Redcarpet::Render::Console.new

  markdown = Redcarpet::Markdown.new(renderer,
                                     no_intra_emphasis: !MDLess.options[:intra_emphasis],
                                     autolink: MDLess.options[:autolink],
                                     fenced_code_blocks: true,
                                     footnotes: true,
                                     hard_wrap: false,
                                     highlight: true,
                                     lax_spacing: MDLess.options[:lax_spacing],
                                     quote: false,
                                     space_after_headers: false,
                                     strikethrough: true,
                                     superscript: true,
                                     tables: true,
                                     underline: false)

  if !args.empty?
    files = args.delete_if { |f| !File.exist?(f) }
    files.each do |file|
      MDLess.log.info(%(Processing "#{file}"))
      MDLess.file = file

      begin
        input = IO.read(file).force_encoding('utf-8')
      rescue StandardError
        input = IO.read(file)
      end
      raise 'Nil input' if input.nil?

      input.scrub!
      input.gsub!(/\r?\n/, "\n")

      if MDLess.options[:taskpaper] == :auto
        MDLess.options[:taskpaper] = if CLIMarkdown::TaskPaper.is_taskpaper?(input)
                                       MDLess.log.info('TaskPaper detected')
                                       true
                                     else
                                       false
                                     end
      end

      if MDLess.options[:list]
        if MDLess.options[:taskpaper]
          puts CLIMarkdown::TaskPaper.list_projects(input)
        else
          puts list_headers(input)
        end
        Process.exit 0
      else
        if MDLess.options[:taskpaper]
          input = input.color_meta(MDLess.cols)
          input = CLIMarkdown::TaskPaper.highlight(input)
          @output = input.highlight_tags
        else
          @output = markdown.render(input)
        end
      end
    end
    printout
  elsif !$stdin.isatty
    MDLess.file = nil
    input = $stdin.read.scrub
    input.gsub!(/\r?\n/, "\n")

    if MDLess.options[:taskpaper] == :auto
      MDLess.options[:taskpaper] = if CLIMarkdown::TaskPaper.is_taskpaper?(input)
                                     MDLess.log.info('TaskPaper detected')
                                     true
                                   else
                                     false
                                   end
    end

    if MDLess.options[:list]
      if MDLess.options[:taskpaper]
        puts CLIMarkdown::TaskPaper.list_projects(input)
      else
        puts list_headers(input)
      end
      Process.exit 0
    else
      if MDLess.options[:taskpaper]
        input = input.color_meta(MDLess.cols)
        input = CLIMarkdown::TaskPaper.highlight(input)
        @output = input.highlight_tags
      else
        @output = markdown.render(input)
      end
    end
    printout
  else
    warn 'No input'
    Process.exit 1
  end
end

Instance Method Details

#clean_markers(input) ⇒ Object



449
450
451
452
453
454
455
# File 'lib/mdless/converter.rb', line 449

def clean_markers(input)
  input.gsub!(/^(\e\[[\d;]+m)?[%~] ?/, '\1')
  # input.gsub!(/^(\e\[[\d;]+m)*>(\e\[[\d;]+m)?( +)/, ' \3\1\2')
  # input.gsub!(/^(\e\[[\d;]+m)*>(\e\[[\d;]+m)?/, '\1\2')
  input.gsub!(/(\e\[[\d;]+m)?@@@(\e\[[\d;]+m)?$/, '')
  input
end

#color(key) ⇒ Object



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

def color(key)
  val = nil
  keys = key.split(/[ ,>]/)
  if MDLess.theme.key?(keys[0])
    val = MDLess.theme[keys.shift]
  else
    MDLess.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
      MDLess.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

#default(option, default) ⇒ Object



12
13
14
# File 'lib/mdless/converter.rb', line 12

def default(option, default)
  MDLess.options[option] = default if MDLess.options[option].nil?
end

#exec_available(cli) ⇒ Object



593
594
595
596
597
598
599
# File 'lib/mdless/converter.rb', line 593

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

#find_color(line, nullable: false) ⇒ Object



466
467
468
469
470
471
472
473
474
475
# File 'lib/mdless/converter.rb', line 466

def find_color(line, nullable: false)
  return line if line.nil?

  colors = line.scan(/\e\[[\d;]+m/)
  if colors.size&.positive?
    colors[-1]
  else
    nullable ? nil : xc
  end
end

#get_headers(string) ⇒ Object



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

def get_headers(string)
  unless @headers && !@headers.empty?
    @headers = []
    input = string.sub(/(?i-m)^---[ \t]*\n([\s\S]*?)\n[-.]{3}[ \t]*\n/m, '')
    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

#highest_header(input) ⇒ Object



442
443
444
445
446
447
# File 'lib/mdless/converter.rb', line 442

def highest_header(input)
  @headers = get_headers(input)
  top = 6
  @headers.each { |h| top = h[0].length if h[0].length < top }
  top
end

#list_headers(input) ⇒ Object



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

def list_headers(input)
  h_adjust = highest_header(input) - 1
  input.gsub!(/^(#+)/) do
    m = Regexp.last_match
    new_level = m[1].length - h_adjust
    new_level.positive? ? '#' * new_level : ''
  end

  @headers = get_headers(input)
  last_level = 0
  headers_out = []
  len = (@headers.count + 1).to_s.length
  @headers.each_with_index do |h, idx|
    level = h[0].length - 1
    title = h[1]

    level = last_level + 1 if level - 1 > last_level

    last_level = level

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

  headers_out.join("\n")
end

#pad_max(block, eol = '') ⇒ Object



477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/mdless/converter.rb', line 477

def pad_max(block, eol='')
  block.split(/\n/).map do |l|
    new_code_line = l.gsub(/\t/, '    ')
    orig_length = new_code_line.size + 8 + eol.size
    pad_count = [MDLess.cols - orig_length, 0].max

    [
      new_code_line,
      eol,
      ' ' * [pad_count - 1, 0].max
    ].join
  end.join("\n")
end

#page(text, &callback) ⇒ Object



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

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
    MDLess.log.info("Using #{pager} as pager")
    begin
      exec(pager.join(' '))
    rescue SystemCallError => e
      MDLess.log.error(e)
      exit 1
    end
  end

  begin
    read_io.close
    write_io.write(text)
    write_io.close
  rescue SystemCallError
    exit 1
  end

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

#printoutObject



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

def printout
  if MDLess.options[:taskpaper]
    out = @output
  else
    out = @output.rstrip.split(/\n/).map do |p|
      p.wrap(MDLess.cols, color('text'))
    end.join("\n")
  end

  unless out.size&.positive?
    MDLess.log.warn 'No results'
    Process.exit
  end

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

  out.uncolor! unless MDLess.options[:color]

  if MDLess.options[:pager]
    page(out)
  else
    $stdout.print out.rstrip
  end
end


457
458
459
460
461
462
463
464
# File 'lib/mdless/converter.rb', line 457

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

#versionObject



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

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

#which_pagerObject



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

def which_pager
  # pagers = [ENV['PAGER'], ENV['GIT_PAGER']]
  pagers = [ENV['PAGER']]

  # if exec_available('git')
  #   git_pager = `git config --get-all core.pager || true`.split.first
  #   git_pager && pagers.push(git_pager)
  # end

  pagers.concat(['less', 'more', 'cat', 'pager'])

  pagers.select! do |f|
    if f
      if f.strip =~ /[ |]/
        f
      elsif f == 'most'
        MDLess.log.warn('most not allowed as pager')
        false
      else
        system "which #{f}", out: File::NULL, err: File::NULL
      end
    else
      false
    end
  end

  pg = pagers.first
  args = case pg
         # when 'delta'
         #   ' --pager="less -Xr"'
         when 'less'
           ' -Xr'
         # when 'bat'
         #   ' -p --pager="less -Xr"'
         else
           ''
         end

  [pg, args]
end