forked from axiros/terminal_markdown_viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdownviewer.py
executable file
·1424 lines (1195 loc) · 44.7 KB
/
markdownviewer.py
1
2
3
4
5
6
7
8
9
10
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
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
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
718
719
720
721
722
723
724
725
726
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
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
"""_
# Usage:
mdv [options] [MDFILE]
# Options:
-t THEME : Key within the color ansi_table.json. 'random' accepted.
-T C_THEME: Theme for code highlight. If not set: Using THEME.
-l : Light background (not yet supported)
-u STYL : Link Style (it=inline table=default, h=hide, i=inline)
-L : Backwards compatible shortcut for '-u i'
-x : Do not try guess code lexer (guessing is a bit slow)
-X Lexer : Default lexer name (default: python). Set -x to use it always.
-f FROM : Display FROM given substring of the file.
-m : Monitor file for changes and redisplay FROM given substring
-M DIR : Monitor directory for markdown file changes
-c COLS : Fix columns to this (default: your terminal width)
-C MODE : Sourcecode highlighting mode
-A : Strip all ansi (no colors then)
-b TABL : Set tab_length to sth. different than 4 [default: 4]
-i : Show theme infos with output
-H : Print html version
-h : Show help
# Details
### **MDFILE**
Filename to markdownfile or '-' for pipe mode (no termwidth auto dedection then)
### **-c COLS**: Columns
We use stty tool to derive terminal size. If you pipe into mdv we use 80 cols.
You can force the columns used via `-c`.
If you export `$width`, this has precedence over `$COLUMNS`.
### **-b TABL**: Tablength
Setting tab_length away from 4 violates [markdown](https://pythonhosted.org/Markdown/).
But since many editors interpret such source we allow it via that flag.
### **-f FROM**: Partial Display
FROM may contain max lines to display, seperated by colon.
Example:
-f 'Some Head:10' -> displays 10 lines after 'Some Head'
If the substring is not found we set it to the *first* character of the file -
resulting in output from the top (if your terminal height can be derived
correctly through the stty cmd).
## Themes
Environ variables `$MDV_THEME` and `$MDV_CODE_THEME` are understood:
```bash
export MDV_THEME='729.8953'; mdv foo.md
```
### Theme rollers:
mdv -T all: All available code styles on the given file.
mdv -t all: All available md styles on the given file.
If file is not given we use a short sample file.
So to see all code hilite variations with a given theme:
Say `C_THEME=all` and fix `THEME`
Setting both to all will probably spin your beach ball...
## Inline Usage (mdv as lib)
Call the main function with markdown string at hand to get a
formatted one back. Sorry then for no Py3 support, accepting PRs if they
don't screw Py2.
## Source Code Highlighting
Set -C <all|code|doc|mod> for source code highlighting of source code files.
Mark inline markdown with a '_' following the docstring beginnings.
- all: Show markdown docstrings AND code (default, if you say e.g. -C.)
- code: Only Code
- doc: Only docstrings with markdown
- mod: Only the module level docstring
## File Monitor:
If FROM is not found we display the whole file.
## Directory Monitor:
We check only text file changes, monitoring their size.
By default .md, .mdown, .markdown files are checked but you can change like
`-M 'mydir:py,c,md,'` where the last empty substrings makes mdv also monitor
any file w/o extension (like 'README').
### Running actions on changes:
If you append to `-M` a `'::<cmd>'` we run the command on any change detected
(sync, in foreground).
The command can contain placeholders:
_fp_ # Will be replaced with filepath
_raw_ # Will be replaced with the base64 encoded raw content
of the file
_pretty_ # Will be replaced with the base64 encoded prettyfied output
Like: `mdv -M './mydocs:py,md::open "_fp_"'` which calls the open command
with argument the path to the changed file.
"""
import sys
# grrr
PY3 = True if sys.version_info[0] > 2 else False
import io
import os
import textwrap
is_app = 0
# code analysis for hilite:
try:
from pygments import lex, token
from pygments.lexers import get_lexer_by_name
from pygments.lexers import guess_lexer as pyg_guess_lexer
have_pygments = True
except ImportError:
have_pygments = False
import time
import markdown
import re
from docopt import docopt
import markdown.util
from markdown.util import etree
from markdown.extensions.tables import TableExtension
from random import randint
from tabulate import tabulate
from json import loads
from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension, fenced_code
try:
from html.parser import HTMLParser
except ImportError as ex:
from HTMLParser import HTMLParser
envget = os.environ.get
# adaptions:
if PY3:
unichr = chr
# ---------------------------------------------------------------------- Config
hr_sep, txt_block_cut, code_pref, list_pref, bquote_pref, hr_ends = \
'─', '✂', '| ', '- ', '|', '◈'
# ansi cols (default):
# R: Red (warnings), L: low visi, BG: background, BGL: background light, C=code
# H1 - H5 = the theme, the numbers are the ansi color codes:
H1, H2, H3, H4, H5, R, L, BG, BGL, T, TL, C = \
231, 153, 117, 109, 65, 124, 59, 16, 188, 188, 59, 102
# Code (C is fallback if we have no lexer). Default: Same theme:
CH1, CH2, CH3, CH4, CH5 = H1, H2, H3, H4, H5
code_hl = {"Keyword": 'CH3',
"Name": 'CH1',
"Comment": 'L',
"String": 'CH4',
"Error": 'R',
"Number": 'CH4',
"Operator": 'CH5',
"Generic": 'CH2'
}
admons = {'note': 'H3',
'warning': 'R',
'attention': 'H1',
'hint': 'H4',
'summary': 'H1',
'hint': 'H4',
'question': 'H5',
'danger': 'R',
'dev': 'H5',
'hint': 'H4',
'caution': 'H2'
}
link_start = u'①'
link_start_ord = ord(link_start)
def_lexer = 'python'
guess_lexer = True
# also global. but not in use, BG handling can get pretty involved, to do with
# taste, since we don't know the term backg....:
background = BG
# hirarchical indentation by:
left_indent = ' '
# normal text color:
color = T
# it: inline table, h: hide, i: inline
show_links = 'it'
# columns(!) - may be set to smaller width:
# could be exported by the shell, normally not in subprocesses:
# zsh does not allow to override COLUMNS ! Thats why we also respect $width:
term_columns, term_rows = envget('width', envget('COLUMNS')), envget('LINES')
if not term_columns and not '-c' in sys.argv:
try:
term_rows, term_columns = os.popen(
'stty size 2>/dev/null', 'r').read().split()
term_columns, term_rows = int(term_columns), int(term_rows)
except:
if '-' not in sys.argv:
print('!! Could not derive your terminal width !!')
term_columns, term_rows = int(term_columns or 80), int(term_rows or 200)
# could be given, otherwise read from ansi_tables.json:
themes = {}
# sample for the theme roller feature:
md_sample = ''
# dir monitor recursion max:
mon_max_files = 1000
# ------------------------------------------------------------------ End Config
import logging
md_logger = logging.getLogger('MARKDOWN')
md_logger.setLevel(logging.WARNING)
# below here you have to *know* what u r doing... (since I didn't too much)
dir_mon_filepath_ph = '_fp_'
dir_mon_content_raw = '_raw_'
dir_mon_content_pretty = '_pretty_'
def read_themes():
if not themes:
with open(j(mydir, 'ansi_tables.json')) as f:
themes.update(loads(f.read()))
return themes
# can unescape:
html_parser = HTMLParser()
you_like = 'You like this theme?'
def make_sample():
""" Generate the theme roller sample markdown """
if md_sample:
# user has set another:
return md_sample
_md = []
for hl in range(1, 7):
_md.append('#' * hl + ' ' + 'Header %s' % hl)
this = open(__file__).read().split('"""', 3)[2].splitlines()[:10]
_md.append('```\n""" Test """\n%s\n```' % '\n'.join(this).strip())
_md.append("""
| Tables | Fmt |
| -- | -- |
| !!! hint: wrapped | 0.1 **strong** |
""")
for ad in list(admons.keys())[:1]:
_md.append('!!! %s: title\n this is a %s\n' % (ad, ad.capitalize()))
# 'this theme' replaced in the roller (but not at mdv w/o args):
globals()['md_sample'] = \
'\n'.join(_md) + '\n----\n!!! question: %s' % you_like
code_hl_tokens = {}
def build_hl_by_token():
if not have_pygments:
return
# replace code strs with tokens:
for k, col in list(code_hl.items()):
code_hl_tokens[getattr(token, k)] = globals()[col]
def clean_ansi(s):
# if someone does not want the color foo:
ansi_escape = re.compile(r'\x1b[^m]*m')
return ansi_escape.sub('', s)
# markers: tab is 09, omit that
code_start, code_end = '\x07', '\x08'
stng_start, stng_end = '\x16', '\x10'
link_start, link_end = '\x17', '\x18'
emph_start, emph_end = '\x11', '\x12'
punctuationmark = '\x13'
fenced_codemark = '\x14'
hr_marker = '\x15'
no_split = '\x19'
def j(p, f):
return os.path.join(p, f)
mydir = os.path.realpath(__file__).rsplit(os.path.sep, 1)[0]
def set_theme(theme=None, for_code=None, theme_info=None):
""" set md and code theme """
# for md the default is None and should return the 'random' theme
# for code the default is 'default' and should return the default theme.
# historical reasons...
dec = {False: {'dflt': None, 'on_dflt': 'random',
'env': ('MDV_THEME', 'AXC_THEME')},
True: {'dflt': 'default', 'on_dflt': None,
'env': ('MDV_CODE_THEME', 'AXC_CODE_THEME')}}
dec = dec[bool(for_code)]
try:
if theme == dec['dflt']:
for k in dec['env']:
ek = envget(k)
if ek:
theme = ek
break
if theme == dec['dflt']:
theme = dec['on_dflt']
if not theme:
return
theme = str(theme)
# all the themes from here:
themes = read_themes()
if theme == 'random':
rand = randint(0, len(themes) - 1)
theme = list(themes.keys())[rand]
t = themes.get(theme)
if not t or len(t.get('ct')) != 5:
# leave defaults:
return
_for = ''
if for_code:
_for = ' (code)'
if theme_info:
print(low('theme%s: %s (%s)' % (_for, theme, t.get('name'))))
t = t['ct']
cols = (t[0], t[1], t[2], t[3], t[4])
if for_code:
global CH1, CH2, CH3, CH4, CH5
CH1, CH2, CH3, CH4, CH5 = cols
else:
global H1, H2, H3, H4, H5
# set the colors now from the ansi codes in the theme:
H1, H2, H3, H4, H5 = cols
finally:
if for_code:
build_hl_by_token()
def style_ansi(raw_code, lang=None):
""" actual code hilite """
def lexer_alias(n):
# not found:
if n == 'markdown': return 'md'
return n
lexer = 0
if lang:
try:
lexer = get_lexer_by_name(lexer_alias(lang))
except ValueError:
print(col(R, 'Lexer for %s not found' % lang))
if not lexer:
try:
if guess_lexer:
# takes a long time!
lexer = pyg_guess_lexer(raw_code)
except:
pass
if not lexer:
for l in def_lexer, 'yaml', 'python', 'c':
try:
lexer = get_lexer_by_name(lexer_alias(l))
break
except:
# OUR def_lexer (python) was overridden,but not found.
# still we should not fail. lets use yaml. or python:
continue
tokens = lex(raw_code, lexer)
cod = []
for t, v in tokens:
if not v:
continue
_col = code_hl_tokens.get(t) or C # color
cod.append(col(v, _col))
return ''.join(cod)
def col_bg(c):
""" colorize background """
return '\033[48;5;%sm' % c
def col(s, c, bg=0, no_reset=0):
"""
print col('foo', 124) -> red 'foo' on the terminal
c = color, s the value to colorize """
reset = reset_col
if no_reset:
reset = ''
for _strt, _end, _col in ((code_start, code_end, H2),
(stng_start, stng_end, H2),
(link_start, link_end, H2),
(emph_start, emph_end, H3)):
if _strt in s:
uon, uoff = '', ''
if _strt == link_start:
uon, uoff = '\033[4m', '\033[24m'
s = s.replace(_strt, col('', _col, bg=background, no_reset=1) + uon)
s = s.replace(_end, uoff + col('', c, no_reset=1))
s = '\033[38;5;%sm%s%s' % (c, s, reset)
if bg:
pass
# s = col_bg(bg) + s
return s
reset_col = '\033[0m'
def low(s):
# shorthand
return col(s, L)
def plain(s, **kw):
# when a tag is not found:
return col(s, T)
def sh(out):
''' debug tool'''
for l in out:
print(l)
# --------------------------------------------------------- Tag formatter funcs
class Tags:
""" can be overwritten in derivations. """
# @staticmethod everywhere is eye cancer, so we instantiate it later
def h(_, s, level):
return '\n%s%s' % (low('#' * 0), col(s, globals()['H%s' % level]))
def h1(_, s, **kw): return _.h(s, 1)
def h2(_, s, **kw): return _.h(s, 2)
def h3(_, s, **kw): return _.h(s, 3)
def h4(_, s, **kw): return _.h(s, 4)
def h5(_, s, **kw): return _.h(s, 5)
def h6(_, s, **kw): return _.h(s, 5) # have not more then 5
def h7(_, s, **kw): return _.h(s, 5) # cols in the themes, low them all
def h8(_, s, **kw): return _.h(s, 5)
def p (_, s, **kw): return col(s, T)
def a (_, s, **kw): return col(s, L)
def hr(_, s, **kw):
# we want nice line seps:
hir = kw.get('hir', 1)
ind = (hir - 1) * left_indent
s = e = col(hr_ends, globals()['H%s' % hir])
return low('\n%s%s%s%s%s\n' % (ind, s, hr_marker, e, ind))
def code(_, s, from_fenced_block=None, **kw):
""" md code AND ``` style fenced raw code ends here"""
lang = kw.get('lang')
if not from_fenced_block:
s = ('\n' + s).replace('\n ', '\n')[1:]
# funny: ":-" confuses the tokenizer. replace/backreplace:
raw_code = s.replace(':-', '\x01--')
if have_pygments:
s = style_ansi(raw_code, lang=lang)
# outest hir is 2, use it for fenced:
ind = ' ' * kw.get('hir', 2)
# if from_fenced_block: ... WE treat equal.
# shift to the far left, no matter the indent (screenspace matters):
firstl = s.split('\n')[0]
del_spaces = ' ' * (len(firstl) - len(firstl.lstrip()))
s = ('\n' + s).replace('\n%s' % del_spaces, '\n')[1:]
# we want an indent of one and low vis prefix. this does it:
code_lines = ('\n' + s).splitlines()
prefix = ('\n%s%s %s' % (ind, low(code_pref), col('', C, no_reset=1)))
code_lines.pop() if code_lines[-1] == u'\x1b[0m' else None
code = prefix.join(code_lines)
code = code.replace('\x01--', ':-')
return code + '\n' + reset_col
def is_text_node(el):
""" """
s = str(etree.tostring(el))
# strip our tag:
html = s.split('<%s' % el.tag, 1)[1].split('>', 1)[1].rsplit('>', 1)[0]
# do we start with another tagged child which is NOT in inlines:?
if not html.startswith('<'):
return 1, html
for inline in ('<a', '<em>', '<code>', '<strong>'):
if html.startswith(inline):
return 1, html
return 0, 0
# ----------------------------------------------------- Text Termcols Adaptions
def rewrap(el, t, ind, pref):
""" Reasonably smart rewrapping checking punctuations """
cols = max(term_columns - len(ind + pref), 5)
if el.tag == 'code' or len(t) <= cols:
return t
# this is a code replacement marker of markdown.py. Don't split the
# replacement marker:
if t.startswith('\x02') and t.endswith('\x03'):
return t
dedented = textwrap.dedent(t).strip()
ret = textwrap.fill(dedented, width=cols)
return ret
# forgot why I didn't use textwrap from the beginning. In case there is a
# reason I leave the old code here:
# edit: think it was because of ansi code unawareness of textwrap.
# wrapping:
# we want to keep existing linebreaks after punctuation
# marks. the others we rewrap:
#puncs = ',', '.', '?', '!', '-', ':'
#parts = []
#origp = t.splitlines()
#if len(origp) > 1:
# pos = -1
# while pos < len(origp) - 1:
# pos += 1
# # last char punctuation?
# if origp[pos][-1] not in puncs and \
# not pos == len(origp) - 1:
# # concat:
# parts.append(origp[pos].strip() + ' ' + origp[pos + 1].strip())
# pos += 1
# else:
# parts.append(origp[pos].strip())
# t = '\n'.join(parts)
## having only the linebreaks with puncs before we rewrap
## now:
#parts = []
#for part in t.splitlines():
# parts.extend([part[i:i+cols] for i in range(0, len(part), cols)])
## last remove leading ' ' (if '\n' came just before):
#t = []
#for p in parts:
# t.append(p.strip())
#return '\n'.join(t)
def split_blocks(text_block, w, cols, part_fmter=None):
""" splits while multiline blocks vertically (for large tables) """
ts = []
for line in text_block.splitlines():
parts = []
# make equal len:
line = line.ljust(w, ' ')
# first part full width, others a bit indented:
parts.append(line[:cols])
scols = cols - 2
# the txt_block_cut in low makes the whole secondary tables
# low. which i find a feature:
# if you don't want it remove the col(.., L)
parts.extend([' ' + col(txt_block_cut, L, no_reset=1) +
line[i:i + scols]
for i in range(cols, len(line), scols)])
ts.append(parts)
blocks = []
for block_part_nr in range(len(ts[0])):
tpart = []
for lines_block in ts:
tpart.append(lines_block[block_part_nr])
if part_fmter:
part_fmter(tpart)
tpart[1] = col(tpart[1], H3)
blocks.append('\n'.join(tpart))
t = '\n'.join(blocks)
return('\n%s\n' % t)
# ---------------------------------------------------- Create the treeprocessor
def replace_links(el, html):
'''digging through inline "<a href=..."
'''
parts = html.split('<a ')
if len(parts) == 1:
return None, html
links_list, cur_link = [], 0
links = [l for l in el.getchildren() if 'href' in l.keys()]
if not len(parts) == len(links) + 1:
# there is an html element within which we don't support,
# e.g. blockquote
return None, html
cur = ''
while parts:
cur += parts.pop(0).rsplit('</a>')[-1]
if not parts:
break
# indicating link formatting start:
cur += link_start
# the 'a' xml element:
link = links[cur_link]
# bug in the markdown api? link el is not providing inlines!!
# -> get them from the html:
#cur += link.text or ''
cur += parts[0].split('>', 1)[1].split('</a', 1)[0] or ''
cur += link_end
if show_links != 'h':
if show_links == 'i':
cur += low('(%s)' % link.get('href',''))
else: # inline table (it)
# we build a link list, add the number like ① :
cur += '%s ' % unichr(link_start_ord + cur_link)
links_list.append(link.get('href', ''))
cur_link += 1
return links_list, cur
class AnsiPrinter(Treeprocessor):
header_tags = ('h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8')
def run(self, doc):
tags = Tags()
def get_attr(el, attr):
for c in list(el.items()):
if c[0] == attr:
return c[1]
return ''
def formatter(el, out, hir=0, pref='', parent=None):
"""
Main recursion.
debugging:
if el.tag == 'xli':
import pdb; pdb.set_trace()
#for c in el.getchildren()[0].getchildren(): print c.text, c
print '---------'
print el, el.text
print '---------'
"""
if el.tag == 'br':
out.append('\n')
return
#for c in el.getchildren(): print c.text, c
links_list, is_txt_and_inline_markup = None, 0
if el.tag == 'blockquote':
for el1 in el.getchildren():
iout = []
formatter(el1, iout, hir+2, parent=el)
pr = col(bquote_pref, H1)
sp = ' ' * (hir + 2)
for l in iout:
for l1 in l.splitlines():
if sp in l1:
l1 = ''.join(l1.split(sp, 1))
out.append(pr + l1)
return
if el.tag == 'hr':
return out.append(tags.hr('', hir=hir))
if el.text or \
el.tag == 'p' or \
el.tag == 'li' or \
el.tag.startswith('h'):
el.text = el.text or ''
# <a attributes>foo... -> we want "foo....". Is it a sub
# tag or inline text?
is_txt_and_inline_markup, html = is_text_node(el)
if is_txt_and_inline_markup:
# foo: \nbar -> will be seing a foo:<br>bar with
# mardkown.py. Code blocks are already quoted -> no prob.
html = html.replace('<br />', '\n')
# strip our own closing tag:
t = html.rsplit('<', 1)[0]
links_list, t = replace_links(el, html=t)
for tg, start, end in (('<code>', code_start, code_end),
('<strong>', stng_start, stng_end),
('<em>', emph_start, emph_end)):
t = t.replace('%s' % tg, start)
close_tag = '</%s' % tg[1:]
t = t.replace(close_tag, end)
t = html_parser.unescape(t)
else:
t = el.text
t = t.strip()
admon = ''
pref = body_pref = ''
if t.startswith('!!! '):
# we allow admons with spaces. so check for startswith:
_ad = None
for k in admons:
if t[4:].startswith(k):
_ad = k
break
# not found - markup using hte first one's color:
if not _ad:
k = t[4:].split(' ', 1)[0]
admons[k] = admons.values()[0]
pref = body_pref = '┃ '
pref += (k.capitalize())
admon = k
t = t.split(k, 1)[1]
# set the parent, e.g. nrs in ols:
if el.get('pref'):
# first line pref, like '-':
pref = el.get('pref')
# next line prefs:
body_pref = ' ' * len(pref)
el.set('pref', '')
ind = left_indent * hir
if el.tag in self.header_tags:
# header level:
hl = int(el.tag[1:])
ind = ' ' * (hl - 1)
hir += hl
t = rewrap(el, t, ind, pref)
# indent. can color the prefixes now, no more len checks:
if admon:
out.append('\n')
pref = col(pref, globals()[admons[admon]])
body_pref = col(body_pref, globals()[admons[admon]])
if pref:
# different color per indent:
h = globals()['H%s' % (((hir - 2) % 5) + 1)]
if pref == list_pref:
pref = col(pref, h)
elif pref.split('.', 1)[0].isdigit():
pref = col(pref, h)
t = ('\n' + ind + body_pref).join((t).splitlines())
t = ind + pref + t
# headers outer left: go sure.
# actually... NO. commented out.
# if el.tag in self.header_tags:
# pref = ''
# calling the class Tags functions
# IF the parent is li and we have a linebreak then the renderer
# delivers <li><p>foo</p> instead of <li>foo, i.e. we have to
# omit the linebreak and append the text of p to the previous
# result, (i.e. the list separator):
tag_fmt_func = getattr(tags, el.tag, plain)
if type(parent) == type(el) and parent.tag == 'li' and \
not parent.text and el.tag == 'p':
_out = tag_fmt_func(t.lstrip(), hir=hir)
out[-1] += _out
else:
out.append(tag_fmt_func(t, hir=hir))
if admon:
out.append('\n')
if links_list:
i = 1
for l in links_list:
out.append(low('%s[%s] %s' % (ind, i, l)))
i += 1
# have children?
# nr for ols:
if is_txt_and_inline_markup:
if el.tag == 'li':
childs = el.getchildren()
for nested in 'ul', 'ol':
if childs and childs[-1].tag == nested:
ul = childs[-1]
# do we have a nested sublist? the li was inline
# formattet,
# split all from <ul> off and format it as own tag:
# (ul always at the end of an li)
out[-1] = out[-1].split('<%s>' % nested, 1)[0]
formatter(ul, out, hir + 1, parent=el)
return
if el.tag == 'table':
# processed all here, in one sweep:
# markdown ext gave us a xml tree from the ascii,
# our part here is the cell formatting and into a
# python nested list, then tabulate spits
# out ascii again:
def borders(t):
t[0] = t[-1] = low(t[0].replace('-', '─'))
def fmt(cell, parent):
""" we just run the whole formatter - just with a fresh new
result list so that our 'out' is untouched """
_cell = []
formatter(cell, out=_cell, hir=0, parent=parent)
return '\n'.join(_cell)
t = []
for he_bo in 0, 1:
for Row in el[he_bo].getchildren():
row = []
t.append(row)
for cell in Row.getchildren():
row.append(fmt(cell, row))
cols = term_columns
# good ansi handling:
tbl = tabulate(t)
# do we have right room to indent it?
# first line is seps, so no ansi esacapes foo:
w = len(tbl.split('\n', 1)[0])
if w <= cols:
t = tbl.splitlines()
borders(t)
# center:
ind = (cols - w) / 2
# too much:
ind = hir
tt = []
for line in t:
tt.append('%s%s' % (ind * left_indent, line))
out.extend(tt)
else:
# TABLE CUTTING WHEN NOT WIDTH FIT
# oh snap, the table bigger than our screen. hmm.
# hey lets split into vertical parts:
# but len calcs are hart, since we are crammed with esc.
# seqs.
# -> get rid of them:
tc = []
for row in t:
tc.append([])
l = tc[-1]
for cell in row:
l.append(clean_ansi(cell))
# again sam:
# note: we had to patch it, it inserted '\n' within cells!
table = tabulate(tc)
out.append(
split_blocks(table, w, cols, part_fmter=borders))
return
nr = 0
for c in el:
if el.tag == 'ul': # or el.tag == 'li':
c.set('pref', list_pref)
elif el.tag == 'ol':
nr += 1
c.set('pref', str(nr) + '. ')
# handle the ``` style unindented code blocks -> parsed as p:
formatter(c, out, hir + 1, parent=el)
# if el.tag == 'ul' or el.tag == 'ol' and not out[-1] == '\n':
# out.append('\n')
out = []
formatter(doc, out)
self.markdown.ansi = '\n'.join(out)
def set_hr_widths(result):
"""
We want the hrs indented by hirarchy...
A bit 2 much effort to calc, maybe just fixed with 10
style seps would have been enough visually:
◈────────────◈
"""
# set all hrs to max width of text:
mw = 0
hrs = []
if hr_marker not in result:
return result
for line in result.splitlines():
if hr_marker in line:
hrs.append(line)
continue
if len(line) < mw:
continue
l = len(clean_ansi(line))
if l > mw:
mw = l
for hr in hrs:
# pos of hr marker is indent, derives full width:
# (more indent = less '-'):
hcl = clean_ansi(hr)
ind = len(hcl) - len(hcl.split(hr_marker, 1)[1]) - 1
w = min(term_columns, mw) - 2 * ind
hrf = hr.replace(hr_marker, hr_sep * w)
result = result.replace(hr, hrf)
return result
# Then tell markdown about it
class AnsiPrintExtension(Extension):
def extendMarkdown(self, md, md_globals):
ansi_print_ext = AnsiPrinter(md)
md.treeprocessors.add('ansi_print_ext', ansi_print_ext, '>inline')
def do_code_hilite(md, what='all'):
'''
"inverse" mode for source code highlighting:
the file contains mainly code and md is within docstrings
what in all, code, doc, mod
'''
if what not in ('all', 'code', 'doc', 'mod'):
what = 'all'
code_mode, md_mode = 1, 2
blocks, block, mode = [], [], code_mode
blocks.append([mode, block])
lines = ('\n' + md).splitlines()
mdstart = '\x01'
while lines:
line = lines.pop(0)
if mode == code_mode:
if line.rstrip() in ('"""_', "'''_", "/*_"):
mdstart = line.rstrip()[:-1]
mode = md_mode
block = []
if mdstart == '/*':
mdstart = '*/'
blocks.append([md_mode, block])
continue
elif line.rstrip() == mdstart:
if what == 'doc':
# only module level docstring:
break
mode = code_mode
block = []
blocks.append([code_mode, block])
continue
if mode == code_mode:
if what in ('all', 'code'):
block.append(line)
elif what != 'code':
block.append(line)
out = []
for mode, block in blocks:
b = '\n'.join(block)
if not b:
continue
if mode == code_mode:
out.append('```\n%s\n```' % b)
else:
out.append('\n'.join(block))
return '\n'.join(out)
def_enc_set = False