-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtxt2tagslite
executable file
·6119 lines (5225 loc) · 224 KB
/
txt2tagslite
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
# txt2tagslite - a modular txt2tags proof of concept
# http://txt2tags.org
#
# Copyright 2001-2013 Aurelio Jargas
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# License: http://www.gnu.org/licenses/gpl-2.0.txt
# Subversion: http://svn.txt2tags.org
# Bug tracker: http://bugs.txt2tags.org
#
########################################################################
#
# BORING CODE EXPLANATION AHEAD
#
# Just read it if you wish to understand how the txt2tags code works.
#
########################################################################
#
# The code that [1] parses the marked text is separated from the
# code that [2] insert the target tags.
#
# [1] made by: def convert()
# [2] made by: class BlockMaster
#
# The structures of the marked text are identified and its contents are
# extracted into a data holder (Python lists and dictionaries).
#
# When parsing the source file, the blocks (para, lists, quote, table)
# are opened with BlockMaster, right when found. Then its contents,
# which spans on several lines, are feeded into a special holder on the
# BlockMaster instance. Just when the block is closed, the target tags
# are inserted for the full block as a whole, in one pass. This way, we
# have a better control on blocks. Much better than the previous line by
# line approach.
#
# In other words, whenever inside a block, the parser *holds* the tag
# insertion process, waiting until the full block is read. That was
# needed primary to close paragraphs for the XHTML target, but
# proved to be a very good adding, improving many other processing.
#
# -------------------------------------------------------------------
#
# These important classes are all documented:
# CommandLine, SourceDocument, ConfigMaster, ConfigLines.
#
# There is a RAW Config format and all kind of configuration is first
# converted to this format. Then a generic method parses it.
#
# These functions get information about the input file(s) and take
# care of the init processing:
# get_infiles_config(), process_source_file() and convert_this_files()
#
########################################################################
#XXX Python coding warning
# Avoid common mistakes:
# - do NOT use newlist=list instead newlist=list[:]
# - do NOT use newdic=dic instead newdic=dic.copy()
# - do NOT use dic[key] instead dic.get(key)
# - do NOT use del dic[key] without key in dic before
#XXX Smart Image Align don't work if the image is a link
# Can't fix that because the image is expanded together with the
# link, at the linkbank filling moment. Only the image is passed
# to parse_images(), not the full line, so it is always 'middle'.
#XXX Paragraph separation not valid inside Quote
# Quote will not have <p></p> inside, instead will close and open
# again the <blockquote>. This really sux in CSS, when defining a
# different background color. Still don't know how to fix it.
#XXX TODO (maybe)
# New mark or macro which expands to an anchor full title.
# It is necessary to parse the full document in this order:
# DONE 1st scan: HEAD: get all settings, including %!includeconf
# DONE 2nd scan: BODY: expand includes & apply %!preproc
# 3rd scan: BODY: read titles and compose TOC info
# 4th scan: BODY: full parsing, expanding [#anchor] 1st
# Steps 2 and 3 can be made together, with no tag adding.
# Two complete body scans will be *slow*, don't know if it worths.
# One solution may be add the titles as postproc rules
# These are all the core Python modules used by txt2tags (KISS!)
import re
import os
import sys
import locale
import time # %%date, %%mtime
import getopt
import textwrap
import csv
import struct
import unicodedata
import base64 # embedImage()
import shlex # CommandLine.tokenize()
# import urllib # read remote files (URLs) -- postponed, see issue 96
# import email # %%mtime for remote files -- postponed, see issue 96
try:
from lib import *
except:
pass
import targets
from targets import _
# Program information
my_url = 'http://txt2tags.org'
my_name = 'txt2tags'
my_email = '[email protected]'
my_revision = '$Revision$' # automatic, from SVN
my_version = '2.6'
# Add SVN revision number to version: 1.2.345
my_version = '%s.%s' % (my_version, re.sub(r'\D', '', my_revision))
# FLAGS : the conversion related flags , may be used in %!options
# OPTIONS : the conversion related options, may be used in %!options
# ACTIONS : the other behavior modifiers, valid on command line only
# MACROS : the valid macros with their default values for formatting
# SETTINGS: global miscellaneous settings, valid on RC file only
# NO_TARGET: actions that don't require a target specification
# NO_MULTI_INPUT: actions that don't accept more than one input file
# CONFIG_KEYWORDS: the valid %!key:val keywords
#
# FLAGS and OPTIONS are configs that affect the converted document.
# They usually have also a --no-<option> to turn them OFF.
#
# ACTIONS are needed because when handling multiple input files, strange
# behavior may occur, such as use command line interface for the
# first file and gui for the second. There is no --no-<action>.
# Options --version and --help inside %!options are odd.
#
FLAGS = {
'headers': 1,
'enum-title': 0,
'mask-email': 0,
'toc-only': 0,
'toc': 0,
'qa': 0,
'rc': 1,
'css-sugar': targets.CONF['css-sugar'],
'css-inside': 0,
'quiet': 0,
'fix-path': 0,
'embed-images': 0,
}
OPTIONS = {
'target': '',
'toc-level': 3,
'toc-title': '',
'style': '',
'infile': '',
'outfile': '',
'encoding': '',
'config-file': '',
'split': 0,
'lang': '',
'width': 0,
'height': 0,
'chars': targets.CONF['chars'],
'show-config-value': '',
'template': '',
'dirname': '', # internal use only
}
ACTIONS = {
'help': 0,
'version': 0,
'gui': 0,
'verbose': 0,
'debug': 0,
'dump-config': 0,
'dump-source': 0,
'targets': 0,
}
MACROS = {
# date
'date': '%Y%m%d',
'mtime': '%Y%m%d',
# files
'infile': '%f',
'currentfile': '%f',
'outfile': '%f',
# app
'appurl': '',
'appname': '',
'appversion': '',
# conversion
'target': '',
'cmdline': '',
'encoding': '',
# header
'header1': '',
'header2': '',
'header3': '',
# Creative Commons license
'cc': '',
}
SETTINGS = {} # for future use
NO_TARGET = [
'help',
'version',
'gui',
'toc-only',
'dump-config',
'dump-source',
'targets',
]
NO_MULTI_INPUT = [
'gui',
'dump-config',
'dump-source'
]
CONFIG_KEYWORDS = [
'cc',
'target',
'encoding',
'style',
'stylepath', # internal use only
'options',
'preproc',
'postproc',
'postvoodoo',
'guicolors',
]
TARGET_NAMES = {
}
TARGET_TYPES = {
'html' : (_('HTML'), []),
'wiki' : (_('WIKI'), []),
'office' : (_('OFFICE'), []),
'text' : (_('TEXT'), []),
}
TARGETS_LIST = targets.TARGETS_LIST
OTHER_TARGETS = []
TARGET_ALIASES = {}
TARGET_EXTENSIONS = {}
for target in TARGETS_LIST:
TARGET_NAMES[target] = getattr(getattr(targets, target), 'NAME', target.capitalize() + ' target')
TARGET_EXTENSIONS[target] = getattr(getattr(targets, target), 'EXTENSION', target)
for alias in getattr(getattr(targets, target), 'ALIASES', []):
TARGET_ALIASES[alias] = target
try:
TARGET_TYPES[getattr(targets, target).TYPE][1].append(target)
except:
OTHER_TARGETS.append(target)
TARGETS = TARGET_NAMES.keys()
TARGETS.sort()
DEBUG = 0 # do not edit here, please use --debug
VERBOSE = 0 # do not edit here, please use -v, -vv or -vvv
QUIET = 0 # do not edit here, please use --quiet
GUI = 0 # do not edit here, please use --gui
AUTOTOC = 1 # do not edit here, please use --no-toc or %%toc
DFT_TEXT_WIDTH = 72 # do not edit here, please use --width
DFT_SLIDE_WIDTH = 80 # do not edit here, please use --width
DFT_SLIDE_HEIGHT = 25 # do not edit here, please use --height
# ASCII Art config
AA = targets.AA
AA_COUNT = 0
AA_PW_TOC = {}
AA_IMG = 0
AA_TITLE = ''
AA_MARKS = []
RC_RAW = []
CMDLINE_RAW = []
CONF = {}
BLOCK = None
TITLE = None
regex = {}
TAGS = {}
rules = {}
MAILING = ''
lang = 'english'
TARGET = ''
STDIN = STDOUT = '-'
MODULEIN = MODULEOUT = '-module-'
ESCCHAR = '\x00'
SEPARATOR = '\x01'
LISTNAMES = {'-': 'list', '+': 'numlist', ':': 'deflist'}
LINEBREAK = {'default': '\n', 'win': '\r\n', 'mac': '\r'}
ESCAPES = {}
for target in TARGETS_LIST:
ESCAPES[target] = getattr(getattr(targets, target), 'ESCAPES', [])
# Platform specific settings
LB = LINEBREAK.get(sys.platform[:3]) or LINEBREAK['default']
VERSIONSTR = _("%s version %s <%s>") % (my_name, my_version, my_url)
def Usage():
fmt1 = "%4s %-15s %s"
fmt2 = "%4s, %-15s %s"
return '\n'.join([
'',
_("Usage: %s [OPTIONS] [infile.t2t ...]") % my_name,
'',
fmt1 % ('' , '--targets' , _("print a list of all the available targets and exit")),
fmt2 % ('-t', '--target=TYPE' , _("set target document type. currently supported:")),
fmt1 % ('' , '' , ', '.join(TARGETS[:8]) + ','),
fmt1 % ('' , '' , ', '.join(TARGETS[8:16]) + ','),
fmt1 % ('' , '' , ', '.join(TARGETS[16:25]) + ','),
fmt1 % ('' , '' , ', '.join(TARGETS[25:34]) + ','),
fmt1 % ('' , '' , ', '.join(TARGETS[34:])),
fmt2 % ('-i', '--infile=FILE' , _("set FILE as the input file name ('-' for STDIN)")),
fmt2 % ('-o', '--outfile=FILE' , _("set FILE as the output file name ('-' for STDOUT)")),
fmt1 % ('' , '--encoding=ENC' , _("inform source file encoding (UTF-8, iso-8859-1, etc)")),
fmt1 % ('' , '--toc' , _("add an automatic Table of Contents to the output")),
fmt1 % ('' , '--toc-title=S' , _("set custom TOC title to S")),
fmt1 % ('' , '--toc-level=N' , _("set maximum TOC level (depth) to N")),
fmt1 % ('' , '--toc-only' , _("print the Table of Contents and exit")),
fmt2 % ('-n', '--enum-title' , _("enumerate all titles as 1, 1.1, 1.1.1, etc")),
fmt1 % ('' , '--style=FILE' , _("use FILE as the document style (like HTML CSS)")),
fmt1 % ('' , '--css-sugar' , _("insert CSS-friendly tags for HTML/XHTML")),
fmt1 % ('' , '--css-inside' , _("insert CSS file contents inside HTML/XHTML headers")),
fmt1 % ('' , '--embed-images' , _("embed image data inside HTML, html5, xhtml, RTF, aat and aap documents")),
fmt2 % ('-H', '--no-headers' , _("suppress header and footer from the output")),
fmt2 % ('-T', '--template=FILE', _("use FILE as the template for the output document")),
fmt1 % ('' , '--mask-email' , _("hide email from spam robots. [email protected] turns <x (a) y z>")),
fmt1 % ('' , '--width=N' , _("set the output's width to N columns (used by aat, aap and aatw targets)")),
fmt1 % ('' , '--height=N' , _("set the output's height to N rows (used by aap target)")),
fmt1 % ('' , '--chars=S' , _("set the output's chars to S (used by all aa targets and rst)")),
fmt1 % ('' , '' , _("aa default " + targets.AA_SIMPLE + " rst default " + targets.RST_VALUES)),
fmt2 % ('-C', '--config-file=F', _("read configuration from file F")),
fmt1 % ('' , '--fix-path' , _("fix resources path (image, links, CSS) when needed")),
fmt1 % ('' , '--gui' , _("invoke Graphical Tk Interface")),
fmt2 % ('-q', '--quiet' , _("quiet mode, suppress all output (except errors)")),
fmt2 % ('-v', '--verbose' , _("print informative messages during conversion")),
fmt2 % ('-h', '--help' , _("print this help information and exit")),
fmt2 % ('-V', '--version' , _("print program version and exit")),
fmt1 % ('' , '--dump-config' , _("print all the configuration found and exit")),
fmt1 % ('' , '--dump-source' , _("print the document source, with includes expanded")),
'',
_("Example:"),
" %s -t html --toc %s" % (my_name, _("file.t2t")),
'',
_("The 'no-' prefix disables the option:"),
' --no-toc, --no-style, --no-enum-title, ...',
'',
_("By default, converted output is saved to 'infile.<target>'."),
_("Use --outfile to force an output file name."),
_("If input file is '-', reads from STDIN."),
_("If output file is '-', dumps output to STDOUT."),
'',
my_url,
'',
])
##############################################################################
# Here is all the target's templates
# You may edit them to fit your needs
# - the %(HEADERn)s strings represent the Header lines
# - the %(STYLE)s string is changed by --style contents
# - the %(ENCODING)s string is changed by --encoding contents
# - if any of the above is empty, the full line is removed
# - use %% to represent a literal %
#
HEADER_TEMPLATE = {
}
for target in TARGETS_LIST:
HEADER_TEMPLATE[target] = getattr(getattr(targets, target), 'HEADER', '')
HEADER_TEMPLATE[target + 'css'] = getattr(getattr(targets, target), 'HEADERCSS', '')
##############################################################################
def getTags(config):
"Returns all the known tags for the specified target"
keys = """
title1 numtitle1
title2 numtitle2
title3 numtitle3
title4 numtitle4
title5 numtitle5
title1Open title1Close
title2Open title2Close
title3Open title3Close
title4Open title4Close
title5Open title5Close
blocktitle1Open blocktitle1Close
blocktitle2Open blocktitle2Close
blocktitle3Open blocktitle3Close
paragraphOpen paragraphClose
blockVerbOpen blockVerbClose blockVerbLine
blockQuoteOpen blockQuoteClose blockQuoteLine
blockVerbSep
blockCommentOpen blockCommentClose
fontMonoOpen fontMonoClose
fontBoldOpen fontBoldClose
fontItalicOpen fontItalicClose
fontUnderlineOpen fontUnderlineClose
fontStrikeOpen fontStrikeClose
listOpen listClose
listOpenCompact listCloseCompact
listItemOpen listItemClose listItemLine
numlistOpen numlistClose
numlistOpenCompact numlistCloseCompact
numlistItemOpen numlistItemClose numlistItemLine
deflistOpen deflistClose
deflistOpenCompact deflistCloseCompact
deflistItem1Open deflistItem1Close
deflistItem2Open deflistItem2Close deflistItem2LinePrefix
bar1 bar2
url urlMark urlMarkAnchor urlImg
email emailMark
img imgAlignLeft imgAlignRight imgAlignCenter
_imgAlignLeft _imgAlignRight _imgAlignCenter
tableOpen tableClose
_tableBorder _tableAlignLeft _tableAlignCenter
tableRowOpen tableRowClose tableRowSep
tableTitleRowOpen tableTitleRowClose
tableCellOpen tableCellClose tableCellSep
tableTitleCellOpen tableTitleCellClose tableTitleCellSep
_tableColAlignLeft _tableColAlignRight _tableColAlignCenter
tableCellAlignLeft tableCellAlignRight tableCellAlignCenter
_tableCellAlignLeft _tableCellAlignRight _tableCellAlignCenter
_tableCellColSpan tableColAlignSep
_tableCellColSpanChar _tableCellBorder
_tableCellMulticolOpen
_tableCellMulticolClose
tableCellHead tableTitleCellHead
bodyOpen bodyClose
cssOpen cssClose
tocOpen tocClose TOC
anchor
comment
pageBreak
EOD
""".split()
# TIP: \a represents the current text inside the mark
# TIP: ~A~, ~B~ and ~C~ are expanded to other tags parts
alltags = {}
for target in TARGETS_LIST:
if getattr(getattr(targets, target), 'RULES', {}).get('confdependenttags'):
reload(getattr(targets, target))
alltags[target] = getattr(getattr(targets, target), 'TAGS', {})
# Compose the target tags dictionary
tags = {}
target_tags = alltags[config['target']].copy()
for key in keys:
tags[key] = '' # create empty keys
for key in target_tags.keys():
tags[key] = maskEscapeChar(target_tags[key]) # populate
# Map strong line to pagebreak
if rules['mapbar2pagebreak'] and tags['pageBreak']:
tags['bar2'] = tags['pageBreak']
# Change img tag if embedding images in RTF
if config['embed-images']:
if tags.get('imgEmbed'):
tags['img'] = tags['imgEmbed']
else:
Error(_("Invalid --embed-images option with target '%s'." % config['target']))
# Map strong line to separator if not defined
if not tags['bar2'] and tags['bar1']:
tags['bar2'] = tags['bar1']
return tags
##############################################################################
def getRules(config):
"Returns all the target-specific syntax rules"
ret = {}
allrules = [
# target rules (ON/OFF)
'linkable', # target supports external links
'tableable', # target supports tables
'tableonly', # target computes only the tables
'spread', # target uses the spread.py engine
'spreadgrid', # target adds the reference grid to the sheet
'imglinkable', # target supports images as links
'imgalignable', # target supports image alignment
'imgasdefterm', # target supports image as definition term
'autonumberlist', # target supports numbered lists natively
'autonumbertitle', # target supports numbered titles natively
'stylable', # target supports external style files
'parainsidelist', # lists items supports paragraph
'compactlist', # separate enclosing tags for compact lists
'spacedlistitem', # lists support blank lines between items
'listnotnested', # lists cannot be nested
'listitemnotnested', # list items must be closed before nesting lists
'quotenotnested', # quotes cannot be nested
'verbblocknotescaped', # don't escape specials in verb block
'verbblockfinalescape', # do final escapes in verb block
'escapeurl', # escape special in link URL
'labelbeforelink', # label comes before the link on the tag
'onelinepara', # dump paragraph as a single long line
'onelinequote', # dump quote as a single long line (EXPERIMENTAL)
'notbreaklistitemclose', # do not break line before the list item close tag (EXPERIMENTAL)
'tabletitlerowinbold', # manually bold any cell on table titles
'tablecellstrip', # strip extra spaces from each table cell
'tablecellspannable', # the table cells can have span attribute
'tablecellmulticol', # separate open+close tags for multicol cells
'tablecolumnsnumber', # set the number of columns in place of n_cols in tableOpen
'tablenumber', # set the number of the table in place of n_table in tableOpen
'barinsidequote', # bars are allowed inside quote blocks
'finalescapetitle', # perform final escapes on title lines
'autotocnewpagebefore', # break page before automatic TOC
'autotocnewpageafter', # break page after automatic TOC
'autotocwithbars', # automatic TOC surrounded by bars
'plaintexttoc', # TOC will be plain text (no links)
'mapbar2pagebreak', # map the strong bar to a page break
'titleblocks', # titles must be on open/close section blocks
'listlineafteropen', # put listItemLine after listItemOpen
'escapexmlchars', # escape the XML special chars: < > &
'listlevelzerobased', # list levels start at 0 when encoding into tags
'zerodepthparagraph', # non-nested paras have block depth of 0 instead of 1
'cellspancumulative', # cell span value adds up for each cell of a row
'keepblankheaderline', # template lines are not removed if headers are blank
'confdependenttags', # tags are configuration dependent
'confdependentrules', # rules are configuration dependent
'asciiart', # ascii art target
'web', # html ascii art target
'slides', # slides target
# Target code beautify (ON/OFF)
'indentverbblock', # add leading spaces to verb block lines
'breaktablecell', # break lines after any table cell
'breaktablelineopen', # break line after opening table line
'notbreaklistopen', # don't break line after opening a new list
'keepquoteindent', # don't remove the leading TABs on quotes
'keeplistindent', # don't remove the leading spaces on lists
'blankendautotoc', # append a blank line at the auto TOC end
'tagnotindentable', # tags must be placed at the line beginning
'spacedlistitemopen', # append a space after the list item open tag
'spacednumlistitemopen', # append a space after the numlist item open tag
'deflisttextstrip', # strip the contents of the deflist text
'blanksaroundpara', # put a blank line before and after paragraphs
'blanksaroundverb', # put a blank line before and after verb blocks
'blanksaroundquote', # put a blank line before and after quotes
'blanksaroundlist', # put a blank line before and after lists
'blanksaroundnumlist', # put a blank line before and after numlists
'blanksarounddeflist', # put a blank line before and after deflists
'blanksaroundnestedlist', # put a blank line before and after all type of nested lists
'blanksaroundtable', # put a blank line before and after tables
'blanksaroundbar', # put a blank line before and after bars
'blanksaroundtitle', # put a blank line before and after titles
'blanksaroundnumtitle', # put a blank line before and after numtitles
'iswrapped', # wrap with the --width value
# Value settings
'listmaxdepth', # maximum depth for lists
'quotemaxdepth', # maximum depth for quotes
'tablecellaligntype', # type of table cell align: cell, column
'blockdepthmultiply', # block depth multiple for encoding
'depthmultiplyplus', # add to block depth before multiplying
'cellspanmultiplier', # cell span is multiplied by this value
'spreadmarkup', # the markup spread engine option: 'txt', 'html' or 'tex'
]
rules_bank = {}
targets.CONF['css-sugar'] = config['css-sugar']
for target in TARGETS_LIST:
if getattr(getattr(targets, target), 'RULES', {}).get('confdependentrules'):
reload(getattr(targets, target))
rules_bank[target] = getattr(getattr(targets, target), 'RULES', {})
myrules = rules_bank[config['target']].copy()
# Populate return dictionary
for key in allrules:
ret[key] = 0 # reset all
ret.update(myrules) # get rules
return ret
##############################################################################
def getRegexes():
"Returns all the regexes used to find the t2t marks"
bank = {
'blockVerbOpen':
re.compile(r'^```\s*$'),
'blockVerbClose':
re.compile(r'^```\s*$'),
'blockRawOpen':
re.compile(r'^"""\s*$'),
'blockRawClose':
re.compile(r'^"""\s*$'),
'blockTaggedOpen':
re.compile(r"^'''\s*$"),
'blockTaggedClose':
re.compile(r"^'''\s*$"),
'blockCommentOpen':
re.compile(r'^%%%\s*$'),
'blockCommentClose':
re.compile(r'^%%%\s*$'),
'quote':
re.compile(r'^\t+'),
'1lineVerb':
re.compile(r'^``` (?=.)'),
'1lineRaw':
re.compile(r'^""" (?=.)'),
'1lineTagged':
re.compile(r"^''' (?=.)"),
# mono, raw, bold, italic, underline:
# - marks must be glued with the contents, no boundary spaces
# - they are greedy, so in ****bold****, turns to <b>**bold**</b>
'fontMono':
re.compile(r'``([^\s](|.*?[^\s])`*)``'),
'raw':
re.compile(r'""([^\s](|.*?[^\s])"*)""'),
'tagged':
re.compile(r"''([^\s](|.*?[^\s])'*)''"),
'fontBold':
re.compile(r'\*\*([^\s](|.*?[^\s])\**)\*\*'),
'fontItalic':
re.compile(r'//([^\s](|.*?[^\s])/*)//'),
'fontUnderline':
re.compile(r'__([^\s](|.*?[^\s])_*)__'),
'fontStrike':
re.compile(r'--([^\s](|.*?[^\s])-*)--'),
'list':
re.compile(r'^( *)(-) (?=[^ ])'),
'numlist':
re.compile(r'^( *)(\+) (?=[^ ])'),
'deflist':
re.compile(r'^( *)(:) (.*)$'),
'listclose':
re.compile(r'^( *)([-+:])\s*$'),
'bar':
re.compile(r'^(\s*)([_=-]{20,})\s*$'),
'table':
re.compile(r'^ *\|(\||_|/)? '),
'blankline':
re.compile(r'^\s*$'),
'comment':
re.compile(r'^%'),
# Auxiliary tag regexes
'_imgAlign' : re.compile(r'~A~', re.I),
'_tableAlign' : re.compile(r'~A~', re.I),
'_anchor' : re.compile(r'~A~', re.I),
'_tableBorder' : re.compile(r'~B~', re.I),
'_tableColAlign' : re.compile(r'~C~', re.I),
'_tableCellColSpan' : re.compile(r'~S~', re.I),
'_tableCellAlign' : re.compile(r'~A~', re.I),
'_tableAttrDelimiter': re.compile(r'~Z~', re.I),
'_blockDepth' : re.compile(r'~D~', re.I),
'_listLevel' : re.compile(r'~L~', re.I),
}
# Special char to place data on TAGs contents (\a == bell)
bank['x'] = re.compile('\a')
# %%macroname [ (formatting) ]
bank['macros'] = re.compile(r'%%%%(?P<name>%s)\b(\((?P<fmt>.*?)\))?' % (
'|'.join(MACROS.keys())), re.I)
# %%TOC special macro for TOC positioning
bank['toc'] = re.compile(r'^ *%%toc\s*$', re.I)
# Almost complicated title regexes ;)
titskel = r'^ *(?P<id>%s)(?P<txt>%s)\1(\[(?P<label>[\w-]*)\])?\s*$'
bank['title'] = re.compile(titskel % ('[=]{1,5}', '[^=](|.*[^=])'))
bank['numtitle'] = re.compile(titskel % ('[+]{1,5}', '[^+](|.*[^+])'))
### Complicated regexes begin here ;)
#
# Textual descriptions on --help's style: [...] is optional, | is OR
### First, some auxiliary variables
#
# [image.EXT]
patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp|svg))\]'
# Link things
# http://www.gbiv.com/protocols/uri/rfc/rfc3986.html
# pchar: A-Za-z._~- / %FF / !$&'()*+,;= / :@
# Recomended order: scheme://user:pass@domain/path?query=foo#anchor
# Also works : scheme://user:pass@domain/path#anchor?query=foo
# TODO form: !'():
urlskel = {
'proto' : r'(https?|ftp|news|telnet|gopher|wais)://',
'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess
'login' : r'A-Za-z0-9_.-', # for ftp://[email protected]
'pass' : r'[^ @]*', # for ftp://login:[email protected]
'chars' : r'A-Za-z0-9%._/~:,=$@&+-', # %20(space), :80(port), D&D
'anchor': r'A-Za-z0-9%._-', # %nn(encoded)
'form' : r'A-Za-z0-9/%&=+:;.,$@*_-', # .,@*_-(as is)
'punct' : r'.,;:!?'
}
# username [ :password ] @
patt_url_login = r'([%s]+(:%s)?@)?' % (urlskel['login'], urlskel['pass'])
# [ http:// ] [ username:password@ ] domain.com [ / ]
# [ #anchor | ?form=data ]
retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]*)?' % (
urlskel['proto'], patt_url_login, urlskel['guess'],
urlskel['chars'], urlskel['form'], urlskel['anchor'])
# filename | [ filename ] #anchor
retxt_url_local = r'[%s]+|[%s]*(#[%s]*)' % (
urlskel['chars'], urlskel['chars'], urlskel['anchor'])
# user@domain [ ?form=data ]
patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?' % (
urlskel['login'], urlskel['form'])
# Saving for future use
bank['_urlskel'] = urlskel
### And now the real regexes
#
bank['email'] = re.compile(patt_email, re.I)
# email | url
bank['link'] = re.compile(r'%s|%s' % (retxt_url, patt_email), re.I)
# \[ label | imagetag url | email | filename \]
bank['linkmark'] = re.compile(
r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]' % (
patt_img, retxt_url, patt_email, retxt_url_local),
re.L + re.I)
# Image
bank['img'] = re.compile(patt_img, re.L + re.I)
# Special things
bank['special'] = re.compile(r'^%!\s*')
return bank
### END OF regex nightmares
def completes_table(table):
data = [[row['cells'], row['cellspan']] for row in table]
n = max([len(line[0]) for line in data])
data2 = []
for line in data:
if not line[1]:
data2.append([n * [''], n * [1]])
else:
data2.append([line[0] + (n - sum(line[1])) * [''], line[1] + (n - sum(line[1])) * [1]])
return data2
def convert_to_table(itera, headers, borders, center):
if center:
row_ini = ' | '
else:
row_ini = '| '
if borders:
row_end = ' |'
else:
row_end = ''
table = []
for row in itera:
table.append(row_ini + ' | '.join(row).expandtabs() + row_end)
if headers:
table[0] = table[0].replace('|', '||', 1)
return table
def parse_convert_table(table, tableable, target):
ret = []
# Note: cell contents is raw, no t2t marks are parsed
if tableable:
ret.extend(BLOCK.blockin('table'))
if table:
BLOCK.tableparser.__init__(table[0])
for row in table:
tablerow = TableMaster().parse_row(row)
BLOCK.tableparser.add_row(tablerow)
# Very ugly, but necessary for escapes
line = SEPARATOR.join(tablerow['cells'])
BLOCK.holdadd(doEscape(target, line))
ret.extend(BLOCK.blockout())
# Tables are mapped to verb when target is not table-aware
else:
ret.extend(BLOCK.blockin('verb'))
BLOCK.propset('mapped', 'table')
for row in table:
BLOCK.holdadd(row)
ret.extend(BLOCK.blockout())
return ret
##############################################################################
class error(Exception):
pass
def echo(msg): # for quick debug
print '\033[32;1m%s\033[m' % msg
def Quit(msg=''):
if msg:
print msg
sys.exit(0)
def Error(msg):
msg = _("%s: Error: ") % my_name + msg
raise error(msg)
def getTraceback():
try:
from traceback import format_exception
etype, value, tb = sys.exc_info()
return ''.join(format_exception(etype, value, tb))
except:
pass
def getUnknownErrorMessage():
msg = '%s\n%s (%s):\n\n%s' % (
_('Sorry! Txt2tags aborted by an unknown error.'),
_('Please send the following Error Traceback to the author'),
my_email, getTraceback())
return msg
def Message(msg, level):
if level <= VERBOSE and not QUIET:
prefix = '-' * 5
print "%s %s" % (prefix * level, msg)
def Debug(msg, id_=0, linenr=None):
"Show debug messages, categorized (colored or not)"
if QUIET or not DEBUG:
return
if int(id_) not in range(8):
id_ = 0
# 0:black 1:red 2:green 3:yellow 4:blue 5:pink 6:cyan 7:white ;1:light
ids = ['INI', 'CFG', 'SRC', 'BLK', 'HLD', 'GUI', 'OUT', 'DET']
colors_bgdark = ['7;1', '1;1', '3;1', '6;1', '4;1', '5;1', '2;1', '7;1']
colors_bglight = ['0' , '1' , '3' , '6' , '4' , '5' , '2' , '0' ]
if linenr is not None:
msg = "LINE %04d: %s" % (linenr, msg)
if targets.COLOR_DEBUG:
if targets.BG_LIGHT:
color = colors_bglight[id_]
else:
color = colors_bgdark[id_]
msg = '\033[3%sm%s\033[m' % (color, msg)
print "++ %s: %s" % (ids[id_], msg)
def Readfile(file_path, remove_linebreaks=0, ignore_error=0):
data = []
# STDIN
if file_path == '-':
try:
data = sys.stdin.readlines()
except:
if not ignore_error:
Error(_('You must feed me with data on STDIN!'))
# URL
elif PathMaster().is_url(file_path):
try:
from urllib import urlopen
f = urlopen(file_path)
if f.getcode() == 404: # URL not found
raise
data = f.readlines()
f.close()
except:
if not ignore_error:
Error(_("Cannot read file:") + ' ' + file_path)
# local file
else:
try:
f = open(file_path)
data = f.readlines()
f.close()
except:
if not ignore_error:
Error(_("Cannot read file:") + ' ' + file_path)
if remove_linebreaks:
data = map(lambda x: re.sub('[\n\r]+$', '', x), data)
Message(_("File read (%d lines): %s") % (len(data), file_path), 2)
return data
def Savefile(file_path, contents):
try:
f = open(file_path, 'wb')
except:
Error(_("Cannot open file for writing:") + ' ' + file_path)
if type(contents) == type([]):
doit = f.writelines
else:
doit = f.write
cont = []
if CONF['encoding'].lower() == 'utf-8' and CONF['target'] != 'mgp':
for line in contents:
if isinstance(line, unicode):
cont.append(line.encode('utf-8'))
else:
cont.append(line)
elif CONF['target'] == 'mgp':
for line in contents:
if isinstance(line, unicode):
cont.append(line.encode('latin1', 'replace'))
else:
cont.append(line)
else:
cont = contents
doit(cont)
f.close()
def showdic(dic):
for k in dic.keys():
print "%15s : %s" % (k, dic[k])
def dotted_spaces(txt=''):
return txt.replace(' ', '.')
# TIP: win env vars http://www.winnetmag.com/Article/ArticleID/23873/23873.html
def get_rc_path():
"Return the full path for the users' RC file"
# Try to get the path from an env var. if yes, we're done
user_defined = os.environ.get('T2TCONFIG')
if user_defined:
return user_defined
# Env var not found, so perform automatic path composing
# Set default filename according system platform
rc_names = {'default': '.txt2tagsrc', 'win': '_t2trc'}
rc_file = rc_names.get(sys.platform[:3]) or rc_names['default']
# The file must be on the user directory, but where is this dir?
rc_dir_search = ['HOME', 'HOMEPATH']
for var in rc_dir_search:
rc_dir = os.environ.get(var)
if rc_dir:
break
# rc dir found, now we must join dir+file to compose the full path
if rc_dir:
# Compose path and return it if the file exists
rc_path = os.path.join(rc_dir, rc_file)