forked from axiros/terminal_markdown_viewer
-
Notifications
You must be signed in to change notification settings - Fork 2
/
markdownviewer.py
executable file
·1623 lines (1367 loc) · 48 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:
-A : no_colors : Strip all ansi (no colors then)
-C MODE : code_hilite : Sourcecode highlighting mode
-F FILE : config_file : Alternative configfile (defaults ~./.mdv or ~/.config/mdv)
-H : do_html : Print html version
-L : display_links : Backwards compatible shortcut for '-u i'
-M DIR : monitor_dir : Monitor directory for markdown file changes
-T C_THEME : c_theme : Theme for code highlight. If not set we use THEME.
-X Lexer : c_def_lexer : Default lexer name (default python). Set -x to use it always.
-b TABL : tab_length : Set tab_length to sth. different than 4 [default 4]
-c COLS : cols : Fix columns to this (default <your terminal width>)
-f FROM : from_txt : Display FROM given substring of the file.
-h : sh_help : Show help
-i : theme_info : Show theme infos with output
-l : bg_light : Light background (not yet supported)
-m : monitor_file : Monitor file for changes and redisplay FROM given substring
-n NRS : header_nrs : Header numbering (default off. Say e.g. -3 or 1- or 1-5)
-t THEME : theme : Key within the color ansi_table.json. 'random' accepted.
-u STYL : link_style : Link Style (it=inline table=default, h=hide, i=inline)
-x : c_no_guess : Do not try guess code lexer (guessing is a bit slow)
# Details
### **MDFILE**
Filename to markdownfile or '-' for pipe mode (no termwidth auto dedection then)
### Configuration
Happens like:
1. parse_default_files at (`~/.mdv` or `~/.config/mdv`)
2. overlay with any -F <filename> config
3. overlay with environ vars (e.g. `$MDV_THEME`)
4. overlay with CLI vars
#### File Formats
We try yaml.
If not installed we try json.
If it is the custom config file we fail if not parsable.
If you prefer shell style config then source and export so you have it as environ.
### **-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
`$MDV_CODE_THEME` is an alias for the standard `$MDV_C_THEME`
```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.
"""
from __future__ import absolute_import, print_function, unicode_literals
import io
import logging
import markdown
import os
import re
import shutil
import sys
import textwrap
import time
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
from functools import partial
from html import unescape
from pygments.util import ClassNotFound
md_logger = logging.getLogger('MARKDOWN')
md_logger.setLevel(logging.WARNING)
errout, envget = partial(print, file=sys.stderr), os.environ.get
# ---------------------------------------------------------------------- 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 = '①'
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'
# 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
# columns(!) - may be set to smaller width:
# could be exported by the shell, normally not in subprocesses:
def get_terminal_size():
"""get terminal size for python3.3 or greater, using shutil.
taken and modified from http://stackoverflow.com/a/14422538
Returns:
tuple: (column, rows) from terminal size, or (0, 0) if error.
"""
error_terminal_size = (0, 0)
if hasattr(shutil, 'get_terminal_size'):
terminal_size = shutil.get_terminal_size(fallback=error_terminal_size)
return terminal_size.columns, terminal_size.lines
else:
return error_terminal_size
# 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: # pragma: no cover
term_columns, term_rows = get_terminal_size()
if '-' not in sys.argv and (term_columns, term_rows) == (0, 0):
errout('!! Could not derive your terminal width !!')
term_columns, term_rows = int(term_columns or 80), int(term_rows or 200)
def die(msg):
errout(msg)
sys.exit(1)
def parse_env_and_cli():
"""replacing docopt"""
kw, argv = {}, list(sys.argv[1:])
opts = __doc__.split('# Options', 1)[1].split('# Details', 1)[0].strip()
opts = [_.lstrip().split(':', 2) for _ in opts.splitlines()]
opts = dict(
[
(l[0].split()[0], (l[0].split()[1:], l[1].strip(), l[2].strip()))
for l in opts
if len(l) > 2
]
)
# check environ:
aliases = {
'MDV_C_THEME': ['AXC_CODE_THEME', 'MDV_CODE_THEME'],
'MDV_THEME': ['AXC_THEME'],
}
for k, v in aliases.items():
for f in v:
if f in os.environ:
os.environ[k] = envget(f)
for k, v in opts.items():
V = envget('MDV_' + v[1].upper())
if V is not None:
kw[v[1]] = V
# walk cli args:
while argv:
k = argv.pop(0)
k = '-h' if k == '--help' else k
try:
reqv, n = opts[k][:2]
kw[n] = argv.pop(0) if reqv else True
except:
if not argv:
kw['filename'] = k
else:
die('Not understood: %s' % k)
return kw
# 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: # pragma: no cover
have_pygments = False
unichr = chr
string_type = str
is_app = 0
def_enc_set = False
# 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
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)
sample_code = """class Foo:
bar = 'baz'
"""
_md.append('```python\n""" Doc String """\n%s\n```' % sample_code)
_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, ClassNotFound):
print(col('Lexer for {} not found'.format(lang), R))
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),
):
s = str(s)
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
# number these header levels:
header_nr = {'from': 0, 'to': 0}
# current state scanning the document:
cur_header_state = {i: 0 for i in range(1, 11)}
def reset_cur_header_state():
"""after one document is complete"""
[into(cur_header_state, i, 0) for i in range(1, 11)]
def parse_header_nrs(nrs):
'nrs e.g. "4-10" or "1-"'
if not nrs:
return
if isinstance(nrs, dict):
return header_nr.update(nrs)
if isinstance(nrs, string_type):
if nrs.startswith('-'):
nrs = '1' + nrs
if nrs.endswith('-'):
nrs += '10'
if not '-' in nrs:
nrs += '-10'
nrs = nrs.split('-')[0:2]
try:
if isinstance(nrs, (tuple, list)):
header_nr['from'] = int(nrs[0])
header_nr['to'] = int(nrs[1])
return
except Extension as ex:
errout('header numbering not understood', nrs)
sys.exit(1)
def into(m, k, v):
m[k] = v
class Tags:
_last_header_level = 0
""" can be overwritten in derivations. """
def update_header_state(_, level):
cur = cur_header_state
if _._last_header_level > level:
[into(cur, i, 0) for i in range(level + 1, 10)]
for l in range(_._last_header_level + 1, level):
if cur[l] == 0:
cur[l] = 1
cur[level] += 1
_._last_header_level = level
ret = ''
f, t = header_nr['from'], header_nr['to']
if level >= f and level <= t:
ret = '.'.join(
[str(cur[i]) for i in range(f, t + 1) if cur[i] > 0]
)
return ret
# @staticmethod everywhere is eye cancer, so we instantiate it later
def h(_, s, level, **kw):
"""we set h1 to h10 formatters calling this when we do tag = Tag()"""
nrstr = _.update_header_state(level)
if nrstr:
# if we have header numbers we don't indent the text yet more:
s = ' ' + s.lstrip()
# have not more colors:
header_col = min(level, 5)
return '\n%s%s%s' % (
low('#' * 0),
nrstr,
col(s, globals()['H%s' % header_col]),
)
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] == '\x1b[0m' else None
code = prefix.join(code_lines)
code = code.replace('\x01--', ':-')
return code + '\n' + reset_col
elstr = lambda el: etree.tostring(el).decode('utf-8')
def is_text_node(el):
""" """
s = elstr(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 list(el) 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 ① :
try:
cur += '%s ' % unichr(link_start_ord + cur_link)
except NameError:
# fix for py3
# http://stackoverflow.com/a/2352047
cur += '%s ' % chr(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()
for h in cur_header_state:
setattr(tags, 'h%s' % h, partial(tags.h, level=h))
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 == 'code':
import pdb
pdb.set_trace()
# for c in list(list(el)[0]): print c.text, c
print('---------')
print(el, el.text)
print('---------')
"""
if el.tag == 'br':
out.append('\n')
return
# for c in list(el): print c.text, c
links_list, is_txt_and_inline_markup = None, 0
if el.tag == 'blockquote':
for el1 in list(el):
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?
if el.tag == 'code':
t = unescape(el.text)
else:
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 = 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] = list(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