Class: Redcarpet::Render::Console
- Inherits:
-
Base
- Object
- Base
- Redcarpet::Render::Console
- Includes:
- CLIMarkdown::Colors, CLIMarkdown::Theme
- Defined in:
- lib/mdless/console.rb
Constant Summary collapse
- @@listitemid =
0
- @@listid =
0
- @@elementid =
0
- @@footnotes =
[]
- @@links =
[]
[]
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
-
#file ⇒ Object
writeonly
Sets the attribute file.
-
#headers ⇒ Object
Returns the value of attribute headers.
Instance Method Summary collapse
- #autolink(link, _) ⇒ Object
- #block_code(code, language) ⇒ Object
- #block_html(raw_html) ⇒ Object
- #block_quote(quote) ⇒ Object
- #code_bg(input, width) ⇒ Object
- #codespan(code) ⇒ Object
- #color(key) ⇒ Object
- #color_dd_def(input) ⇒ Object
- #color_footnote_def(idx) ⇒ Object
- #color_image_reference(idx, content) ⇒ Object
- #color_image_tag(link, title, alt_text) ⇒ Object
- #color_link(link, title, content) ⇒ Object
- #color_link_reference(_link, idx, content) ⇒ Object
- #color_links(input) ⇒ Object
- #color_list_item(indent, content, type, counter) ⇒ Object
- #color_meta(text) ⇒ Object
- #color_reference_link(link, title, content, image: false) ⇒ Object
- #color_table(input) ⇒ Object
- #color_tags(html) ⇒ Object
- #double_emphasis(text) ⇒ Object
- #emphasis(text) ⇒ Object
- #exec_available(cli) ⇒ Object
- #fix_colors(input) ⇒ Object
- #fix_equations(input) ⇒ Object
- #fix_image_attributes(input) ⇒ Object
- #fix_items(content, last_indent = 0, levels = [0]) ⇒ Object
- #fix_list_items(input) ⇒ Object
- #fix_list_spacing(input) ⇒ Object
- #fix_lists(input) ⇒ Object
- #footnote_def(text, idx) ⇒ Object
- #footnote_ref(text) ⇒ Object
- #footnotes(_text) ⇒ Object
- #get_headers(input) ⇒ Object
- #header(text, header_level) ⇒ Object
- #highlight(text) ⇒ Object
- #highlight_tags(input) ⇒ Object
- #highlight_wiki_links(input) ⇒ Object
- #hilite_code(code_block, language) ⇒ Object
- #hrule ⇒ Object
- #image(link, title, alt_text) ⇒ Object
- #indent_lines(input) ⇒ Object
- #insert_footnotes(input) ⇒ Object
- #linebreak ⇒ Object
- #link(link, title, content) ⇒ Object
- #list(contents, list_type) ⇒ Object
- #list_item(text, list_type) ⇒ Object
- #mmd_metadata_replace(input) ⇒ Object
- #mmd_transclude(input) ⇒ Object
- #nest_lists(input, indent = 0) ⇒ Object
- #normalize_indentation(line) ⇒ Object
- #paragraph(text) ⇒ Object
- #post_element ⇒ Object
- #postprocess(input) ⇒ Object
- #pre_element ⇒ Object
- #preprocess(input) ⇒ Object
- #raw_html(raw_html) ⇒ Object
- #reference_links(input) ⇒ Object
- #render_images(input) ⇒ Object
- #strikethrough(text) ⇒ Object
- #superscript(text) ⇒ Object
- #table(header, body) ⇒ Object
- #table_cell(content, alignment) ⇒ Object
- #table_header_row ⇒ Object
- #table_row(content) ⇒ Object
- #triple_emphasis(text) ⇒ Object
- #uncolor_grafs(text) ⇒ Object
- #x ⇒ Object
- #xc ⇒ Object
Methods included from CLIMarkdown::Theme
Methods included from CLIMarkdown::Colors
#blackout, #c, #last_color_code, #remove_pre_post, #size_clean, #uncolor, #uncolor!, #unpad, #wrap
Instance Attribute Details
#file=(value) ⇒ Object (writeonly)
Sets the attribute file
8 9 10 |
# File 'lib/mdless/console.rb', line 8 def file=(value) @file = value end |
#headers ⇒ Object
Returns the value of attribute headers.
7 8 9 |
# File 'lib/mdless/console.rb', line 7 def headers @headers end |
Instance Method Details
#autolink(link, _) ⇒ Object
327 328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/mdless/console.rb', line 327 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
197 198 199 |
# File 'lib/mdless/console.rb', line 197 def block_code(code, language) "\n\n#{hilite_code(code, language)}#{xc}\n\n" end |
#block_html(raw_html) ⇒ Object
216 217 218 |
# File 'lib/mdless/console.rb', line 216 def block_html(raw_html) "#{color('html color')}#{(raw_html)}#{xc}" end |
#block_quote(quote) ⇒ Object
201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/mdless/console.rb', line 201 def block_quote(quote) ret = "\n\n" quote.strip.wrap(MDLess.cols, color('blockquote color')).split(/\n/).each do |line| ret += [ color('blockquote marker color'), MDLess.theme['blockquote']['marker']['character'], color('blockquote color'), ' ', line, "\n" ].join('') end "#{ret}\n\n" end |
#code_bg(input, width) ⇒ Object
61 62 63 64 65 66 |
# File 'lib/mdless/console.rb', line 61 def code_bg(input, width) input.split(/\n/).map do |line| tail = line.uncolor.length < width ? "\u00A0" * (width - line.uncolor.length) : '' "#{x}#{line}#{tail}#{x}" end.join("\n") end |
#codespan(code) ⇒ Object
341 342 343 344 345 346 347 348 349 350 351 352 353 |
# File 'lib/mdless/console.rb', line 341 def codespan(code) out = [ pre_element, color('code_span marker'), MDLess.theme['code_span']['character'], color('code_span color'), code, color('code_span marker'), MDLess.theme['code_span']['character'], xc, post_element ].join end |
#color(key) ⇒ Object
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 |
# File 'lib/mdless/console.rb', line 170 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 |
#color_dd_def(input) ⇒ Object
912 913 914 915 916 917 918 919 920 921 922 923 |
# File 'lib/mdless/console.rb', line 912 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
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/mdless/console.rb', line 545 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_reference(idx, content) ⇒ Object
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 |
# File 'lib/mdless/console.rb', line 490 def color_image_reference(idx, content) [ pre_element, color('image brackets'), '[', color('image title'), content, color('image brackets'), '][', color('link url'), idx, color('image brackets'), ']', xc, post_element ].join end |
#color_image_tag(link, title, alt_text) ⇒ Object
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 |
# File 'lib/mdless/console.rb', line 424 def color_image_tag(link, title, alt_text) image = [ color('image brackets'), '[', color('image title'), alt_text, color('image brackets'), '](', color('image url'), link, title.nil? ? '' : %( "#{title}"), color('image brackets'), ')' ].join @@links << { link: image, url: link, title: title, content: alt_text, image: true } [ color('image bang'), '!', image, xc ].join end |
#color_link(link, title, content) ⇒ Object
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
# File 'lib/mdless/console.rb', line 405 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 |
#color_link_reference(_link, idx, content) ⇒ Object
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 |
# File 'lib/mdless/console.rb', line 455 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 |
#color_links(input) ⇒ Object
925 926 927 928 929 930 |
# File 'lib/mdless/console.rb', line 925 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_list_item(indent, content, type, counter) ⇒ Object
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 |
# File 'lib/mdless/console.rb', line 616 def color_list_item(indent, content, type, counter) out = case type when :unordered [ ' ' * indent, color('list bullet'), MDLess.theme['list']['ul_char'].strip, ' ', color('list color'), indent_lines(content).strip, xc ].join when :ordered [ ' ' * indent, color('list number'), "#{counter}. ", color('list color'), indent_lines(content).strip, xc ].join end if MDLess.[:at_tags] || MDLess.[:taskpaper] (out) else out end end |
#color_meta(text) ⇒ Object
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 807 808 809 810 |
# File 'lib/mdless/console.rb', line 743 def (text) input = text.dup input.clean_empty_lines! MDLess. = {} first_line = input.split("\n").first if first_line =~ /(?i-m)^---[ \t]*?$/ MDLess.log.info('Found YAML') # YAML in_yaml = true input.sub!(/(?i-m)^---[ \t]*\n(?<content>(?:[\s\S]*?))\n[-.]{3}[ \t]*\n/m) do m = Regexp.last_match MDLess.log.info('Processing YAML header') begin MDLess. = YAML.unsafe_load(m['content']).each_with_object({}) { |(k, v), h| h[k.downcase] = v } rescue Psych::DisallowedClass => e @log.error('Error reading YAML header') @log.error(e) MDLess. = {} rescue StandardError => e @log.error("StandardError: #{e}") end lines = m[0].split(/\n/) longest = lines.longest_element.length longest = longest < MDLess.cols ? longest + 1 : MDLess.cols lines.map do |line| if line =~ /^[-.]{3}\s*$/ line = "#{color('metadata marker')}#{'%' * longest}" else line.sub!(/^(.*?:)[ \t]+(\S)/, '\1 \2') line = "#{color('metadata marker')}% #{color('metadata color')}#{line}" end if (longest - line.uncolor.strip.length).positive? line += "\u00A0" * (longest - line.uncolor.strip.length) end line + xc end.join("\n") + "#{xc}\n" end end if !in_yaml && first_line =~ /(?i-m)^[\w ]+:\s+\S+/ MDLess.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 < MDLess.cols ? longest + 1 : MDLess.cols lines.map do |line| line.sub!(/^(.*?:)[ \t]+(\S)/, '\1 \2') parts = line.match(/^[ \t]*(\S.*?):[ \t]+(\S.*?)$/) if parts key = parts[1].gsub(/[^a-z0-9\-_]/i, '') value = parts[2].strip MDLess.[key] = value end line = "#{color('metadata marker')}%#{color('metadata color')}#{line}" if (longest - line.uncolor.strip.length).positive? line += "\u00A0" * (longest - line.uncolor.strip.length) end line + xc end.join("\n") + "#{xc}\n" end end input end |
#color_reference_link(link, title, content, image: false) ⇒ Object
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
# File 'lib/mdless/console.rb', line 473 def color_reference_link(link, title, content, image: false) [ color('link brackets'), '[', color('link text'), content, color('link brackets'), ']:', color('text'), ' ', image ? color('image url') : 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
519 520 521 |
# File 'lib/mdless/console.rb', line 519 def (html) html.gsub(%r{((?!<)</?\w+( [^>]+)?>)}, "#{color('html brackets')}\\1#{xc}") end |
#double_emphasis(text) ⇒ Object
355 356 357 358 359 360 361 362 363 364 365 |
# File 'lib/mdless/console.rb', line 355 def double_emphasis(text) [ pre_element, color('emphasis bold'), MDLess.theme['emphasis']['bold_character'], text, MDLess.theme['emphasis']['bold_character'], xc, post_element ].join end |
#emphasis(text) ⇒ Object
367 368 369 370 371 372 373 374 375 376 377 |
# File 'lib/mdless/console.rb', line 367 def emphasis(text) [ pre_element, color('emphasis italic'), MDLess.theme['emphasis']['italic_character'], text, MDLess.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.(cli)) File.executable?(File.(cli)) else TTY::Which.exist?(cli) end end |
#fix_colors(input) ⇒ Object
985 986 987 988 989 990 991 992 993 |
# File 'lib/mdless/console.rb', line 985 def fix_colors(input) input.gsub(/<<pre(?<id>\d+)>>(?<content>.*?)<<post\k<id>>>/m) do m = Regexp.last_match pre = m.pre_match.gsub(/<<pre(?<id>\d+)>>.*?<<post\k<id>>>/m, '') last_color = pre.last_color_code "#{fix_colors(m['content'])}#{last_color}" end.gsub(/<<(pre|post)\d+>>/, '') end |
#fix_equations(input) ⇒ Object
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 |
# File 'lib/mdless/console.rb', line 1069 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_image_attributes(input) ⇒ Object
837 838 839 |
# File 'lib/mdless/console.rb', line 837 def fix_image_attributes(input) input.gsub(/^( {0,3}\[[^^*>].*?\]: *\S+) +([^"].*?)$/, '\1') end |
#fix_items(content, last_indent = 0, levels = [0]) ⇒ Object
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 |
# File 'lib/mdless/console.rb', line 683 def fix_items(content, last_indent = 0, levels = [0]) content.gsub(%r{^(?<indent> *)<<listitem(?<id>\d+)-(?<type>(?:un)?ordered)>>(?<content>.*?)<</listitem\k<id>>>}m) do m = Regexp.last_match indent = m['indent'].length if m['type'].to_sym == :ordered if indent == last_indent levels[indent] ||= 0 levels[indent] += 1 elsif indent < last_indent levels[last_indent] = 0 levels[indent] += 1 last_indent = indent else levels[indent] = 1 last_indent = indent end end content = m['content'] =~ /<<listitem/ ? fix_items(m['content'], indent, levels) : m['content'] color_list_item(indent, uncolor_grafs(content), m['type'].to_sym, levels[indent]) end end |
#fix_list_items(input) ⇒ Object
707 708 709 710 711 712 |
# File 'lib/mdless/console.rb', line 707 def fix_list_items(input) input.gsub(%r{<<main(?<id>\d+)>>(?<content>.*?)<</main\k<id>>>}m) do m = Regexp.last_match fix_items(m['content']) end end |
#fix_list_spacing(input) ⇒ Object
651 652 653 |
# File 'lib/mdless/console.rb', line 651 def fix_list_spacing(input) input.gsub(/( *\n)+( *)<<listitem/, "\n\\2<<listitem").gsub(/( *\n){2,}/, "\n\n") end |
#fix_lists(input) ⇒ Object
645 646 647 648 649 |
# File 'lib/mdless/console.rb', line 645 def fix_lists(input) input = nest_lists(input) input = fix_list_spacing(input) fix_list_items(input) end |
#footnote_def(text, idx) ⇒ Object
564 565 566 |
# File 'lib/mdless/console.rb', line 564 def footnote_def(text, idx) @@footnotes[idx] = text end |
#footnote_ref(text) ⇒ Object
568 569 570 571 572 573 574 575 576 |
# File 'lib/mdless/console.rb', line 568 def footnote_ref(text) [ pre_element, color('footnote title'), "[^#{text}]", xc, post_element ].join('') end |
#footnotes(_text) ⇒ Object
535 536 537 538 539 540 541 542 543 |
# File 'lib/mdless/console.rb', line 535 def footnotes(_text) # [ # color('footnote note'), # text, # "\n", # xc, # ].join('') nil end |
#get_headers(input) ⇒ Object
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# File 'lib/mdless/console.rb', line 714 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
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 |
# File 'lib/mdless/console.rb', line 220 def header(text, header_level) pad = '' ansi = '' text.clean_header_ids! uncolored = text.uncolor.gsub(/<<(pre|post)\d+>>/, '') uncolored.sub!(/\[(.*?)\]\(.*?\)/, '[\1][xxx]') if MDLess.[:links] != :inline text_length = uncolored.length case header_level when 1 ansi = color('h1 color') pad = color('h1 pad') char = MDLess.theme['h1']['pad_char'] || '=' pad += text_length + 2 > MDLess.cols ? char * text_length : char * (MDLess.cols - (text_length + 1)) when 2 ansi = color('h2 color') pad = color('h2 pad') char = MDLess.theme['h2']['pad_char'] || '-' pad += text_length + 2 > MDLess.cols ? char * text_length : char * (MDLess.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 && MDLess.[:pager] == false ansi = "\e]1337;SetMark\a#{ansi}" end "\n\n#{xc}#{ansi}#{text} #{pad}#{xc}\n\n" end |
#highlight(text) ⇒ Object
393 394 395 |
# File 'lib/mdless/console.rb', line 393 def highlight(text) "#{pre_element}#{color('highlight')}#{text}#{xc}#{post_element}" end |
#highlight_tags(input) ⇒ Object
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 |
# File 'lib/mdless/console.rb', line 1094 def (input) tag_color = color('at_tags tag') value_color = color('at_tags value') input.gsub(/(?<pre>\s|m)(?<tag>@[^ \]:;.?!,("'\n]+)(?:(?<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 |
#highlight_wiki_links(input) ⇒ Object
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 |
# File 'lib/mdless/console.rb', line 1115 def highlight_wiki_links(input) input.gsub(/\[\[(.*?)\]\]/) do content = Regexp.last_match(1) [ pre_element, color('link brackets'), '[[', color('link text'), content, color('link brackets'), ']]', xc, post_element ].join end end |
#hilite_code(code_block, language) ⇒ Object
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 |
# File 'lib/mdless/console.rb', line 68 def hilite_code(code_block, language) longest_line = code_block.uncolor.split(/\n/).longest_element.length + 4 longest_line = longest_line > MDLess.cols ? MDLess.cols : longest_line # if MDLess.options[:syntax_higlight] # formatter = Rouge::Formatters::Terminal256 # lexer = if language # Object.const_get("Rouge::Lexers::#{language.capitalize}") rescue Rouge::Lexer.guess(source: code_block) # else # Rouge::Lexer.guess(source: code_block) # end # hilite = formatter.format(lexer.lex(code_block)) # hilite = xc + hilite.split(/\n/).map do |l| # [ # color('code_block marker'), # MDLess.theme['code_block']['character'], # "#{color('code_block bg')}#{l.rstrip}#{xc}" # ].join # end.join("\n").blackout(MDLess.theme['code_block']['bg']) + "#{xc}\n" # else # hilite = code_block.split(/\n/).map do |line| # [ # color('code_block marker'), # MDLess.theme['code_block']['character'], # color('code_block color'), # line, # xc # ].join # end.join("\n").blackout(MDLess.theme['code_block']['bg']) + "#{xc}\n" # end if MDLess.[:syntax_higlight] && !exec_available('pygmentize') MDLess.log.error('Syntax highlighting requested by pygmentize is not available') MDLess.[:syntax_higlight] = false end if MDLess.[:syntax_higlight] pyg = TTY::Which.which('pygmentize') lexer = language&.valid_lexer? ? "-l #{language}" : '-g' begin pygments_theme = MDLess.[:pygments_theme] || MDLess.theme['code_block']['pygments_theme'] unless pygments_theme.valid_pygments_theme? MDLess.log.error("Invalid Pygments theme #{pygments_theme}, defaulting to 'default' for highlighting") pygments_theme = 'default' end cmd = [ "#{pyg} -f terminal256", "-O style=#{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'), MDLess.theme['code_block']['character'], "#{color('code_block bg')}#{l}#{xc}" ].join end.join("\n").blackout(MDLess.theme['code_block']['bg']) + "#{xc}\n" end rescue StandardError => e MDLess.log.error(e) hilite = code_block end else hilite = code_block.split(/\n/).map do |line| [ color('code_block marker'), MDLess.theme['code_block']['character'], color('code_block color'), line, xc ].join end.join("\n").blackout(MDLess.theme['code_block']['bg']) + "#{xc}\n" end top_border = if language.nil? || language.empty? '-' * longest_line else len = (longest_line - 6 - language.length) > 0 ? longest_line - 6 - language.length : 0 "--[ #{language} ]#{"-" * len}" end [ xc, color('code_block border'), top_border, xc, "\n", color('code_block color'), code_bg(hilite.chomp, longest_line), "\n", color('code_block border'), '-' * longest_line, xc ].join end |
#hrule ⇒ Object
260 261 262 |
# File 'lib/mdless/console.rb', line 260 def hrule "\n\n#{color('hr color')}#{'_' * MDLess.cols}#{xc}\n\n" end |
#image(link, title, alt_text) ⇒ Object
397 398 399 |
# File 'lib/mdless/console.rb', line 397 def image(link, title, alt_text) "<<img>>#{link}||#{title}||#{alt_text}<</img>>" end |
#indent_lines(input) ⇒ Object
605 606 607 608 609 610 611 612 613 614 |
# File 'lib/mdless/console.rb', line 605 def indent_lines(input) return nil if input.nil? lines = input.split(/\n/) line1 = lines.shift pre = ' ' body = lines.map { |l| "#{pre}#{l.rstrip}" }.join("\n") "#{line1}\n#{body}" end |
#insert_footnotes(input) ⇒ Object
578 579 580 581 582 583 584 585 586 587 588 |
# File 'lib/mdless/console.rb', line 578 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\n" else line end end.join("\n") end |
#linebreak ⇒ Object
401 402 403 |
# File 'lib/mdless/console.rb', line 401 def linebreak " \n" end |
#link(link, title, content) ⇒ Object
508 509 510 511 512 513 514 515 516 517 |
# File 'lib/mdless/console.rb', line 508 def link(link, title, content) res = color_link(link, title&.strip, content&.strip) @@links << { link: res, url: link, title: title, content: content } res end |
#list(contents, list_type) ⇒ Object
590 591 592 593 |
# File 'lib/mdless/console.rb', line 590 def list(contents, list_type) @@listid += 1 "<<list#{@@listid}-#{list_type}>>#{contents}<</list#{@@listid}>>" end |
#list_item(text, list_type) ⇒ Object
595 596 597 598 599 600 601 602 603 |
# File 'lib/mdless/console.rb', line 595 def list_item(text, list_type) @@listitemid += 1 case list_type when :unordered "<<listitem#{@@listitemid}-#{list_type}>>#{text.strip}<</listitem#{@@listitemid}>>\n" when :ordered "<<listitem#{@@listitemid}-#{list_type}>>#{text.strip}<</listitem#{@@listitemid}>>\n" end end |
#mmd_metadata_replace(input) ⇒ Object
826 827 828 829 830 831 832 833 834 835 |
# File 'lib/mdless/console.rb', line 826 def (input) input.gsub(/\[%(.*?)\]/) do |m| key = Regexp.last_match(1) if MDLess..key?(key) MDLess.[key] else m end end end |
#mmd_transclude(input) ⇒ Object
812 813 814 815 816 817 818 819 820 821 822 823 824 |
# File 'lib/mdless/console.rb', line 812 def mmd_transclude(input) return input unless MDLess.file || MDLess..key?('transcludebase') input.gsub(/^{{(.*?)}}/) do |m| filename = Regexp.last_match(1).strip file = if MDLess..key?('transcludebase') File.join(File.(MDLess.['transcludebase']), filename) else File.join(File.dirname(MDLess.file), filename) end File.exist?(file) ? "\n\n#{mmd_transclude(IO.read(file).)}\n\n" : m end end |
#nest_lists(input, indent = 0) ⇒ Object
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 |
# File 'lib/mdless/console.rb', line 655 def nest_lists(input, indent = 0) input.gsub!(%r{<<list(?<id>\d+)-(?<type>.*?)>>(?<content>.*?)<</list\k<id>>>}m) do m = Regexp.last_match lines = m['content'].strip.split(/\n/) list = nest_lists(lines.map do |l| outdent = l.scan(%r{<</list\d+>>}).count indent += l.scan(/<<list\d+-.*?>>/).count indent -= outdent " #{l}" end.join("\n"), indent) next if list.nil? "<<main#{m['id']}>>#{list}<</main#{m['id']}>>\n\n" end input.gsub(%r{^(?<indent> +)<<main(?<id>\d+)>>(?<content>.*?)<</main\k<id>>>}m) do m = Regexp.last_match "#{m['indent']}#{m['content']}" end end |
#normalize_indentation(line) ⇒ Object
677 678 679 680 681 |
# File 'lib/mdless/console.rb', line 677 def normalize_indentation(line) line.gsub(/^([ \t]+)/) do |pre| pre.gsub(/\t/, ' ') end end |
#paragraph(text) ⇒ Object
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
# File 'lib/mdless/console.rb', line 264 def paragraph(text) text.scrub! out = if MDLess.[:preserve_linebreaks] "#{xc}#{text.gsub(/ +/, ' ').strip}#{xc}#{x}\n\n" else if text.uncolor =~ / {2,}$/ || text.uncolor =~ /^%/ "#{xc}#{text.gsub(/ +/, ' ').strip}#{xc}#{x}\n" else "#{xc}#{text.gsub(/ +/, ' ').gsub(/\n+(?![:-])/, ' ').strip}#{xc}#{x}\n\n" end end if MDLess.[:at_tags] || MDLess.[:taskpaper] (out) else out end end |
#post_element ⇒ Object
22 23 24 |
# File 'lib/mdless/console.rb', line 22 def post_element "<<post#{@@elementid}>>" end |
#postprocess(input) ⇒ Object
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 |
# File 'lib/mdless/console.rb', line 1132 def postprocess(input) input.scrub! input = highlight_wiki_links(input) if MDLess.[:wiki_links] if MDLess.[: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}") # render images input = render_images(input) if MDLess.[:local_images] # format links input = reference_links(input) if MDLess.[:links] == :reference || MDLess.[:links] == :paragraph # lists input = fix_lists(input) fix_colors(input) end |
#pre_element ⇒ Object
17 18 19 20 |
# File 'lib/mdless/console.rb', line 17 def pre_element @@elementid += 1 "<<pre#{@@elementid}>>" end |
#preprocess(input) ⇒ Object
841 842 843 844 845 846 847 848 849 850 851 852 853 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 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 |
# File 'lib/mdless/console.rb', line 841 def preprocess(input) input = (input) input = mmd_transclude(input) if MDLess.[:transclude] input = (input) if MDLess.[:mmd_metadata] input = fix_image_attributes(input) replaced_input = input.clone ## Replace setex headers with ATX replaced_input.gsub!(/^([^\n]+)\n={2,}\s*$/m, "# \\1\n") replaced_input.gsub!(/^([^\n]+?)\n-{2,}\s*$/m, "## \\1\n") @headers = get_headers(replaced_input) if MDLess.[:section] new_content = [] MDLess.log.info("Matching section(s) #{MDLess.[:section].join(', ')}") MDLess.[:section].each do |sect| comparison = MDLess.[:section][0].is_a?(String) ? :regex : :numeric in_section = false top_level = 1 input.split(/\n/).each_with_index do |graf, _idx| 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 (comparison == :regex && title.downcase =~ sect.downcase.to_rx) || (comparison == :numeric && 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 # deletions input.gsub!(/(?mi)(?<=\n|\A)~~(?<text>.*?)~~/) do m = Regexp.last_match "#{color('deletion')}#{m['text']}#{xc}" end # emojis input.gsub!(/(?<=\s|\A):(?<emoji>\S+):/) do m = Regexp.last_match emoji = CLIMarkdown::Emoji.convert_emoji(m['emoji']) "#{emoji}#{xc}" end input end |
#raw_html(raw_html) ⇒ Object
523 524 525 |
# File 'lib/mdless/console.rb', line 523 def raw_html(raw_html) "#{pre_element}#{color('html color')}#{(raw_html)}#{xc}#{post_element}" end |
#reference_links(input) ⇒ Object
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 |
# File 'lib/mdless/console.rb', line 932 def reference_links(input) grafs = input.split(/\n{2,}/) counter = 1 grafs.map! do |graf| return "\n" if graf =~ /^ *\n$/ links_added = false @@links.each do |link| next unless graf =~ /#{Regexp.escape(link[:link].gsub(/\n/, " "))}/ table = graf.uncolor =~ /^ *\|/ url = link[:url].uncolor content = link[:content] title = link[:title]&.uncolor image = link.key?(:image) && link[:image] ? true : false colored_link = image ? color_image_reference(counter, content) : color_link_reference(url, counter, content) if table diff = link[:link].gsub(/\n/, ' ').uncolor.length - colored_link.uncolor.gsub(/\n/, ' ').length graf.gsub!(/(?<=\|)([^\|]*?)#{Regexp.escape(link[:link].gsub(/\n/, " "))}(.*?)(?=\|)/) do before = Regexp.last_match(1) after = Regexp.last_match(2) surround = "#{before}#{after}" puts "**#{surround}**" diff += 2 if surround.uncolor.gsub(/#{CLIMarkdown::MDTableCleanup::PAD_CHAR}*/, '').strip.length.zero? "#{before}#{colored_link}#{after}#{' ' * diff}" end else graf.gsub!(/#{Regexp.escape(link[:link].gsub(/\n/, " "))}/, colored_link) end if MDLess.[:links] == :paragraph if links_added graf += "\n#{color_reference_link(url, title, counter, image: image)}" else graf = "#{graf}\n\n#{color_reference_link(url, title, counter, image: image)}" links_added = true end else @@footer_links << color_reference_link(url, title, counter, image: image) end counter += 1 end "\n#{graf}\n" end if MDLess.[:links] == :paragraph grafs.join("\n") else grafs.join("\n") + "\n#{@@footer_links.join("\n")}\n" end end |
#render_images(input) ⇒ Object
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 |
# File 'lib/mdless/console.rb', line 995 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')) && MDLess.[:local_images] if exec_available('imgcat') MDLess.log.info('Using imgcat for image rendering') elsif exec_available('chafa') MDLess.log.info('Using chafa for image rendering') end img_path = link if img_path =~ /^http/ && MDLess.[:remote_images] if exec_available('imgcat') MDLess.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 MDLess.log.error(e) end elsif exec_available('chafa') MDLess.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])}-- #{title} --" : '' result = pre + img + post Dir.chdir('..') FileUtils.rm_r '.mdless_tmp', force: true else MDLess.log.warn('No viewer for remote images') end else if img_path =~ %r{^[~/]} img_path = File.(img_path) elsif MDLess.file base = File.(File.dirname(MDLess.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
527 528 529 |
# File 'lib/mdless/console.rb', line 527 def strikethrough(text) "#{pre_element}#{color('deletion')}#{text}#{xc}#{post_element}" end |
#superscript(text) ⇒ Object
531 532 533 |
# File 'lib/mdless/console.rb', line 531 def superscript(text) "#{pre_element}#{color('super')}^#{text}#{xc}#{post_element}" end |
#table(header, body) ⇒ Object
303 304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/mdless/console.rb', line 303 def table(header, body) formatted = CLIMarkdown::MDTableCleanup.new([ header.to_s, table_header_row, "|\n", "#{body}\n\n" ].join('')) @header_row = [] res = formatted.to_md "#{color_table(res)}\n\n" # res end |
#table_cell(content, alignment) ⇒ Object
321 322 323 324 325 |
# File 'lib/mdless/console.rb', line 321 def table_cell(content, alignment) @header_row ||= [] @header_row << alignment if @table_cols && @header_row.count < @table_cols %(#{content} |) end |
#table_header_row ⇒ Object
288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/mdless/console.rb', line 288 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
316 317 318 319 |
# File 'lib/mdless/console.rb', line 316 def table_row(content) @table_cols = content.scan(/\|/).count %(#{content}\n) end |
#triple_emphasis(text) ⇒ Object
379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/mdless/console.rb', line 379 def triple_emphasis(text) [ pre_element, color('emphasis bold-italic'), MDLess.theme['emphasis']['italic_character'], MDLess.theme['emphasis']['bold_character'], text, MDLess.theme['emphasis']['bold_character'], MDLess.theme['emphasis']['italic_character'], xc, post_element ].join end |
#uncolor_grafs(text) ⇒ Object
282 283 284 |
# File 'lib/mdless/console.rb', line 282 def uncolor_grafs(text) text.gsub(/#{Regexp.escape(color("text"))}/, color('list color')) end |
#x ⇒ Object
30 31 32 |
# File 'lib/mdless/console.rb', line 30 def x c([:reset]) end |
#xc ⇒ Object
26 27 28 |
# File 'lib/mdless/console.rb', line 26 def xc x + color('text') end |