Class: CLIMarkdown::Converter

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

Constant Summary

Constants included from Theme

Theme::THEME_DEFAULTS

Constants included from Colors

CLIMarkdown::Colors::COLORS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Theme

#load_theme, #load_theme_file

Methods included from Colors

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

Constructor Details

#initialize(args) ⇒ Converter

Returns a new instance of Converter.



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

def initialize(args)
  @log = Logger.new($stderr)
  @log.level = Logger::ERROR

  @options = {}
  config = File.expand_path('~/.config/mdless/config.yml')
  @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"

    @options[:color] ||= true
    opts.on('-c', '--[no-]color', 'Colorize output (default on)') do |c|
      @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
        @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

    @options[:local_images] ||= false
    @options[:remote_images] ||= false
    opts.on('-i', '--images=TYPE',
            'Include [local|remote (both)] images in output (requires chafa or imgcat, default NONE).') do |type|
      if exec_available('imgcat') || exec_available('chafa')
        if type =~ /^(r|b|a)/i
          @options[:local_images] = true
          @options[:remote_images] = true
        elsif type =~ /^l/i
          @options[:local_images] = true
        end
      else
        @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'
        @options[:local_images] = true
        @options[:remote_images] = true
      else
        @log.warn('images turned on but imgcat/chafa not found')
      end
    end

    @options[:syntax_higlight] ||= false
    opts.on('--syntax', 'Syntax highlight code blocks') do |p|
      @options[:syntax_higlight] = p
    end

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

    @options[:list] ||= false
    opts.on('-l', '--list', 'List headers in document and exit') do
      @options[:list] = true
    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[:section] ||= nil
    opts.on('-s', '--section=NUMBER[,NUMBER]',
            'Output only a headline-based section of the input (numeric from --list)') do |section|
      @options[:section] = section.split(/ *, */).map(&:strip).map(&:to_i)
    end

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

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

    @options[:width] = `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[:inline_footnotes] ||= false
    opts.on('--[no-]inline_footnotes',
            'Display footnotes immediately after the paragraph that references them') do |p|
      @options[:inline_footnotes] = p
    end
  end

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

  unless File.exist?(config)
    FileUtils.mkdir_p(File.dirname(config))
    File.open(config, 'w') do |f|
      opts = @options.dup
      opts.delete(:list)
      opts.delete(:section)
      f.puts YAML.dump(opts)
      warn "Config file saved to #{config}"
    end
  end

  @theme = load_theme(@options[:theme])
  @cols = @options[:width] - 2
  @output = ''
  @headers = []
  @setheaders = []

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

  renderer = Redcarpet::Render::Console.new
  renderer.theme = @theme
  renderer.cols = @cols
  renderer.log = @log
  renderer.options = @options

  markdown = Redcarpet::Markdown.new(renderer,
                                     autolink: true,
                                     fenced_code_blocks: true,
                                     footnotes: true,
                                     hard_wrap: false,
                                     highlight: true,
                                     lax_spacing: true,
                                     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|
      @log.info(%(Processing "#{file}"))
      @file = file
      renderer.file = @file
      begin
        input = IO.read(file).force_encoding('utf-8')
      rescue StandardError
        input = IO.read(file)
      end
      input.gsub!(/\r?\n/, "\n")
      if @options[:list]
        puts list_headers(input)
        Process.exit 0
      else
        @output = markdown.render(input)
      end
    end
    printout
  elsif !$stdin.isatty
    @file = nil
    begin
      input = $stdin.read.force_encoding('utf-8')
    rescue StandardError
      input = $stdin.read
    end
    input.gsub!(/\r?\n/, "\n")
    if @options[:list]
      puts list_headers(input)
      Process.exit 0
    else
      @output = markdown.render(input)
    end
    printout
  else
    warn 'No input'
    Process.exit 1
  end
end

Instance Attribute Details

#helpersObject (readonly)

Returns the value of attribute helpers.



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

def helpers
  @helpers
end

#logObject (readonly)

Returns the value of attribute log.



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

def log
  @log
end

Instance Method Details

#clean_markers(input) ⇒ Object



313
314
315
316
317
318
319
# File 'lib/mdless/converter.rb', line 313

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



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

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

#exec_available(cli) ⇒ Object



453
454
455
456
457
458
459
# File 'lib/mdless/converter.rb', line 453

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



330
331
332
333
334
335
336
337
338
339
# File 'lib/mdless/converter.rb', line 330

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



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 237

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



306
307
308
309
310
311
# File 'lib/mdless/converter.rb', line 306

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



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

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 = []
  @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>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



341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/mdless/converter.rb', line 341

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 = [@cols - orig_length, 0].max

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

#page(text, &callback) ⇒ Object



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

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



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/mdless/converter.rb', line 390

def printout
  out = @output.rstrip.split(/\n/).map do |p|
    p.wrap(@cols, color('text'))
  end.join("\n")

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

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

  out.uncolor! unless @options[:color]

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


321
322
323
324
325
326
327
328
# File 'lib/mdless/converter.rb', line 321

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

#versionObject



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

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

#which_pagerObject



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

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'
        @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