PageRenderTime 99ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 1ms

/old/txt2tags-2.4.py

http://txt2tags.googlecode.com/
Python | 4715 lines | 4247 code | 184 blank | 284 comment | 199 complexity | c383d7cb0d3fbb2ec403bd96a4d14473 MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, WTFPL
  1. #!/usr/bin/env python
  2. # txt2tags - generic text conversion tool
  3. # http://txt2tags.sf.net
  4. #
  5. # Copyright 2001, 2002, 2003, 2004, 2005, 2006 Aurelio Marinho Jargas
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 2.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You have received a copy of the GNU General Public License along
  17. # with this program, on the COPYING file.
  18. #
  19. ########################################################################
  20. #
  21. # BORING CODE EXPLANATION AHEAD
  22. #
  23. # Just read if you wish to understand how the txt2tags code works
  24. #
  25. ########################################################################
  26. #
  27. # Version 2.0 was a complete rewrite for the program 'core'.
  28. #
  29. # Now the code that [1] parses the marked text is separated from the
  30. # code that [2] insert the target tags.
  31. #
  32. # [1] made by: def convert()
  33. # [2] made by: class BlockMaster
  34. #
  35. # The structures of the marked text are identified and its contents are
  36. # extracted into a data holder (Python lists and dictionaries).
  37. #
  38. # When parsing the source file, the blocks (para, lists, quote, table)
  39. # are opened with BlockMaster, right when found. Then its contents,
  40. # which spans on several lines, are feeded into a special holder on the
  41. # BlockMaster instance. Just when the block is closed, the target tags
  42. # are inserted for the full block as a whole, in one pass. This way, we
  43. # have a better control on blocks. Much better than the previous line by
  44. # line approach.
  45. #
  46. # In other words, whenever inside a block, the parser *holds* the tag
  47. # insertion process, waiting until the full block is read. That was
  48. # needed primary to close paragraphs for the new XHTML target, but
  49. # proved to be a very good adding, improving many other processing.
  50. #
  51. # -------------------------------------------------------------------
  52. #
  53. # There is also a brand new code for the Configuration schema, 100%
  54. # rewritten. There are new classes, all self documented: CommandLine,
  55. # SourceDocument, ConfigMaster and ConfigLines. In short, a new RAW
  56. # Config format was created, and all kind of configuration is first
  57. # converted to this format, and then a generic method parses it.
  58. #
  59. # The init processing was changed also, and now the functions which
  60. # gets informations about the input files are: get_infiles_config(),
  61. # process_source_file() and convert_this_files()
  62. #
  63. # Other parts are untouched, and remains the same as in v1.7, as the
  64. # marks regexes, target Headers and target Tags & Rules.
  65. #
  66. ########################################################################
  67. # Now I think the code is nice, easier to read and understand
  68. #XXX Python coding warning
  69. # Avoid common mistakes:
  70. # - do NOT use newlist=list instead newlist=list[:]
  71. # - do NOT use newdic=dic instead newdic=dic.copy()
  72. # - do NOT use dic[key] instead dic.get(key)
  73. # - do NOT use del dic[key] without has_key() before
  74. #XXX Smart Image Align don't work if the image is a link
  75. # Can't fix that because the image is expanded together with the
  76. # link, at the linkbank filling moment. Only the image is passed
  77. # to parse_images(), not the full line, so it is always 'middle'.
  78. #XXX Paragraph separation not valid inside Quote
  79. # Quote will not have <p></p> inside, instead will close and open
  80. # again the <blockquote>. This really sux in CSS, when defining a
  81. # different background color. Still don't know how to fix it.
  82. #XXX TODO (maybe)
  83. # New mark or macro which expands to an anchor full title.
  84. # It is necessary to parse the full document in this order:
  85. # DONE 1st scan: HEAD: get all settings, including %!includeconf
  86. # DONE 2nd scan: BODY: expand includes & apply %!preproc
  87. # 3rd scan: BODY: read titles and compose TOC info
  88. # 4th scan: BODY: full parsing, expanding [#anchor] 1st
  89. # Steps 2 and 3 can be made together, with no tag adding.
  90. # Two complete body scans will be *slow*, don't know if it worths.
  91. # One solution may be add the titles as postproc rules
  92. ##############################################################################
  93. # User config (1=ON, 0=OFF)
  94. USE_I18N = 1 # use gettext for i18ned messages? (default is 1)
  95. COLOR_DEBUG = 1 # show debug messages in colors? (default is 1)
  96. BG_LIGHT = 0 # your terminal background color is light (default is 0)
  97. HTML_LOWER = 0 # use lowercased HTML tags instead upper? (default is 0)
  98. ##############################################################################
  99. # These are all the core Python modules used by txt2tags (KISS!)
  100. import re, string, os, sys, time, getopt
  101. # Program information
  102. my_url = 'http://txt2tags.sf.net'
  103. my_name = 'txt2tags'
  104. my_email = 'verde@aurelio.net'
  105. my_version = '2.4'
  106. # i18n - just use if available
  107. if USE_I18N:
  108. try:
  109. import gettext
  110. # If your locale dir is different, change it here
  111. cat = gettext.Catalog('txt2tags',localedir='/usr/share/locale/')
  112. _ = cat.gettext
  113. except:
  114. _ = lambda x:x
  115. else:
  116. _ = lambda x:x
  117. # FLAGS : the conversion related flags , may be used in %!options
  118. # OPTIONS : the conversion related options, may be used in %!options
  119. # ACTIONS : the other behavior modifiers, valid on command line only
  120. # MACROS : the valid macros with their default values for formatting
  121. # SETTINGS: global miscellaneous settings, valid on RC file only
  122. # NO_TARGET: actions that don't require a target specification
  123. # NO_MULTI_INPUT: actions that don't accept more than one input file
  124. # CONFIG_KEYWORDS: the valid %!key:val keywords
  125. #
  126. # FLAGS and OPTIONS are configs that affect the converted document.
  127. # They usually have also a --no-<option> to turn them OFF.
  128. # ACTIONS are needed because when doing multiple input files, strange
  129. # behavior would be found, as use command line interface for the
  130. # first file and gui for the second. There is no --no-<action>.
  131. # --version and --help inside %!options are also odd
  132. #
  133. TARGETS = ['html', 'xhtml', 'sgml', 'tex', 'lout', 'man', 'mgp',
  134. 'moin', 'pm6' , 'txt']
  135. FLAGS = {'headers' :1 , 'enum-title' :0 , 'mask-email' :0 ,
  136. 'toc-only' :0 , 'toc' :0 , 'rc' :1 ,
  137. 'css-sugar' :0 , 'css-suggar' :0 , 'css-inside' :0 ,
  138. 'quiet' :0 }
  139. OPTIONS = {'target' :'', 'toc-level' :3 , 'style' :'',
  140. 'infile' :'', 'outfile' :'', 'encoding' :'',
  141. 'config-file':'', 'split' :0 , 'lang' :''}
  142. ACTIONS = {'help' :0 , 'version' :0 , 'gui' :0 ,
  143. 'verbose' :0 , 'debug' :0 , 'dump-config':0 ,
  144. 'dump-source':0 }
  145. MACROS = {'date' : '%Y%m%d', 'infile': '%f',
  146. 'mtime': '%Y%m%d', 'outfile': '%f'}
  147. SETTINGS = {} # for future use
  148. NO_TARGET = ['help', 'version', 'gui', 'toc-only', 'dump-config', 'dump-source']
  149. NO_MULTI_INPUT = ['gui','dump-config','dump-source']
  150. CONFIG_KEYWORDS = [
  151. 'target', 'encoding', 'style', 'options', 'preproc','postproc',
  152. 'guicolors']
  153. TARGET_NAMES = {
  154. 'html' : _('HTML page'),
  155. 'xhtml': _('XHTML page'),
  156. 'sgml' : _('SGML document'),
  157. 'tex' : _('LaTeX document'),
  158. 'lout' : _('Lout document'),
  159. 'man' : _('UNIX Manual page'),
  160. 'mgp' : _('MagicPoint presentation'),
  161. 'moin' : _('MoinMoin page'),
  162. 'pm6' : _('PageMaker document'),
  163. 'txt' : _('Plain Text'),
  164. }
  165. DEBUG = 0 # do not edit here, please use --debug
  166. VERBOSE = 0 # do not edit here, please use -v, -vv or -vvv
  167. QUIET = 0 # do not edit here, please use --quiet
  168. GUI = 0 # do not edit here, please use --gui
  169. AUTOTOC = 1 # do not edit here, please use --no-toc or %%toc
  170. RC_RAW = []
  171. CMDLINE_RAW = []
  172. CONF = {}
  173. BLOCK = None
  174. regex = {}
  175. TAGS = {}
  176. rules = {}
  177. lang = 'english'
  178. TARGET = ''
  179. STDIN = STDOUT = '-'
  180. MODULEIN = MODULEOUT = '-module-'
  181. ESCCHAR = '\x00'
  182. SEPARATOR = '\x01'
  183. LISTNAMES = {'-':'list', '+':'numlist', ':':'deflist'}
  184. LINEBREAK = {'default':'\n', 'win':'\r\n', 'mac':'\r'}
  185. # Platform specific settings
  186. LB = LINEBREAK.get(sys.platform[:3]) or LINEBREAK['default']
  187. VERSIONSTR = _("%s version %s <%s>")%(my_name,my_version,my_url)
  188. USAGE = string.join([
  189. '',
  190. _("Usage: %s [OPTIONS] [infile.t2t ...]") % my_name,
  191. '',
  192. _(" -t, --target=TYPE set target document type. currently supported:"),
  193. ' %s' % re.sub(r"[]'[]",'',repr(TARGETS)),
  194. _(" -i, --infile=FILE set FILE as the input file name ('-' for STDIN)"),
  195. _(" -o, --outfile=FILE set FILE as the output file name ('-' for STDOUT)"),
  196. _(" -H, --no-headers suppress header, title and footer contents"),
  197. _(" --headers show header, title and footer contents (default ON)"),
  198. _(" --encoding=ENC set target file encoding (utf-8, iso-8859-1, etc)"),
  199. _(" --style=FILE use FILE as the document style (like HTML CSS)"),
  200. _(" --css-sugar insert CSS-friendly tags for HTML and XHTML targets"),
  201. _(" --css-inside insert CSS file contents inside HTML/XHTML headers"),
  202. _(" --mask-email hide email from spam robots. x@y.z turns <x (a) y z>"),
  203. _(" --toc add TOC (Table of Contents) to target document"),
  204. _(" --toc-only print document TOC and exit"),
  205. _(" --toc-level=N set maximum TOC level (depth) to N"),
  206. _(" -n, --enum-title enumerate all titles as 1, 1.1, 1.1.1, etc"),
  207. _(" -C, --config-file=F read config from file F"),
  208. _(" --rc read user config file ~/.txt2tagsrc (default ON)"),
  209. _(" --gui invoke Graphical Tk Interface"),
  210. _(" -q, --quiet quiet mode, suppress all output (except errors)"),
  211. _(" -v, --verbose print informative messages during conversion"),
  212. _(" -h, --help print this help information and exit"),
  213. _(" -V, --version print program version and exit"),
  214. _(" --dump-config print all the config found and exit"),
  215. _(" --dump-source print the document source, with includes expanded"),
  216. '',
  217. _("Turn OFF options:"),
  218. " --no-outfile, --no-infile, --no-style, --no-encoding, --no-headers",
  219. " --no-toc, --no-toc-only, --no-mask-email, --no-enum-title, --no-rc",
  220. " --no-css-sugar, --no-css-inside, --no-quiet, --no-dump-config",
  221. " --no-dump-source",
  222. '',
  223. _("Example:\n %s -t html --toc myfile.t2t") % my_name,
  224. '',
  225. _("By default, converted output is saved to 'infile.<target>'."),
  226. _("Use --outfile to force an output file name."),
  227. _("If input file is '-', reads from STDIN."),
  228. _("If output file is '-', dumps output to STDOUT."),
  229. '',
  230. 'http://txt2tags.sourceforge.net',
  231. ''
  232. ], '\n')
  233. ##############################################################################
  234. # Here is all the target's templates
  235. # You may edit them to fit your needs
  236. # - the %(HEADERn)s strings represent the Header lines
  237. # - the %(STYLE)s string is changed by --style contents
  238. # - the %(ENCODING)s string is changed by --encoding contents
  239. # - if any of the above is empty, the full line is removed
  240. # - use %% to represent a literal %
  241. #
  242. HEADER_TEMPLATE = {
  243. 'txt': """\
  244. %(HEADER1)s
  245. %(HEADER2)s
  246. %(HEADER3)s
  247. """,
  248. 'sgml': """\
  249. <!doctype linuxdoc system>
  250. <article>
  251. <title>%(HEADER1)s
  252. <author>%(HEADER2)s
  253. <date>%(HEADER3)s
  254. """,
  255. 'html': """\
  256. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  257. <HTML>
  258. <HEAD>
  259. <META NAME="generator" CONTENT="http://txt2tags.sf.net">
  260. <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s">
  261. <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s">
  262. <TITLE>%(HEADER1)s</TITLE>
  263. </HEAD><BODY BGCOLOR="white" TEXT="black">
  264. <P ALIGN="center"><CENTER><H1>%(HEADER1)s</H1>
  265. <FONT SIZE="4">
  266. <I>%(HEADER2)s</I><BR>
  267. %(HEADER3)s
  268. </FONT></CENTER>
  269. """,
  270. 'htmlcss': """\
  271. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  272. <HTML>
  273. <HEAD>
  274. <META NAME="generator" CONTENT="http://txt2tags.sf.net">
  275. <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s">
  276. <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s">
  277. <TITLE>%(HEADER1)s</TITLE>
  278. </HEAD>
  279. <BODY>
  280. <DIV CLASS="header" ID="header">
  281. <H1>%(HEADER1)s</H1>
  282. <H2>%(HEADER2)s</H2>
  283. <H3>%(HEADER3)s</H3>
  284. </DIV>
  285. """,
  286. 'xhtml': """\
  287. <?xml version="1.0"
  288. encoding="%(ENCODING)s"
  289. ?>
  290. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\
  291. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  292. <html xmlns="http://www.w3.org/1999/xhtml">
  293. <head>
  294. <title>%(HEADER1)s</title>
  295. <meta name="generator" content="http://txt2tags.sf.net" />
  296. <link rel="stylesheet" type="text/css" href="%(STYLE)s" />
  297. </head>
  298. <body bgcolor="white" text="black">
  299. <div align="center">
  300. <h1>%(HEADER1)s</h1>
  301. <h2>%(HEADER2)s</h2>
  302. <h3>%(HEADER3)s</h3>
  303. </div>
  304. """,
  305. 'xhtmlcss': """\
  306. <?xml version="1.0"
  307. encoding="%(ENCODING)s"
  308. ?>
  309. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\
  310. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  311. <html xmlns="http://www.w3.org/1999/xhtml">
  312. <head>
  313. <title>%(HEADER1)s</title>
  314. <meta name="generator" content="http://txt2tags.sf.net" />
  315. <link rel="stylesheet" type="text/css" href="%(STYLE)s" />
  316. </head>
  317. <body>
  318. <div class="header" id="header">
  319. <h1>%(HEADER1)s</h1>
  320. <h2>%(HEADER2)s</h2>
  321. <h3>%(HEADER3)s</h3>
  322. </div>
  323. """,
  324. 'man': """\
  325. .TH "%(HEADER1)s" 1 "%(HEADER3)s" "%(HEADER2)s"
  326. """,
  327. # TODO style to <HR>
  328. 'pm6': """\
  329. <PMTags1.0 win><C-COLORTABLE ("Preto" 1 0 0 0)
  330. ><@Normal=
  331. <FONT "Times New Roman"><CCOLOR "Preto"><SIZE 11>
  332. <HORIZONTAL 100><LETTERSPACE 0><CTRACK 127><CSSIZE 70><C+SIZE 58.3>
  333. <C-POSITION 33.3><C+POSITION 33.3><P><CBASELINE 0><CNOBREAK 0><CLEADING -0.05>
  334. <GGRID 0><GLEFT 7.2><GRIGHT 0><GFIRST 0><G+BEFORE 7.2><G+AFTER 0>
  335. <GALIGNMENT "justify"><GMETHOD "proportional"><G& "ENGLISH">
  336. <GPAIRS 12><G%% 120><GKNEXT 0><GKWIDOW 0><GKORPHAN 0><GTABS $>
  337. <GHYPHENATION 2 34 0><GWORDSPACE 75 100 150><GSPACE -5 0 25>
  338. ><@Bullet=<@-PARENT "Normal"><FONT "Abadi MT Condensed Light">
  339. <GLEFT 14.4><G+BEFORE 2.15><G%% 110><GTABS(25.2 l "")>
  340. ><@PreFormat=<@-PARENT "Normal"><FONT "Lucida Console"><SIZE 8><CTRACK 0>
  341. <GLEFT 0><G+BEFORE 0><GALIGNMENT "left"><GWORDSPACE 100 100 100><GSPACE 0 0 0>
  342. ><@Title1=<@-PARENT "Normal"><FONT "Arial"><SIZE 14><B>
  343. <GCONTENTS><GLEFT 0><G+BEFORE 0><GALIGNMENT "left">
  344. ><@Title2=<@-PARENT "Title1"><SIZE 12><G+BEFORE 3.6>
  345. ><@Title3=<@-PARENT "Title1"><SIZE 10><GLEFT 7.2><G+BEFORE 7.2>
  346. ><@Title4=<@-PARENT "Title3">
  347. ><@Title5=<@-PARENT "Title3">
  348. ><@Quote=<@-PARENT "Normal"><SIZE 10><I>>
  349. %(HEADER1)s
  350. %(HEADER2)s
  351. %(HEADER3)s
  352. """,
  353. 'mgp': """\
  354. #!/usr/X11R6/bin/mgp -t 90
  355. %%deffont "normal" xfont "utopia-medium-r", charset "iso8859-1"
  356. %%deffont "normal-i" xfont "utopia-medium-i", charset "iso8859-1"
  357. %%deffont "normal-b" xfont "utopia-bold-r" , charset "iso8859-1"
  358. %%deffont "normal-bi" xfont "utopia-bold-i" , charset "iso8859-1"
  359. %%deffont "mono" xfont "courier-medium-r", charset "iso8859-1"
  360. %%default 1 size 5
  361. %%default 2 size 8, fore "yellow", font "normal-b", center
  362. %%default 3 size 5, fore "white", font "normal", left, prefix " "
  363. %%tab 1 size 4, vgap 30, prefix " ", icon arc "red" 40, leftfill
  364. %%tab 2 prefix " ", icon arc "orange" 40, leftfill
  365. %%tab 3 prefix " ", icon arc "brown" 40, leftfill
  366. %%tab 4 prefix " ", icon arc "darkmagenta" 40, leftfill
  367. %%tab 5 prefix " ", icon arc "magenta" 40, leftfill
  368. %%%%------------------------- end of headers -----------------------------
  369. %%page
  370. %%size 10, center, fore "yellow"
  371. %(HEADER1)s
  372. %%font "normal-i", size 6, fore "white", center
  373. %(HEADER2)s
  374. %%font "mono", size 7, center
  375. %(HEADER3)s
  376. """,
  377. 'moin': """\
  378. '''%(HEADER1)s'''
  379. ''%(HEADER2)s''
  380. %(HEADER3)s
  381. """,
  382. 'tex': \
  383. r"""\documentclass{article}
  384. \usepackage{graphicx}
  385. \usepackage[urlcolor=blue,colorlinks=true]{hyperref}
  386. \usepackage[%(ENCODING)s]{inputenc} %% char encoding
  387. \usepackage{%(STYLE)s} %% user defined
  388. \title{%(HEADER1)s}
  389. \author{%(HEADER2)s}
  390. \begin{document}
  391. \date{%(HEADER3)s}
  392. \maketitle
  393. \clearpage
  394. """,
  395. 'lout': """\
  396. @SysInclude { doc }
  397. @Document
  398. @InitialFont { Times Base 12p } # Times, Courier, Helvetica, ...
  399. @PageOrientation { Portrait } # Portrait, Landscape
  400. @ColumnNumber { 1 } # Number of columns (2, 3, ...)
  401. @PageHeaders { Simple } # None, Simple, Titles, NoTitles
  402. @InitialLanguage { English } # German, French, Portuguese, ...
  403. @OptimizePages { Yes } # Yes/No smart page break feature
  404. //
  405. @Text @Begin
  406. @Display @Heading { %(HEADER1)s }
  407. @Display @I { %(HEADER2)s }
  408. @Display { %(HEADER3)s }
  409. #@NP # Break page after Headers
  410. """
  411. # @SysInclude { tbl } # Tables support
  412. # setup: @MakeContents { Yes } # show TOC
  413. # setup: @SectionGap # break page at each section
  414. }
  415. ##############################################################################
  416. def getTags(config):
  417. "Returns all the known tags for the specified target"
  418. keys = [
  419. 'paragraphOpen','paragraphClose',
  420. 'title1','title2','title3','title4','title5',
  421. 'title1Open','title1Close','title2Open','title2Close',
  422. 'blocktitle1Open','title1Close','title2Open','title2Close',
  423. 'title3Open','title3Close','title4Open','title4Close',
  424. 'title5Open','title5Close',
  425. 'numtitle1','numtitle2','numtitle3','numtitle4','numtitle5',
  426. 'blockVerbOpen','blockVerbClose',
  427. 'blockQuoteOpen','blockQuoteClose','blockQuoteLine',
  428. 'blockCommentOpen','blockCommentClose',
  429. 'fontMonoOpen','fontMonoClose',
  430. 'fontBoldOpen','fontBoldClose',
  431. 'fontItalicOpen','fontItalicClose',
  432. 'fontUnderlineOpen','fontUnderlineClose',
  433. 'listOpen','listClose',
  434. 'listItemOpen','listItemClose','listItemLine',
  435. 'numlistOpen','numlistClose',
  436. 'numlistItemOpen','numlistItemClose','numlistItemLine',
  437. 'deflistOpen','deflistClose',
  438. 'deflistItem1Open','deflistItem1Close',
  439. 'deflistItem2Open','deflistItem2Close',
  440. 'bar1','bar2',
  441. 'url','urlMark','email','emailMark',
  442. 'img','imgAlignLeft','imgAlignRight','imgAlignCenter',
  443. 'tableOpen','tableClose',
  444. 'tableRowOpen','tableRowClose','tableRowSep',
  445. 'tableCellOpen','tableCellClose','tableCellSep',
  446. 'tableTitleCellOpen','tableTitleCellClose','tableTitleCellSep',
  447. 'tableTitleRowOpen','tableTitleRowClose',
  448. 'tableBorder', 'tableAlignLeft', 'tableAlignCenter',
  449. 'tableCellAlignLeft','tableCellAlignRight','tableCellAlignCenter',
  450. 'tableColAlignLeft','tableColAlignRight','tableColAlignCenter',
  451. 'tableColAlignSep', 'tableCellColSpan',
  452. 'anchor','comment','pageBreak',
  453. 'TOC','tocOpen','tocClose',
  454. 'cssOpen', 'cssClose',
  455. 'bodyOpen','bodyClose',
  456. 'EOD'
  457. ]
  458. # TIP: \a represents the current text on the mark
  459. # TIP: ~A~, ~B~ and ~C~ are expanded to other tags parts
  460. alltags = {
  461. 'txt': {
  462. 'title1' : ' \a' ,
  463. 'title2' : '\t\a' ,
  464. 'title3' : '\t\t\a' ,
  465. 'title4' : '\t\t\t\a' ,
  466. 'title5' : '\t\t\t\t\a',
  467. 'blockQuoteLine' : '\t' ,
  468. 'listItemOpen' : '- ' ,
  469. 'numlistItemOpen' : '\a. ' ,
  470. 'bar1' : '\a' ,
  471. 'url' : '\a' ,
  472. 'urlMark' : '\a (\a)' ,
  473. 'email' : '\a' ,
  474. 'emailMark' : '\a (\a)' ,
  475. 'img' : '[\a]' ,
  476. },
  477. 'html': {
  478. 'paragraphOpen' : '<P>' ,
  479. 'paragraphClose' : '</P>' ,
  480. 'title1' : '~A~<H1>\a</H1>' ,
  481. 'title2' : '~A~<H2>\a</H2>' ,
  482. 'title3' : '~A~<H3>\a</H3>' ,
  483. 'title4' : '~A~<H4>\a</H4>' ,
  484. 'title5' : '~A~<H5>\a</H5>' ,
  485. 'blockVerbOpen' : '<PRE>' ,
  486. 'blockVerbClose' : '</PRE>' ,
  487. 'blockQuoteOpen' : '<BLOCKQUOTE>' ,
  488. 'blockQuoteClose' : '</BLOCKQUOTE>' ,
  489. 'fontMonoOpen' : '<CODE>' ,
  490. 'fontMonoClose' : '</CODE>' ,
  491. 'fontBoldOpen' : '<B>' ,
  492. 'fontBoldClose' : '</B>' ,
  493. 'fontItalicOpen' : '<I>' ,
  494. 'fontItalicClose' : '</I>' ,
  495. 'fontUnderlineOpen' : '<U>' ,
  496. 'fontUnderlineClose' : '</U>' ,
  497. 'listOpen' : '<UL>' ,
  498. 'listClose' : '</UL>' ,
  499. 'listItemOpen' : '<LI>' ,
  500. 'numlistOpen' : '<OL>' ,
  501. 'numlistClose' : '</OL>' ,
  502. 'numlistItemOpen' : '<LI>' ,
  503. 'deflistOpen' : '<DL>' ,
  504. 'deflistClose' : '</DL>' ,
  505. 'deflistItem1Open' : '<DT>' ,
  506. 'deflistItem1Close' : '</DT>' ,
  507. 'deflistItem2Open' : '<DD>' ,
  508. 'bar1' : '<HR NOSHADE SIZE=1>' ,
  509. 'bar2' : '<HR NOSHADE SIZE=5>' ,
  510. 'url' : '<A HREF="\a">\a</A>' ,
  511. 'urlMark' : '<A HREF="\a">\a</A>' ,
  512. 'email' : '<A HREF="mailto:\a">\a</A>' ,
  513. 'emailMark' : '<A HREF="mailto:\a">\a</A>' ,
  514. 'img' : '<IMG~A~ SRC="\a" BORDER="0" ALT="">',
  515. 'imgAlignLeft' : ' ALIGN="left"' ,
  516. 'imgAlignCenter' : ' ALIGN="middle"',
  517. 'imgAlignRight' : ' ALIGN="right"' ,
  518. 'tableOpen' : '<TABLE~A~ CELLPADDING="4"~B~>',
  519. 'tableClose' : '</TABLE>' ,
  520. 'tableRowOpen' : '<TR>' ,
  521. 'tableRowClose' : '</TR>' ,
  522. 'tableCellOpen' : '<TD~A~~S~>' ,
  523. 'tableCellClose' : '</TD>' ,
  524. 'tableTitleCellOpen' : '<TH~S~>' ,
  525. 'tableTitleCellClose' : '</TH>' ,
  526. 'tableBorder' : ' BORDER="1"' ,
  527. 'tableAlignCenter' : ' ALIGN="center"',
  528. 'tableCellAlignRight' : ' ALIGN="right"' ,
  529. 'tableCellAlignCenter': ' ALIGN="center"',
  530. 'tableCellColSpan' : ' COLSPAN="\a"' ,
  531. 'anchor' : '<A NAME="\a"></A>\n',
  532. 'cssOpen' : '<STYLE TYPE="text/css">',
  533. 'cssClose' : '</STYLE>' ,
  534. 'comment' : '<!-- \a -->' ,
  535. 'EOD' : '</BODY></HTML>'
  536. },
  537. #TIP xhtml inherits all HTML definitions (lowercased)
  538. #TIP http://www.w3.org/TR/xhtml1/#guidelines
  539. #TIP http://www.htmlref.com/samples/Chapt17/17_08.htm
  540. 'xhtml': {
  541. 'listItemClose' : '</li>' ,
  542. 'numlistItemClose' : '</li>' ,
  543. 'deflistItem2Close' : '</dd>' ,
  544. 'bar1' : '<hr class="light" />',
  545. 'bar2' : '<hr class="heavy" />',
  546. 'anchor' : '<a id="\a" name="\a"></a>\n',
  547. 'img' : '<img~A~ src="\a" border="0" alt=""/>',
  548. },
  549. 'sgml': {
  550. 'paragraphOpen' : '<p>' ,
  551. 'title1' : '<sect>\a~A~<p>' ,
  552. 'title2' : '<sect1>\a~A~<p>' ,
  553. 'title3' : '<sect2>\a~A~<p>' ,
  554. 'title4' : '<sect3>\a~A~<p>' ,
  555. 'title5' : '<sect4>\a~A~<p>' ,
  556. 'blockVerbOpen' : '<tscreen><verb>' ,
  557. 'blockVerbClose' : '</verb></tscreen>' ,
  558. 'blockQuoteOpen' : '<quote>' ,
  559. 'blockQuoteClose' : '</quote>' ,
  560. 'fontMonoOpen' : '<tt>' ,
  561. 'fontMonoClose' : '</tt>' ,
  562. 'fontBoldOpen' : '<bf>' ,
  563. 'fontBoldClose' : '</bf>' ,
  564. 'fontItalicOpen' : '<em>' ,
  565. 'fontItalicClose' : '</em>' ,
  566. 'fontUnderlineOpen' : '<bf><em>' ,
  567. 'fontUnderlineClose' : '</em></bf>' ,
  568. 'listOpen' : '<itemize>' ,
  569. 'listClose' : '</itemize>' ,
  570. 'listItemOpen' : '<item>' ,
  571. 'numlistOpen' : '<enum>' ,
  572. 'numlistClose' : '</enum>' ,
  573. 'numlistItemOpen' : '<item>' ,
  574. 'deflistOpen' : '<descrip>' ,
  575. 'deflistClose' : '</descrip>' ,
  576. 'deflistItem1Open' : '<tag>' ,
  577. 'deflistItem1Close' : '</tag>' ,
  578. 'bar1' : '<!-- \a -->' ,
  579. 'url' : '<htmlurl url="\a" name="\a">' ,
  580. 'urlMark' : '<htmlurl url="\a" name="\a">' ,
  581. 'email' : '<htmlurl url="mailto:\a" name="\a">' ,
  582. 'emailMark' : '<htmlurl url="mailto:\a" name="\a">' ,
  583. 'img' : '<figure><ph vspace=""><img src="\a">'+\
  584. '</figure>' ,
  585. 'tableOpen' : '<table><tabular ca="~C~">' ,
  586. 'tableClose' : '</tabular></table>' ,
  587. 'tableRowSep' : '<rowsep>' ,
  588. 'tableCellSep' : '<colsep>' ,
  589. 'tableColAlignLeft' : 'l' ,
  590. 'tableColAlignRight' : 'r' ,
  591. 'tableColAlignCenter' : 'c' ,
  592. 'comment' : '<!-- \a -->' ,
  593. 'anchor' : '<label id="\a">' ,
  594. 'TOC' : '<toc>' ,
  595. 'EOD' : '</article>'
  596. },
  597. 'tex': {
  598. 'title1' : '\n\section*{\a}' ,
  599. 'title2' : '\\subsection*{\a}' ,
  600. 'title3' : '\\subsubsection*{\a}',
  601. # title 4/5: DIRTY: para+BF+\\+\n
  602. 'title4' : '\\paragraph{}\\textbf{\a}\\\\\n',
  603. 'title5' : '\\paragraph{}\\textbf{\a}\\\\\n',
  604. 'numtitle1' : '\n\section{\a}' ,
  605. 'numtitle2' : '\\subsection{\a}' ,
  606. 'numtitle3' : '\\subsubsection{\a}' ,
  607. 'blockVerbOpen' : '\\begin{verbatim}' ,
  608. 'blockVerbClose' : '\\end{verbatim}' ,
  609. 'blockQuoteOpen' : '\\begin{quotation}' ,
  610. 'blockQuoteClose' : '\\end{quotation}' ,
  611. 'fontMonoOpen' : '\\texttt{' ,
  612. 'fontMonoClose' : '}' ,
  613. 'fontBoldOpen' : '\\textbf{' ,
  614. 'fontBoldClose' : '}' ,
  615. 'fontItalicOpen' : '\\textit{' ,
  616. 'fontItalicClose' : '}' ,
  617. 'fontUnderlineOpen' : '\\underline{' ,
  618. 'fontUnderlineClose' : '}' ,
  619. 'listOpen' : '\\begin{itemize}' ,
  620. 'listClose' : '\\end{itemize}' ,
  621. 'listItemOpen' : '\\item ' ,
  622. 'numlistOpen' : '\\begin{enumerate}' ,
  623. 'numlistClose' : '\\end{enumerate}' ,
  624. 'numlistItemOpen' : '\\item ' ,
  625. 'deflistOpen' : '\\begin{description}',
  626. 'deflistClose' : '\\end{description}' ,
  627. 'deflistItem1Open' : '\\item[' ,
  628. 'deflistItem1Close' : ']' ,
  629. 'bar1' : '\n\\hrulefill{}\n' ,
  630. 'bar2' : '\n\\rule{\linewidth}{1mm}\n',
  631. 'url' : '\\htmladdnormallink{\a}{\a}',
  632. 'urlMark' : '\\htmladdnormallink{\a}{\a}',
  633. 'email' : '\\htmladdnormallink{\a}{mailto:\a}',
  634. 'emailMark' : '\\htmladdnormallink{\a}{mailto:\a}',
  635. 'img' : '\\includegraphics{\a}',
  636. 'tableOpen' : '\\begin{center}\\begin{tabular}{|~C~|}',
  637. 'tableClose' : '\\end{tabular}\\end{center}',
  638. 'tableRowOpen' : '\\hline ' ,
  639. 'tableRowClose' : ' \\\\' ,
  640. 'tableCellSep' : ' & ' ,
  641. 'tableColAlignLeft' : 'l' ,
  642. 'tableColAlignRight' : 'r' ,
  643. 'tableColAlignCenter' : 'c' ,
  644. 'tableColAlignSep' : '|' ,
  645. 'comment' : '% \a' ,
  646. 'TOC' : '\\tableofcontents',
  647. 'pageBreak' : '\\clearpage',
  648. 'EOD' : '\\end{document}'
  649. },
  650. 'lout': {
  651. 'paragraphOpen' : '@LP' ,
  652. 'blockTitle1Open' : '@BeginSections' ,
  653. 'blockTitle1Close' : '@EndSections' ,
  654. 'blockTitle2Open' : ' @BeginSubSections' ,
  655. 'blockTitle2Close' : ' @EndSubSections' ,
  656. 'blockTitle3Open' : ' @BeginSubSubSections' ,
  657. 'blockTitle3Close' : ' @EndSubSubSections' ,
  658. 'title1Open' : '\n@Section @Title { \a } @Begin',
  659. 'title1Close' : '@End @Section' ,
  660. 'title2Open' : '\n @SubSection @Title { \a } @Begin',
  661. 'title2Close' : ' @End @SubSection' ,
  662. 'title3Open' : '\n @SubSubSection @Title { \a } @Begin',
  663. 'title3Close' : ' @End @SubSubSection' ,
  664. 'title4Open' : '\n@LP @LeftDisplay @B { \a }',
  665. 'title5Open' : '\n@LP @LeftDisplay @B { \a }',
  666. 'anchor' : '@Tag { \a }' ,
  667. 'blockVerbOpen' : '@LP @ID @F @RawVerbatim @Begin',
  668. 'blockVerbClose' : '@End @RawVerbatim' ,
  669. 'blockQuoteOpen' : '@QD {' ,
  670. 'blockQuoteClose' : '}' ,
  671. # enclosed inside {} to deal with joined**words**
  672. 'fontMonoOpen' : '{@F {' ,
  673. 'fontMonoClose' : '}}' ,
  674. 'fontBoldOpen' : '{@B {' ,
  675. 'fontBoldClose' : '}}' ,
  676. 'fontItalicOpen' : '{@II {' ,
  677. 'fontItalicClose' : '}}' ,
  678. 'fontUnderlineOpen' : '{@Underline{' ,
  679. 'fontUnderlineClose' : '}}' ,
  680. # the full form is more readable, but could be BL EL LI NL TL DTI
  681. 'listOpen' : '@BulletList' ,
  682. 'listClose' : '@EndList' ,
  683. 'listItemOpen' : '@ListItem{' ,
  684. 'listItemClose' : '}' ,
  685. 'numlistOpen' : '@NumberedList' ,
  686. 'numlistClose' : '@EndList' ,
  687. 'numlistItemOpen' : '@ListItem{' ,
  688. 'numlistItemClose' : '}' ,
  689. 'deflistOpen' : '@TaggedList' ,
  690. 'deflistClose' : '@EndList' ,
  691. 'deflistItem1Open' : '@DropTagItem {' ,
  692. 'deflistItem1Close' : '}' ,
  693. 'deflistItem2Open' : '{' ,
  694. 'deflistItem2Close' : '}' ,
  695. 'bar1' : '\n@DP @FullWidthRule\n' ,
  696. 'url' : '{blue @Colour { \a }}' ,
  697. 'urlMark' : '\a ({blue @Colour { \a }})' ,
  698. 'email' : '{blue @Colour { \a }}' ,
  699. 'emailMark' : '\a ({blue Colour{ \a }})' ,
  700. 'img' : '~A~@IncludeGraphic { \a }' , # eps only!
  701. 'imgAlignLeft' : '@LeftDisplay ' ,
  702. 'imgAlignRight' : '@RightDisplay ' ,
  703. 'imgAlignCenter' : '@CentredDisplay ' ,
  704. # lout tables are *way* complicated, no support for now
  705. #'tableOpen' : '~A~@Tbl~B~\naformat{ @Cell A | @Cell B } {',
  706. #'tableClose' : '}' ,
  707. #'tableRowOpen' : '@Rowa\n' ,
  708. #'tableTitleRowOpen' : '@HeaderRowa' ,
  709. #'tableCenterAlign' : '@CentredDisplay ' ,
  710. #'tableCellOpen' : '\a {' , # A, B, ...
  711. #'tableCellClose' : '}' ,
  712. #'tableBorder' : '\nrule {yes}' ,
  713. 'comment' : '# \a' ,
  714. # @MakeContents must be on the config file
  715. 'TOC' : '@DP @ContentsGoesHere @DP',
  716. 'pageBreak' : '\n@NP\n' ,
  717. 'EOD' : '@End @Text'
  718. },
  719. 'moin': {
  720. 'title1' : '= \a =' ,
  721. 'title2' : '== \a ==' ,
  722. 'title3' : '=== \a ===' ,
  723. 'title4' : '==== \a ====' ,
  724. 'title5' : '===== \a =====',
  725. 'blockVerbOpen' : '{{{' ,
  726. 'blockVerbClose' : '}}}' ,
  727. 'blockQuoteLine' : ' ' ,
  728. 'fontMonoOpen' : '{{{' ,
  729. 'fontMonoClose' : '}}}' ,
  730. 'fontBoldOpen' : "'''" ,
  731. 'fontBoldClose' : "'''" ,
  732. 'fontItalicOpen' : "''" ,
  733. 'fontItalicClose' : "''" ,
  734. 'fontUnderlineOpen' : "__" ,
  735. 'fontUnderlineClose' : "__" ,
  736. 'listItemOpen' : ' * ' ,
  737. 'numlistItemOpen' : ' \a. ' ,
  738. 'bar1' : '----' ,
  739. 'url' : '[\a]' ,
  740. 'urlMark' : '[\a \a]' ,
  741. 'email' : '[\a]' ,
  742. 'emailMark' : '[\a \a]' ,
  743. 'img' : '[\a]' ,
  744. 'tableRowOpen' : '||' ,
  745. 'tableCellOpen' : '~A~' ,
  746. 'tableCellClose' : '||' ,
  747. 'tableTitleCellClose' : '||' ,
  748. 'tableCellAlignRight' : '<)>' ,
  749. 'tableCellAlignCenter': '<:>' ,
  750. 'comment' : '## \a' ,
  751. 'TOC' : '[[TableOfContents]]'
  752. },
  753. 'mgp': {
  754. 'paragraphOpen' : '%font "normal", size 5' ,
  755. 'title1' : '%page\n\n\a\n' ,
  756. 'title2' : '%page\n\n\a\n' ,
  757. 'title3' : '%page\n\n\a\n' ,
  758. 'title4' : '%page\n\n\a\n' ,
  759. 'title5' : '%page\n\n\a\n' ,
  760. 'blockVerbOpen' : '%font "mono"' ,
  761. 'blockVerbClose' : '%font "normal"' ,
  762. 'blockQuoteOpen' : '%prefix " "' ,
  763. 'blockQuoteClose' : '%prefix " "' ,
  764. 'fontMonoOpen' : '\n%cont, font "mono"\n' ,
  765. 'fontMonoClose' : '\n%cont, font "normal"\n' ,
  766. 'fontBoldOpen' : '\n%cont, font "normal-b"\n' ,
  767. 'fontBoldClose' : '\n%cont, font "normal"\n' ,
  768. 'fontItalicOpen' : '\n%cont, font "normal-i"\n' ,
  769. 'fontItalicClose' : '\n%cont, font "normal"\n' ,
  770. 'fontUnderlineOpen' : '\n%cont, fore "cyan"\n' ,
  771. 'fontUnderlineClose' : '\n%cont, fore "white"\n' ,
  772. 'listItemLine' : '\t' ,
  773. 'numlistItemLine' : '\t' ,
  774. 'deflistItem1Open' : '\t\n%cont, font "normal-b"\n',
  775. 'deflistItem1Close' : '\n%cont, font "normal"\n' ,
  776. 'bar1' : '%bar "white" 5' ,
  777. 'bar2' : '%pause' ,
  778. 'url' : '\n%cont, fore "cyan"\n\a' +\
  779. '\n%cont, fore "white"\n' ,
  780. 'urlMark' : '\a \n%cont, fore "cyan"\n\a'+\
  781. '\n%cont, fore "white"\n' ,
  782. 'email' : '\n%cont, fore "cyan"\n\a' +\
  783. '\n%cont, fore "white"\n' ,
  784. 'emailMark' : '\a \n%cont, fore "cyan"\n\a'+\
  785. '\n%cont, fore "white"\n' ,
  786. 'img' : '~A~\n%newimage "\a"\n%left\n',
  787. 'imgAlignLeft' : '\n%left' ,
  788. 'imgAlignRight' : '\n%right' ,
  789. 'imgAlignCenter' : '\n%center' ,
  790. 'comment' : '%% \a' ,
  791. 'pageBreak' : '%page\n\n\n' ,
  792. 'EOD' : '%%EOD'
  793. },
  794. # man groff_man ; man 7 groff
  795. 'man': {
  796. 'paragraphOpen' : '.P' ,
  797. 'title1' : '.SH \a' ,
  798. 'title2' : '.SS \a' ,
  799. 'title3' : '.SS \a' ,
  800. 'title4' : '.SS \a' ,
  801. 'title5' : '.SS \a' ,
  802. 'blockVerbOpen' : '.nf' ,
  803. 'blockVerbClose' : '.fi\n' ,
  804. 'blockQuoteOpen' : '.RS' ,
  805. 'blockQuoteClose' : '.RE' ,
  806. 'fontBoldOpen' : '\\fB' ,
  807. 'fontBoldClose' : '\\fR' ,
  808. 'fontItalicOpen' : '\\fI' ,
  809. 'fontItalicClose' : '\\fR' ,
  810. 'listOpen' : '.RS' ,
  811. 'listItemOpen' : '.IP \(bu 3\n',
  812. 'listClose' : '.RE' ,
  813. 'numlistOpen' : '.RS' ,
  814. 'numlistItemOpen' : '.IP \a. 3\n',
  815. 'numlistClose' : '.RE' ,
  816. 'deflistItem1Open' : '.TP\n' ,
  817. 'bar1' : '\n\n' ,
  818. 'url' : '\a' ,
  819. 'urlMark' : '\a (\a)',
  820. 'email' : '\a' ,
  821. 'emailMark' : '\a (\a)',
  822. 'img' : '\a' ,
  823. 'tableOpen' : '.TS\n~A~~B~tab(^); ~C~.',
  824. 'tableClose' : '.TE' ,
  825. 'tableRowOpen' : ' ' ,
  826. 'tableCellSep' : '^' ,
  827. 'tableAlignCenter' : 'center, ',
  828. 'tableBorder' : 'allbox, ',
  829. 'tableColAlignLeft' : 'l' ,
  830. 'tableColAlignRight' : 'r' ,
  831. 'tableColAlignCenter' : 'c' ,
  832. 'comment' : '.\\" \a'
  833. },
  834. 'pm6': {
  835. 'paragraphOpen' : '<@Normal:>' ,
  836. 'title1' : '\n<@Title1:>\a',
  837. 'title2' : '\n<@Title2:>\a',
  838. 'title3' : '\n<@Title3:>\a',
  839. 'title4' : '\n<@Title4:>\a',
  840. 'title5' : '\n<@Title5:>\a',
  841. 'blockVerbOpen' : '<@PreFormat:>' ,
  842. 'blockQuoteLine' : '<@Quote:>' ,
  843. 'fontMonoOpen' : '<FONT "Lucida Console"><SIZE 9>' ,
  844. 'fontMonoClose' : '<SIZE$><FONT$>',
  845. 'fontBoldOpen' : '<B>' ,
  846. 'fontBoldClose' : '<P>' ,
  847. 'fontItalicOpen' : '<I>' ,
  848. 'fontItalicClose' : '<P>' ,
  849. 'fontUnderlineOpen' : '<U>' ,
  850. 'fontUnderlineClose' : '<P>' ,
  851. 'listOpen' : '<@Bullet:>' ,
  852. 'listItemOpen' : '\x95\t' , # \x95 == ~U
  853. 'numlistOpen' : '<@Bullet:>' ,
  854. 'numlistItemOpen' : '\x95\t' ,
  855. 'bar1' : '\a' ,
  856. 'url' : '<U>\a<P>' , # underline
  857. 'urlMark' : '\a <U>\a<P>' ,
  858. 'email' : '\a' ,
  859. 'emailMark' : '\a \a' ,
  860. 'img' : '\a'
  861. }
  862. }
  863. # Exceptions for --css-sugar
  864. if config['css-sugar'] and config['target'] in ('html','xhtml'):
  865. # Change just HTML because XHTML inherits it
  866. htmltags = alltags['html']
  867. # Table with no cellpadding
  868. htmltags['tableOpen'] = string.replace(
  869. htmltags['tableOpen'], ' CELLPADDING="4"', '')
  870. # DIVs
  871. htmltags['tocOpen' ] = '<DIV CLASS="toc" ID="toc">'
  872. htmltags['tocClose'] = '</DIV>'
  873. htmltags['bodyOpen'] = '<DIV CLASS="body" ID="body">'
  874. htmltags['bodyClose']= '</DIV>'
  875. # Make the HTML -> XHTML inheritance
  876. xhtml = alltags['html'].copy()
  877. for key in xhtml.keys(): xhtml[key] = string.lower(xhtml[key])
  878. # Some like HTML tags as lowercase, some don't... (headers out)
  879. if HTML_LOWER: alltags['html'] = xhtml.copy()
  880. xhtml.update(alltags['xhtml'])
  881. alltags['xhtml'] = xhtml.copy()
  882. # Compose the target tags dictionary
  883. tags = {}
  884. target_tags = alltags[config['target']].copy()
  885. for key in keys: tags[key] = '' # create empty keys
  886. for key in target_tags.keys():
  887. tags[key] = maskEscapeChar(target_tags[key]) # populate
  888. # Map strong line to separator if not defined
  889. if not tags['bar2'] and tags['bar1']:
  890. tags['bar2'] = tags['bar1']
  891. return tags
  892. ##############################################################################
  893. def getRules(config):
  894. "Returns all the target-specific syntax rules"
  895. ret = {}
  896. allrules = [
  897. # target rules (ON/OFF)
  898. 'linkable', # target supports external links
  899. 'tableable', # target supports tables
  900. 'imglinkable', # target supports images as links
  901. 'imgalignable', # target supports image alignment
  902. 'imgasdefterm', # target supports image as definition term
  903. 'autonumberlist', # target supports numbered lists natively
  904. 'autonumbertitle', # target supports numbered titles natively
  905. 'stylable', # target supports external style files
  906. 'parainsidelist', # lists items supports paragraph
  907. 'spacedlistitem', # lists support blank lines between items
  908. 'listnotnested', # lists cannot be nested
  909. 'quotenotnested', # quotes cannot be nested
  910. 'verbblocknotescaped', # don't escape specials in verb block
  911. 'verbblockfinalescape', # do final escapes in verb block
  912. 'escapeurl', # escape special in link URL
  913. 'onelinepara', # dump paragraph as a single long line
  914. 'tabletitlerowinbold', # manually bold any cell on table titles
  915. 'tablecellstrip', # strip extra spaces from each table cell
  916. 'tablecellspannable', # the table cells can have span attribute
  917. 'barinsidequote', # bars are allowed inside quote blocks
  918. 'finalescapetitle', # perform final escapes on title lines
  919. 'autotocnewpagebefore', # break page before automatic TOC
  920. 'autotocnewpageafter', # break page after automatic TOC
  921. 'autotocwithbars', # automatic TOC surrounded by bars
  922. 'mapbar2pagebreak', # map the strong bar to a page break
  923. 'titleblocks', # titles must be on open/close section blocks
  924. # Target code beautify (ON/OFF)
  925. 'indentverbblock', # add leading spaces to verb block lines
  926. 'breaktablecell', # break lines after any table cell
  927. 'breaktablelineopen', # break line after opening table line
  928. 'notbreaklistopen', # don't break line after opening a new list
  929. 'notbreakparaopen', # don't break line after opening a new para
  930. 'keepquoteindent', # don't remove the leading TABs on quotes
  931. 'keeplistindent', # don't remove the leading spaces on lists
  932. 'blankendmotherlist', # append a blank line at the mother list end
  933. 'blankendtable', # append a blank line at the table end
  934. 'blankendautotoc', # append a blank line at the auto TOC end
  935. 'tagnotindentable', # tags must be placed at the line begining
  936. # Value settings
  937. 'listmaxdepth', # maximum depth for lists
  938. 'quotemaxdepth', # maximum depth for quotes
  939. 'tablecellaligntype' # type of table cell align: cell, column
  940. ]
  941. rules_bank = {
  942. 'txt' : {
  943. 'indentverbblock':1,
  944. 'spacedlistitem':1,
  945. 'parainsidelist':1,
  946. 'keeplistindent':1,
  947. 'barinsidequote':1,
  948. 'autotocwithbars':1,
  949. 'blankendmotherlist':1
  950. },
  951. 'html': {
  952. 'indentverbblock':1,
  953. 'linkable':1,
  954. 'stylable':1,
  955. 'escapeurl':1,
  956. 'imglinkable':1,
  957. 'imgalignable':1,
  958. 'imgasdefterm':1,
  959. 'autonumberlist':1,
  960. 'spacedlistitem':1,
  961. 'parainsidelist':1,
  962. 'blankendmotherlist':1,
  963. 'tableable':1,
  964. 'tablecellstrip':1,
  965. 'blankendtable':1,
  966. 'breaktablecell':1,
  967. 'breaktablelineopen':1,
  968. 'keeplistindent':1,
  969. 'keepquoteindent':1,
  970. 'barinsidequote':1,
  971. 'autotocwithbars':1,
  972. 'tablecellspannable':1,
  973. 'tablecellaligntype':'cell'
  974. },
  975. #TIP xhtml inherits all HTML rules
  976. 'xhtml': {
  977. },
  978. 'sgml': {
  979. 'linkable':1,
  980. 'escapeurl':1,
  981. 'autonumberlist':1,
  982. 'spacedlistitem':1,
  983. 'blankendmotherlist':1,
  984. 'tableable':1,
  985. 'tablecellstrip':1,
  986. 'blankendtable':1,
  987. 'blankendautotoc':1,
  988. 'quotenotnested':1,
  989. 'keeplistindent':1,
  990. 'keepquoteindent':1,
  991. 'barinsidequote':1,
  992. 'finalescapetitle':1,
  993. 'tablecellaligntype':'column'
  994. },
  995. 'mgp' : {
  996. 'blankendmotherlist':1,
  997. 'tagnotindentable':1,
  998. 'spacedlistitem':1,
  999. 'imgalignable':1,
  1000. 'autotocnewpagebefore':1,
  1001. },
  1002. 'tex' : {
  1003. 'stylable':1,
  1004. 'escapeurl':1,
  1005. 'autonumberlist':1,
  1006. 'autonumbertitle':1,
  1007. 'spacedlistitem':1,
  1008. 'blankendmotherlist':1,
  1009. 'tableable':1,
  1010. 'tablecellstrip':1,
  1011. 'tabletitlerowinbold':1,
  1012. 'blankendtable':1,
  1013. 'verbblocknotescaped':1,
  1014. 'keeplistindent':1,
  1015. 'listmaxdepth':4, # deflist is 6
  1016. 'quotemaxdepth':6,
  1017. 'barinsidequote':1,
  1018. 'finalescapetitle':1,
  1019. 'autotocnewpageafter':1,
  1020. 'mapbar2pagebreak':1,
  1021. 'tablecellaligntype':'column'
  1022. },
  1023. 'lout': {
  1024. 'keepquoteindent':1,
  1025. 'escapeurl':1,
  1026. 'verbblocknotescaped':1,
  1027. 'imgalignable':1,
  1028. 'mapbar2pagebreak':1,
  1029. 'titleblocks':1,
  1030. 'notbreakparaopen':1
  1031. },
  1032. 'moin': {
  1033. 'spacedlistitem':1,
  1034. 'linkable':1,
  1035. 'blankendmotherlist':1,
  1036. 'keeplistindent':1,
  1037. 'tableable':1,
  1038. 'barinsidequote':1,
  1039. 'blankendtable':1,
  1040. 'tabletitlerowinbold':1,
  1041. 'tablecellstrip':1,
  1042. 'autotocwithbars':1,
  1043. 'tablecellaligntype':'cell'
  1044. },
  1045. 'man' : {
  1046. 'spacedlistitem':1,
  1047. 'indentverbblock':1,
  1048. 'blankendmotherlist':1,
  1049. 'tagnotindentable':1,
  1050. 'tableable':1,
  1051. 'tablecellaligntype':'column',
  1052. 'tabletitlerowinbold':1,
  1053. 'tablecellstrip':1,
  1054. 'blankendtable':1,
  1055. 'keeplistindent':0,
  1056. 'barinsidequote':1,
  1057. 'parainsidelist':0,
  1058. },
  1059. 'pm6' : {
  1060. 'keeplistindent':1,
  1061. 'verbblockfinalescape':1,
  1062. #TODO add support for these - maybe set a JOINNEXT char and
  1063. # do it on addLineBreaks()
  1064. 'notbreaklistopen':1,
  1065. 'notbreakparaopen':1,
  1066. 'barinsidequote':1,
  1067. 'autotocwithbars':1,
  1068. 'onelinepara':1,
  1069. }
  1070. }
  1071. # Exceptions for --css-sugar
  1072. if config['css-sugar'] and config['target'] in ('html','xhtml'):
  1073. rules_bank['html']['indentverbblock'] = 0
  1074. rules_bank['html']['autotocwithbars'] = 0
  1075. # Get the target specific rules
  1076. if config['target'] == 'xhtml':
  1077. myrules = rules_bank['html'].copy() # inheritance
  1078. myrules.update(rules_bank['xhtml']) # get XHTML specific
  1079. else:
  1080. myrules = rules_bank[config['target']].copy()
  1081. # Populate return dictionary
  1082. for key in allrules: ret[key] = 0 # reset all
  1083. ret.update(myrules) # get rules
  1084. return ret
  1085. ##############################################################################
  1086. def getRegexes():
  1087. "Returns all the regexes used to find the t2t marks"
  1088. bank = {
  1089. 'blockVerbOpen':
  1090. re.compile(r'^```\s*$'),
  1091. 'blockVerbClose':
  1092. re.compile(r'^```\s*$'),
  1093. 'blockRawOpen':
  1094. re.compile(r'^"""\s*$'),
  1095. 'blockRawClose':
  1096. re.compile(r'^"""\s*$'),
  1097. 'blockCommentOpen':
  1098. re.compile(r'^%%%\s*$'),
  1099. 'blockCommentClose':
  1100. re.compile(r'^%%%\s*$'),
  1101. 'quote':
  1102. re.compile(r'^\t+'),
  1103. '1lineVerb':
  1104. re.compile(r'^``` (?=.)'),
  1105. '1lineRaw':
  1106. re.compile(r'^""" (?=.)'),
  1107. # mono, raw, bold, italic, underline:
  1108. # - marks must be glued with the contents, no boundary spaces
  1109. # - they are greedy, so in ****bold****, turns to <b>**bold**</b>
  1110. 'fontMono':
  1111. re.compile( r'``([^\s](|.*?[^\s])`*)``'),
  1112. 'raw':
  1113. re.compile( r'""([^\s](|.*?[^\s])"*)""'),
  1114. 'fontBold':
  1115. re.compile(r'\*\*([^\s](|.*?[^\s])\**)\*\*'),
  1116. 'fontItalic':
  1117. re.compile( r'//([^\s](|.*?[^\s])/*)//'),
  1118. 'fontUnderline':
  1119. re.compile( r'__([^\s](|.*?[^\s])_*)__'),
  1120. 'list':
  1121. re.compile(r'^( *)(-) (?=[^ ])'),
  1122. 'numlist':
  1123. re.compile(r'^( *)(\+) (?=[^ ])'),
  1124. 'deflist':
  1125. re.compile(r'^( *)(:) (.*)$'),
  1126. 'listclose':
  1127. re.compile(r'^( *)([-+:])\s*$'),
  1128. 'bar':
  1129. re.compile(r'^(\s*)([_=-]{20,})\s*$'),
  1130. 'table':
  1131. re.compile(r'^ *\|\|? '),
  1132. 'blankline':
  1133. re.compile(r'^\s*$'),
  1134. 'comment':
  1135. re.compile(r'^%'),
  1136. # Auxiliary tag regexes
  1137. '_imgAlign' : re.compile(r'~A~', re.I),
  1138. '_tableAlign' : re.compile(r'~A~', re.I),
  1139. '_anchor' : re.compile(r'~A~', re.I),
  1140. '_tableBorder' : re.compile(r'~B~', re.I),
  1141. '_tableColAlign' : re.compile(r'~C~', re.I),
  1142. '_tableCellColSpan': re.compile(r'~S~', re.I),
  1143. '_tableCellAlign' : re.compile(r'~A~', re.I),
  1144. }
  1145. # Special char to place data on TAGs contents (\a == bell)
  1146. bank['x'] = re.compile('\a')
  1147. # %%macroname [ (formatting) ]
  1148. bank['macros'] = re.compile(r'%%%%(?P<name>%s)\b(\((?P<fmt>.*?)\))?'%(
  1149. string.join(MACROS.keys(), '|')), re.I)
  1150. # %%TOC special macro for TOC positioning
  1151. bank['toc'] = re.compile(r'^ *%%toc\s*$', re.I)
  1152. # Almost complicated title regexes ;)
  1153. titskel = r'^ *(?P<id>%s)(?P<txt>%s)\1(\[(?P<label>[\w-]*)\])?\s*$'
  1154. bank[ 'title'] = re.compile(titskel%('[=]{1,5}','[^=](|.*[^=])'))
  1155. bank['numtitle'] = re.compile(titskel%('[+]{1,5}','[^+](|.*[^+])'))
  1156. ### Complicated regexes begin here ;)
  1157. #
  1158. # Textual descriptions on --help's style: [...] is optional, | is OR
  1159. ### First, some auxiliary variables
  1160. #
  1161. # [image.EXT]
  1162. patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))\]'
  1163. # Link things
  1164. # http://www.gbiv.com/protocols/uri/rfc/rfc3986.html
  1165. # pchar: A-Za-z._~- / %FF / !$&'()*+,;= / :@
  1166. # Recomended order: scheme://user:pass@domain/path?query=foo#anchor
  1167. # Also works : scheme://user:pass@domain/path#anchor?query=foo
  1168. # TODO form: !'():
  1169. urlskel = {
  1170. 'proto' : r'(https?|ftp|news|telnet|gopher|wais)://',
  1171. 'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess
  1172. 'login' : r'A-Za-z0-9_.-', # for ftp://login@domain.com
  1173. 'pass' : r'[^ @]*', # for ftp://login:pass@dom.com
  1174. 'chars' : r'A-Za-z0-9%._/~:,=$@&+-', # %20(space), :80(port), D&D
  1175. 'anchor': r'A-Za-z0-9%._-', # %nn(encoded)
  1176. 'form' : r'A-Za-z0-9/%&=+;.,$@*_-', # .,@*_-(as is)
  1177. 'punct' : r'.,;:!?'
  1178. }
  1179. # username [ :password ] @
  1180. patt_url_login = r'([%s]+(:%s)?@)?'%(urlskel['login'],urlskel['pass'])
  1181. # [ http:// ] [ username:password@ ] domain.com [ / ]
  1182. # [ #anchor | ?form=data ]
  1183. retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]*)?'%(
  1184. urlskel['proto'],patt_url_login, urlskel['guess'],
  1185. urlskel['chars'],urlskel['form'],urlskel['anchor'])
  1186. # filename | [ filename ] #anchor
  1187. retxt_url_local = r'[%s]+|[%s]*(#[%s]*)'%(
  1188. urlskel['chars'],urlskel['chars'],urlskel['anchor'])
  1189. # user@domain [ ?form=data ]
  1190. patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?'%(
  1191. urlskel['login'],urlskel['form'])
  1192. # Saving for future use
  1193. bank['_urlskel'] = urlskel
  1194. ### And now the real regexes
  1195. #
  1196. bank['email'] = re.compile(patt_email,re.I)
  1197. # email | url
  1198. bank['link'] = re.compile(r'%s|%s'%(retxt_url,patt_email), re.I)
  1199. # \[ label | imagetag url | email | filename \]
  1200. bank['linkmark'] = re.compile(
  1201. r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]'%(
  1202. patt_img, retxt_url, patt_email, retxt_url_local),
  1203. re.L+re.I)
  1204. # Image
  1205. bank['img'] = re.compile(patt_img, re.L+re.I)
  1206. # Special things
  1207. bank['special'] = re.compile(r'^%!\s*')
  1208. return bank
  1209. ### END OF regex nightmares
  1210. ##############################################################################
  1211. class error(Exception):
  1212. pass
  1213. def echo(msg): # for quick debug
  1214. print '\033[32;1m%s\033[m'%msg
  1215. def Quit(msg=''):
  1216. if msg: print msg
  1217. sys.exit(0)
  1218. def Error(msg):
  1219. msg = _("%s: Error: ")%my_name + msg
  1220. raise error, msg
  1221. def getTraceback():
  1222. try:
  1223. from traceback import format_exception
  1224. etype, value, tb = sys.exc_info()
  1225. return string.join(format_exception(etype, value, tb), '')
  1226. except: pass
  1227. def getUnknownErrorMessage():
  1228. msg = '%s\n%s (%s):\n\n%s'%(
  1229. _('Sorry! Txt2tags aborted by an unknown error.'),
  1230. _('Please send the following Error Traceback to the author'),
  1231. my_email, getTraceback())
  1232. return msg
  1233. def Message(msg,level):
  1234. if level <= VERBOSE and not QUIET:
  1235. prefix = '-'*5
  1236. print "%s %s"%(prefix*level, msg)
  1237. def Debug(msg,id=0,linenr=None):
  1238. "Show debug messages, categorized (colored or not)"
  1239. if QUIET or not DEBUG: return
  1240. if int(id) not in range(8): id = 0
  1241. # 0:black 1:red 2:green 3:yellow 4:blue 5:pink 6:cyan 7:white ;1:light
  1242. ids = ['INI','CFG','SRC','BLK','HLD','GUI','OUT','DET']
  1243. colors_bgdark = ['7;1','1;1','3;1','6;1','4;1','5;1','2;1','7;1']
  1244. colors_bglight = ['0' ,'1' ,'3' ,'6' ,'4' ,'5' ,'2' ,'0' ]
  1245. if linenr is not None: msg = "LINE %04d: %s"%(linenr,msg)
  1246. if COLOR_DEBUG:
  1247. if BG_LIGHT: color = colors_bglight[id]
  1248. else : color = colors_bgdark[id]
  1249. msg = '\033[3%sm%s\033[m'%(color,msg)
  1250. print "++ %s: %s"%(ids[id],msg)
  1251. def Readfile(file, remove_linebreaks=0, ignore_error=0):
  1252. data = []
  1253. if file == '-':
  1254. try: data = sys.stdin.readlines()
  1255. except:
  1256. if not ignore_error:
  1257. Error(_('You must feed me with data on STDIN!'))
  1258. else:
  1259. try: f = open(file); data = f.readlines() ; f.close()
  1260. except:
  1261. if not ignore_error:
  1262. Error(_("Cannot read file:")+" %s"%file)
  1263. if remove_linebreaks:
  1264. data = map(lambda x:re.sub('[\n\r]+$','',x), data)
  1265. Message(_("File read (%d lines): %s")%(len(data),file),2)
  1266. return data
  1267. def Savefile(file, contents):
  1268. try: f = open(file, 'wb')
  1269. except: Error(_("Cannot open file for writing:")+" %s"%file)
  1270. if type(contents) == type([]): doit = f.writelines
  1271. else: doit = f.write
  1272. doit(contents) ; f.close()
  1273. def showdic(dic):
  1274. for k in dic.keys(): print "%15s : %s" % (k,dic[k])
  1275. def dotted_spaces(txt=''):
  1276. return string.replace(txt,' ','.')
  1277. # TIP: win env vars http://www.winnetmag.com/Article/ArticleID/23873/23873.html
  1278. def get_rc_path():
  1279. "Return the full path for the users' RC file"
  1280. # Try to get the path from an env var. if yes, we're done
  1281. user_defined = os.environ.get('T2TCONFIG')
  1282. if user_defined: return user_defined
  1283. # Env var not found, so perform automatic path composing
  1284. # Set default filename according system platform
  1285. rc_names = {'default':'.txt2tagsrc', 'win':'_t2trc'}
  1286. rc_file = rc_names.get(sys.platform[:3]) or rc_names['default']
  1287. # The file must be on the user directory, but where is this dir?
  1288. rc_dir_search = ['HOME', 'HOMEPATH']
  1289. for var in rc_dir_search:
  1290. rc_dir = os.environ.get(var)
  1291. if rc_dir: break
  1292. # rc dir found, now we must join dir+file to compose the full path
  1293. if rc_dir:
  1294. # Compose path and return it if the file exists
  1295. rc_path = os.path.join(rc_dir, rc_file)
  1296. # On windows, prefix with the drive (%homedrive%: 2k/XP/NT)
  1297. if sys.platform[:3] == 'win':
  1298. rc_drive = os.environ.get('HOMEDRIVE')
  1299. rc_path = os.path.join(rc_drive,rc_path)
  1300. return rc_path
  1301. # Sorry, not found
  1302. return ''
  1303. ##############################################################################
  1304. class CommandLine:
  1305. """
  1306. Command Line class - Masters command line
  1307. This class checks and extract data from the provided command line.
  1308. The --long options and flags are taken from the global OPTIONS,
  1309. FLAGS and ACTIONS dictionaries. The short options are registered
  1310. here, and also their equivalence to the long ones.
  1311. METHODS:
  1312. _compose_short_opts() -> str
  1313. _compose_long_opts() -> list
  1314. Compose the valid short and long options list, on the
  1315. 'getopt' format.
  1316. parse() -> (opts, args)
  1317. Call getopt to check and parse the command line.
  1318. It expects to receive the command line as a list, and
  1319. without the program name (sys.argv[1:]).
  1320. get_raw_config() -> [RAW config]
  1321. Scans command line and convert the data to the RAW config
  1322. format. See ConfigMaster class to the RAW format description.
  1323. Optional 'ignore' and 'filter' arguments are used to filter
  1324. in or out specified keys.
  1325. compose_cmdline(dict) -> [Command line]
  1326. Compose a command line list from an already parsed config
  1327. dictionary, generated from RAW by ConfigMaster(). Use
  1328. this to compose an optimal command line for a group of
  1329. options.
  1330. The get_raw_config() calls parse(), so the tipical use of this
  1331. class is:
  1332. raw = CommandLine().get_raw_config(sys.argv[1:])
  1333. """
  1334. def __init__(self):
  1335. self.all_options = OPTIONS.keys()
  1336. self.all_flags = FLAGS.keys()
  1337. self.all_actions = ACTIONS.keys()
  1338. # short:long options equivalence
  1339. self.short_long = {
  1340. 'h':'help' , 'V':'version',
  1341. 'n':'enum-title', 'i':'infile' ,
  1342. 'H':'no-headers', 'o':'outfile',
  1343. 'v':'verbose' , 't':'target' ,
  1344. 'q':'quiet' , 'C':'config-file'
  1345. }
  1346. # Compose valid short and long options data for getopt
  1347. self.short_opts = self._compose_short_opts()
  1348. self.long_opts = self._compose_long_opts()
  1349. def _compose_short_opts(self):
  1350. "Returns a string like 'hVt:o' with all short options/flags"
  1351. ret = []
  1352. for opt in self.short_long.keys():
  1353. long = self.short_long[opt]
  1354. if long in self.all_options: # is flag or option?
  1355. opt = opt+':' # option: have param
  1356. ret.append(opt)
  1357. #Debug('Valid SHORT options: %s'%ret)
  1358. return string.join(ret, '')
  1359. def _compose_long_opts(self):
  1360. "Returns a list with all the valid long options/flags"
  1361. ret = map(lambda x:x+'=', self.all_options) # add =
  1362. ret.extend(self.all_flags) # flag ON
  1363. ret.extend(self.all_actions) # acts
  1364. ret.extend(map(lambda x:'no-'+x, self.all_flags)) # add no-*
  1365. ret.extend(['no-style','no-encoding']) # turn OFF
  1366. ret.extend(['no-outfile','no-infile']) # turn OFF
  1367. ret.extend(['no-dump-config', 'no-dump-source']) # turn OFF
  1368. #Debug('Valid LONG options: %s'%ret)
  1369. return ret
  1370. def _tokenize(self, cmd_string=''):
  1371. "Convert a command line string to a list"
  1372. #TODO protect quotes contents
  1373. return string.split(cmd_string)
  1374. def parse(self, cmdline=[]):
  1375. "Check/Parse a command line list TIP: no program name!"
  1376. # Get the valid options
  1377. short, long = self.short_opts, self.long_opts
  1378. # Parse it!
  1379. try:
  1380. opts, args = getopt.getopt(cmdline, short, long)
  1381. except getopt.error, errmsg:
  1382. Error(_("%s (try --help)")%errmsg)
  1383. return (opts, args)
  1384. def get_raw_config(self, cmdline=[], ignore=[], filter=[], relative=0):
  1385. "Returns the options/arguments found as RAW config"
  1386. if not cmdline: return []
  1387. ret = []
  1388. # We need lists, not strings
  1389. if type(cmdline) == type(''): cmdline = self._tokenize(cmdline)
  1390. opts, args = self.parse(cmdline[:])
  1391. # Parse all options
  1392. for name,value in opts:
  1393. # Remove leading - and --
  1394. name = re.sub('^--?', '', name)
  1395. # Alias to old misspelled 'suGGar'
  1396. if name == 'css-suggar': name = 'css-sugar'
  1397. elif name == 'no-css-suggar': name = 'no-css-sugar'
  1398. # Translate short opt to long
  1399. if len(name) == 1: name = self.short_long.get(name)
  1400. # Outfile exception: path relative to PWD
  1401. if name == 'outfile' and relative \
  1402. and value not in [STDOUT, MODULEOUT]:
  1403. value = os.path.abspath(value)
  1404. # config-file inclusion, path relative to PWD
  1405. if name == 'config-file':
  1406. configs = ConfigLines().include_config_file(
  1407. value)
  1408. # Remove the 'target' item of all configs
  1409. configs = map(lambda c: [c[1],c[2]], configs)
  1410. ret.extend(configs)
  1411. continue
  1412. # Save it
  1413. ret.append([name, value])
  1414. # Get infile, if any
  1415. while args:
  1416. infile = args.pop(0)
  1417. ret.append(['infile', infile])
  1418. # Apply 'ignore' and 'filter' rules (filter is stronger)
  1419. temp = ret[:] ; ret = []
  1420. for name,value in temp:
  1421. if (not filter and not ignore) or \
  1422. (filter and name in filter) or \
  1423. (ignore and name not in ignore):
  1424. ret.append( ['all', name, value] )
  1425. # Add the original command line string as 'realcmdline'
  1426. ret.append( ['all', 'realcmdline', cmdline] )
  1427. return ret
  1428. def compose_cmdline(self, conf={}, no_check=0):
  1429. "compose a full (and diet) command line from CONF dict"
  1430. if not conf: return []
  1431. args = []
  1432. dft_options = OPTIONS.copy()
  1433. cfg = conf.copy()
  1434. valid_opts = self.all_options + self.all_flags
  1435. use_short = {'no-headers':'H', 'enum-title':'n'}
  1436. # Remove useless options
  1437. if not no_check and cfg.get('toc-only'):
  1438. if cfg.has_key('no-headers'):
  1439. del cfg['no-headers']
  1440. if cfg.has_key('outfile'):
  1441. del cfg['outfile'] # defaults to STDOUT
  1442. if cfg.get('target') == 'txt':
  1443. del cfg['target'] # already default
  1444. args.append('--toc-only') # must be the first
  1445. del cfg['toc-only']
  1446. # Add target type
  1447. if cfg.has_key('target'):
  1448. args.append('-t '+cfg['target'])
  1449. del cfg['target']
  1450. # Add other options
  1451. for key in cfg.keys():
  1452. if key not in valid_opts: continue # may be a %!setting
  1453. if key == 'outfile' or key == 'infile': continue # later
  1454. val = cfg[key]
  1455. if not val: continue
  1456. # Default values are useless on cmdline
  1457. if val == dft_options.get(key): continue
  1458. # -short format
  1459. if key in use_short.keys():
  1460. args.append('-'+use_short[key])
  1461. continue
  1462. # --long format
  1463. if key in self.all_flags: # add --option
  1464. args.append('--'+key)
  1465. else: # add --option=value
  1466. args.append('--%s=%s'%(key,val))
  1467. # The outfile using -o
  1468. if cfg.has_key('outfile') and \
  1469. cfg['outfile'] != dft_options.get('outfile'):
  1470. args.append('-o '+cfg['outfile'])
  1471. # Place input file(s) always at the end
  1472. if cfg.has_key('infile'):
  1473. args.append(string.join(cfg['infile'],' '))
  1474. # Return as a nice list
  1475. Debug("Diet command line: %s"%string.join(args,' '), 1)
  1476. return args
  1477. ##############################################################################
  1478. class SourceDocument:
  1479. """
  1480. SourceDocument class - scan document structure, extract data
  1481. It knows about full files. It reads a file and identify all
  1482. the areas begining (Head,Conf,Body). With this info it can
  1483. extract each area contents.
  1484. Note: the original line break is removed.
  1485. DATA:
  1486. self.arearef - Save Head, Conf, Body init line number
  1487. self.areas - Store the area names which are not empty
  1488. self.buffer - The full file contents (with NO \\r, \\n)
  1489. METHODS:
  1490. get() - Access the contents of an Area. Example:
  1491. config = SourceDocument(file).get('conf')
  1492. split() - Get all the document Areas at once. Example:
  1493. head, conf, body = SourceDocument(file).split()
  1494. RULES:
  1495. * The document parts are sequential: Head, Conf and Body.
  1496. * One ends when the next begins.
  1497. * The Conf Area is optional, so a document can have just
  1498. Head and Body Areas.
  1499. These are the Areas limits:
  1500. - Head Area: the first three lines
  1501. - Body Area: from the first valid text line to the end
  1502. - Conf Area: the comments between Head and Body Areas
  1503. Exception: If the first line is blank, this means no
  1504. header info, so the Head Area is just the first line.
  1505. """
  1506. def __init__(self, filename='', contents=[]):
  1507. self.areas = ['head','conf','body']
  1508. self.arearef = []
  1509. self.areas_fancy = ''
  1510. self.filename = filename
  1511. self.buffer = []
  1512. if filename:
  1513. self.scan_file(filename)
  1514. elif contents:
  1515. self.scan(contents)
  1516. def split(self):
  1517. "Returns all document parts, splitted into lists."
  1518. return self.get('head'), self.get('conf'), self.get('body')
  1519. def get(self, areaname):
  1520. "Returns head|conf|body contents from self.buffer"
  1521. # Sanity
  1522. if areaname not in self.areas: return []
  1523. if not self.buffer : return []
  1524. # Go get it
  1525. bufini = 1
  1526. bufend = len(self.buffer)
  1527. if areaname == 'head':
  1528. ini = bufini
  1529. end = self.arearef[1] or self.arearef[2] or bufend
  1530. elif areaname == 'conf':
  1531. ini = self.arearef[1]
  1532. end = self.arearef[2] or bufend
  1533. elif areaname == 'body':
  1534. ini = self.arearef[2]
  1535. end = bufend
  1536. else:
  1537. Error("Unknown Area name '%s'"%areaname)
  1538. lines = self.buffer[ini:end]
  1539. # Make sure head will always have 3 lines
  1540. while areaname == 'head' and len(lines) < 3:
  1541. lines.append('')
  1542. return lines
  1543. def scan_file(self, filename):
  1544. Debug("source file: %s"%filename)
  1545. Message(_("Loading source document"),1)
  1546. buf = Readfile(filename, remove_linebreaks=1)
  1547. self.scan(buf)
  1548. def scan(self, lines):
  1549. "Run through source file and identify head/conf/body areas"
  1550. buf = lines
  1551. if len(buf) == 0:
  1552. Error(_('The input file is empty: %s')%self.filename)
  1553. cfg_parser = ConfigLines().parse_line
  1554. buf.insert(0, '') # text start at pos 1
  1555. ref = [1,4,0]
  1556. if not string.strip(buf[1]): # no header
  1557. ref[0] = 0 ; ref[1] = 2
  1558. rgx = getRegexes()
  1559. on_comment_block = 0
  1560. for i in xrange(ref[1],len(buf)): # find body init:
  1561. # Handle comment blocks inside config area
  1562. if not on_comment_block \
  1563. and rgx['blockCommentOpen'].search(buf[i]):
  1564. on_comment_block = 1
  1565. continue
  1566. if on_comment_block \
  1567. and rgx['blockCommentOpen'].search(buf[i]):
  1568. on_comment_block = 0
  1569. continue
  1570. if on_comment_block: continue
  1571. if string.strip(buf[i]) and ( # ... not blank and
  1572. buf[i][0] != '%' or # ... not comment or
  1573. rgx['macros'].match(buf[i]) or # ... %%macro
  1574. rgx['toc'].match(buf[i]) or # ... %%toc
  1575. cfg_parser(buf[i],'include')[1]): # ... %!include
  1576. ref[2] = i ; break
  1577. if ref[1] == ref[2]: ref[1] = 0 # no conf area
  1578. for i in 0,1,2: # del !existent
  1579. if ref[i] >= len(buf): ref[i] = 0 # title-only
  1580. if not ref[i]: self.areas[i] = ''
  1581. Debug('Head,Conf,Body start line: %s'%ref)
  1582. self.arearef = ref # save results
  1583. self.buffer = buf
  1584. # Fancyness sample: head conf body (1 4 8)
  1585. self.areas_fancy = "%s (%s)"%(
  1586. string.join(self.areas),
  1587. string.join(map(str, map(lambda x:x or '', ref))))
  1588. Message(_("Areas found: %s")%self.areas_fancy, 2)
  1589. def get_raw_config(self):
  1590. "Handy method to get the CONF area RAW config (if any)"
  1591. if not self.areas.count('conf'): return []
  1592. Message(_("Scanning source document CONF area"),1)
  1593. raw = ConfigLines(
  1594. file=self.filename, lines=self.get('conf'),
  1595. first_line=self.arearef[1]).get_raw_config()
  1596. Debug("document raw config: %s"%raw, 1)
  1597. return raw
  1598. ##############################################################################
  1599. class ConfigMaster:
  1600. """
  1601. ConfigMaster class - the configuration wizard
  1602. This class is the configuration master. It knows how to handle
  1603. the RAW and PARSED config format. It also performs the sanity
  1604. checking for a given configuration.
  1605. DATA:
  1606. self.raw - Stores the config on the RAW format
  1607. self.parsed - Stores the config on the PARSED format
  1608. self.defaults - Stores the default values for all keys
  1609. self.off - Stores the OFF values for all keys
  1610. self.multi - List of keys which can have multiple values
  1611. self.numeric - List of keys which value must be a number
  1612. self.incremental - List of keys which are incremental
  1613. RAW FORMAT:
  1614. The RAW format is a list of lists, being each mother list item
  1615. a full configuration entry. Any entry is a 3 item list, on
  1616. the following format: [ TARGET, KEY, VALUE ]
  1617. Being a list, the order is preserved, so it's easy to use
  1618. different kinds of configs, as CONF area and command line,
  1619. respecting the precedence.
  1620. The special target 'all' is used when no specific target was
  1621. defined on the original config.
  1622. PARSED FORMAT:
  1623. The PARSED format is a dictionary, with all the 'key : value'
  1624. found by reading the RAW config. The self.target contents
  1625. matters, so this dictionary only contains the target's
  1626. config. The configs of other targets are ignored.
  1627. The CommandLine and ConfigLines classes have the get_raw_config()
  1628. method which convert the configuration found to the RAW format.
  1629. Just feed it to parse() and get a brand-new ready-to-use config
  1630. dictionary. Example:
  1631. >>> raw = CommandLine().get_raw_config(['-n', '-H'])
  1632. >>> print raw
  1633. [['all', 'enum-title', ''], ['all', 'no-headers', '']]
  1634. >>> parsed = ConfigMaster(raw).parse()
  1635. >>> print parsed
  1636. {'enum-title': 1, 'headers': 0}
  1637. """
  1638. def __init__(self, raw=[], target=''):
  1639. self.raw = raw
  1640. self.target = target
  1641. self.parsed = {}
  1642. self.dft_options = OPTIONS.copy()
  1643. self.dft_flags = FLAGS.copy()
  1644. self.dft_actions = ACTIONS.copy()
  1645. self.dft_settings = SETTINGS.copy()
  1646. self.defaults = self._get_defaults()
  1647. self.off = self._get_off()
  1648. self.incremental = ['verbose']
  1649. self.numeric = ['toc-level','split']
  1650. self.multi = ['infile', 'preproc', 'postproc',
  1651. 'options', 'style']
  1652. def _get_defaults(self):
  1653. "Get the default values for all config/options/flags"
  1654. empty = {}
  1655. for kw in CONFIG_KEYWORDS: empty[kw] = ''
  1656. empty.update(self.dft_options)
  1657. empty.update(self.dft_flags)
  1658. empty.update(self.dft_actions)
  1659. empty.update(self.dft_settings)
  1660. empty['realcmdline'] = '' # internal use only
  1661. empty['sourcefile'] = '' # internal use only
  1662. return empty
  1663. def _get_off(self):
  1664. "Turns OFF all the config/options/flags"
  1665. off = {}
  1666. for key in self.defaults.keys():
  1667. kind = type(self.defaults[key])
  1668. if kind == type(9):
  1669. off[key] = 0
  1670. elif kind == type(''):
  1671. off[key] = ''
  1672. elif kind == type([]):
  1673. off[key] = []
  1674. else:
  1675. Error('ConfigMaster: %s: Unknown type'+key)
  1676. return off
  1677. def _check_target(self):
  1678. "Checks if the target is already defined. If not, do it"
  1679. if not self.target:
  1680. self.target = self.find_value('target')
  1681. def get_target_raw(self):
  1682. "Returns the raw config for self.target or 'all'"
  1683. ret = []
  1684. self._check_target()
  1685. for entry in self.raw:
  1686. if entry[0] == self.target or entry[0] == 'all':
  1687. ret.append(entry)
  1688. return ret
  1689. def add(self, key, val):
  1690. "Adds the key:value pair to the config dictionary (if needed)"
  1691. # %!options
  1692. if key == 'options':
  1693. ignoreme = self.dft_actions.keys() + ['target']
  1694. ignoreme.remove('dump-config')
  1695. ignoreme.remove('dump-source')
  1696. raw_opts = CommandLine().get_raw_config(
  1697. val, ignore=ignoreme)
  1698. for target, key, val in raw_opts:
  1699. self.add(key, val)
  1700. return
  1701. # The no- prefix turns OFF this key
  1702. if key[:3] == 'no-':
  1703. key = key[3:] # remove prefix
  1704. val = self.off.get(key) # turn key OFF
  1705. # Is this key valid?
  1706. if key not in self.defaults.keys():
  1707. Debug('Bogus Config %s:%s'%(key,val),1)
  1708. return
  1709. # Is this value the default one?
  1710. if val == self.defaults.get(key):
  1711. # If default value, remove previous key:val
  1712. if self.parsed.has_key(key):
  1713. del self.parsed[key]
  1714. # Nothing more to do
  1715. return
  1716. # Flags ON comes empty. we'll add the 1 value now
  1717. if val == '' and (
  1718. key in self.dft_flags.keys() or
  1719. key in self.dft_actions.keys()):
  1720. val = 1
  1721. # Multi value or single?
  1722. if key in self.multi:
  1723. # First one? start new list
  1724. if not self.parsed.has_key(key):
  1725. self.parsed[key] = []
  1726. self.parsed[key].append(val)
  1727. # Incremental value? so let's add it
  1728. elif key in self.incremental:
  1729. self.parsed[key] = (self.parsed.get(key) or 0) + val
  1730. else:
  1731. self.parsed[key] = val
  1732. fancykey = dotted_spaces("%12s"%key)
  1733. Message(_("Added config %s : %s")%(fancykey,val),3)
  1734. def get_outfile_name(self, config={}):
  1735. "Dirname is the same for {in,out}file"
  1736. infile, outfile = config['sourcefile'], config['outfile']
  1737. if outfile and outfile not in (STDOUT, MODULEOUT) \
  1738. and not os.path.isabs(outfile):
  1739. outfile = os.path.join(os.path.dirname(infile), outfile)
  1740. if infile == STDIN and not outfile: outfile = STDOUT
  1741. if infile == MODULEIN and not outfile: outfile = MODULEOUT
  1742. if not outfile and (infile and config.get('target')):
  1743. basename = re.sub('\.(txt|t2t)$','',infile)
  1744. outfile = "%s.%s"%(basename, config['target'])
  1745. Debug(" infile: '%s'"%infile , 1)
  1746. Debug("outfile: '%s'"%outfile, 1)
  1747. return outfile
  1748. def sanity(self, config, gui=0):
  1749. "Basic config sanity checking"
  1750. if not config: return {}
  1751. target = config.get('target')
  1752. # Some actions don't require target specification
  1753. if not target:
  1754. for action in NO_TARGET:
  1755. if config.get(action):
  1756. target = 'txt'
  1757. break
  1758. # On GUI, some checking are skipped
  1759. if not gui:
  1760. # We *need* a target
  1761. if not target:
  1762. Error(_('No target specified (try --help)')+\
  1763. '\n\n'+\
  1764. _('Maybe trying to convert an old v1.x file?'))
  1765. # And of course, an infile also
  1766. if not config.get('infile'):
  1767. Error(_('Missing input file (try --help)'))
  1768. # Is the target valid?
  1769. if not TARGETS.count(target):
  1770. Error(_("Invalid target '%s' (try --help)")%\
  1771. target)
  1772. # Ensure all keys are present
  1773. empty = self.defaults.copy() ; empty.update(config)
  1774. config = empty.copy()
  1775. # Check integers options
  1776. for key in config.keys():
  1777. if key in self.numeric:
  1778. try: config[key] = int(config[key])
  1779. except: Error(_('--%s value must be a number'
  1780. )%key)
  1781. # Check split level value
  1782. if config['split'] not in (0,1,2):
  1783. Error(_('Option --split must be 0, 1 or 2'))
  1784. # --toc-only is stronger than others
  1785. if config['toc-only']:
  1786. config['headers'] = 0
  1787. config['toc'] = 0
  1788. config['split'] = 0
  1789. config['gui'] = 0
  1790. config['outfile'] = config['outfile'] or STDOUT
  1791. # Splitting is disable for now (future: HTML only, no STDOUT)
  1792. config['split'] = 0
  1793. # Restore target
  1794. config['target'] = target
  1795. # Set output file name
  1796. config['outfile'] = self.get_outfile_name(config)
  1797. # Checking suicide
  1798. if config['sourcefile'] == config['outfile'] and \
  1799. config['outfile'] not in [STDOUT,MODULEOUT] and not gui:
  1800. Error(_("Input and Output files are the same: %s")%(
  1801. config['outfile']))
  1802. return config
  1803. def parse(self):
  1804. "Returns the parsed config for the current target"
  1805. raw = self.get_target_raw()
  1806. for target, key, value in raw:
  1807. self.add(key, value)
  1808. Message(_("Added the following keys: %s")%string.join(
  1809. self.parsed.keys(),', '),2)
  1810. return self.parsed.copy()
  1811. def find_value(self, key='', target=''):
  1812. "Scans ALL raw config to find the desired key"
  1813. ret = []
  1814. # Scan and save all values found
  1815. for targ, k, val in self.raw:
  1816. if k == key and (targ == target or targ == 'all'):
  1817. ret.append(val)
  1818. if not ret: return ''
  1819. # If not multi value, return only the last found
  1820. if key in self.multi: return ret
  1821. else : return ret[-1]
  1822. ########################################################################
  1823. class ConfigLines:
  1824. """
  1825. ConfigLines class - the config file data extractor
  1826. This class reads and parse the config lines on the %!key:val
  1827. format, converting it to RAW config. It deals with user
  1828. config file (RC file), source document CONF area and
  1829. %!includeconf directives.
  1830. Call it passing a file name or feed the desired config lines.
  1831. Then just call the get_raw_config() method and wait to
  1832. receive the full config data on the RAW format. This method
  1833. also follows the possible %!includeconf directives found on
  1834. the config lines. Example:
  1835. raw = ConfigLines(file=".txt2tagsrc").get_raw_config()
  1836. The parse_line() method is also useful to be used alone,
  1837. to identify and tokenize a single config line. For example,
  1838. to get the %!include command components, on the source
  1839. document BODY:
  1840. target, key, value = ConfigLines().parse_line(body_line)
  1841. """
  1842. def __init__(self, file='', lines=[], first_line=1):
  1843. self.file = file or 'NOFILE'
  1844. self.lines = lines
  1845. self.first_line = first_line
  1846. def load_lines(self):
  1847. "Make sure we've loaded the file contents into buffer"
  1848. if not self.lines and not self.file:
  1849. Error("ConfigLines: No file or lines provided")
  1850. if not self.lines:
  1851. self.lines = self.read_config_file(self.file)
  1852. def read_config_file(self, filename=''):
  1853. "Read a Config File contents, aborting on invalid line"
  1854. if not filename: return []
  1855. errormsg = _("Invalid CONFIG line on %s")+"\n%03d:%s"
  1856. lines = Readfile(filename, remove_linebreaks=1)
  1857. # Sanity: try to find invalid config lines
  1858. for i in xrange(len(lines)):
  1859. line = string.rstrip(lines[i])
  1860. if not line: continue # empty
  1861. if line[0] != '%': Error(errormsg%(filename,i+1,line))
  1862. return lines
  1863. def include_config_file(self, file=''):
  1864. "Perform the %!includeconf action, returning RAW config"
  1865. if not file: return []
  1866. # Current dir relative to the current file (self.file)
  1867. current_dir = os.path.dirname(self.file)
  1868. file = os.path.join(current_dir, file)
  1869. # Read and parse included config file contents
  1870. lines = self.read_config_file(file)
  1871. return ConfigLines(file=file, lines=lines).get_raw_config()
  1872. def get_raw_config(self):
  1873. "Scan buffer and extract all config as RAW (including includes)"
  1874. ret = []
  1875. self.load_lines()
  1876. first = self.first_line
  1877. for i in xrange(len(self.lines)):
  1878. line = self.lines[i]
  1879. Message(_("Processing line %03d: %s")%(first+i,line),2)
  1880. target, key, val = self.parse_line(line)
  1881. if not key: continue # no config on this line
  1882. if key == 'includeconf':
  1883. err = _('A file cannot include itself (loop!)')
  1884. if val == self.file:
  1885. Error("%s: %%!includeconf: %s"%(
  1886. err, self.file))
  1887. more_raw = self.include_config_file(val)
  1888. ret.extend(more_raw)
  1889. Message(_("Finished Config file inclusion: %s"
  1890. )%(val),2)
  1891. else:
  1892. ret.append([target, key, val])
  1893. Message(_("Added %s")%key,3)
  1894. return ret
  1895. def parse_line(self, line='', keyname='', target=''):
  1896. "Detects %!key:val config lines and extract data from it"
  1897. empty = ['', '', '']
  1898. if not line: return empty
  1899. no_target = ['target', 'includeconf']
  1900. re_name = keyname or '[a-z]+'
  1901. re_target = target or '[a-z]*'
  1902. # XXX TODO <value>\S.+? requires TWO chars, breaks %!include:a
  1903. cfgregex = re.compile("""
  1904. ^%%!\s* # leading id with opt spaces
  1905. (?P<name>%s)\s* # config name
  1906. (\((?P<target>%s)\))? # optional target spec inside ()
  1907. \s*:\s* # key:value delimiter with opt spaces
  1908. (?P<value>\S.+?) # config value
  1909. \s*$ # rstrip() spaces and hit EOL
  1910. """%(re_name,re_target), re.I+re.VERBOSE)
  1911. prepostregex = re.compile("""
  1912. # ---[ PATTERN ]---
  1913. ^( "([^"]*)" # "double quoted" or
  1914. | '([^']*)' # 'single quoted' or
  1915. | ([^\s]+) # single_word
  1916. )
  1917. \s+ # separated by spaces
  1918. # ---[ REPLACE ]---
  1919. ( "([^"]*)" # "double quoted" or
  1920. | '([^']*)' # 'single quoted' or
  1921. | (.*) # anything
  1922. )
  1923. \s*$
  1924. """, re.VERBOSE)
  1925. guicolors = re.compile("^([^\s]+\s+){3}[^\s]+") # 4 tokens
  1926. match = cfgregex.match(line)
  1927. if not match: return empty
  1928. name = string.lower(match.group('name') or '')
  1929. target = string.lower(match.group('target') or 'all')
  1930. value = match.group('value')
  1931. # NO target keywords: force all targets
  1932. if name in no_target: target = 'all'
  1933. # Special config for GUI colors
  1934. if name == 'guicolors':
  1935. valmatch = guicolors.search(value)
  1936. if not valmatch: return empty
  1937. value = re.split('\s+', value)
  1938. # Special config with two quoted values (%!preproc: "foo" 'bar')
  1939. if name == 'preproc' or name == 'postproc':
  1940. valmatch = prepostregex.search(value)
  1941. if not valmatch: return empty
  1942. getval = valmatch.group
  1943. patt = getval(2) or getval(3) or getval(4) or ''
  1944. repl = getval(6) or getval(7) or getval(8) or ''
  1945. value = (patt, repl)
  1946. return [target, name, value]
  1947. ##############################################################################
  1948. class MaskMaster:
  1949. "(Un)Protect important structures from escaping and formatting"
  1950. def __init__(self):
  1951. self.linkmask = 'vvvLINKvvv'
  1952. self.monomask = 'vvvMONOvvv'
  1953. self.macromask = 'vvvMACROvvv'
  1954. self.rawmask = 'vvvRAWvvv'
  1955. self.tocmask = 'vvvTOCvvv'
  1956. self.macroman = MacroMaster()
  1957. self.reset()
  1958. def reset(self):
  1959. self.linkbank = []
  1960. self.monobank = []
  1961. self.macrobank = []
  1962. self.rawbank = []
  1963. def mask(self, line=''):
  1964. global AUTOTOC
  1965. # Protect raw text
  1966. while regex['raw'].search(line):
  1967. txt = regex['raw'].search(line).group(1)
  1968. txt = doEscape(TARGET,txt)
  1969. self.rawbank.append(txt)
  1970. line = regex['raw'].sub(self.rawmask,line,1)
  1971. # Protect pre-formatted font text
  1972. while regex['fontMono'].search(line):
  1973. txt = regex['fontMono'].search(line).group(1)
  1974. txt = doEscape(TARGET,txt)
  1975. self.monobank.append(txt)
  1976. line = regex['fontMono'].sub(self.monomask,line,1)
  1977. # Protect macros
  1978. while regex['macros'].search(line):
  1979. txt = regex['macros'].search(line).group()
  1980. self.macrobank.append(txt)
  1981. line = regex['macros'].sub(self.macromask,line,1)
  1982. # Protect TOC location
  1983. while regex['toc'].search(line):
  1984. line = regex['toc'].sub(self.tocmask,line)
  1985. AUTOTOC = 0
  1986. # Protect URLs and emails
  1987. while regex['linkmark'].search(line) or \
  1988. regex['link' ].search(line):
  1989. # Try to match plain or named links
  1990. match_link = regex['link'].search(line)
  1991. match_named = regex['linkmark'].search(line)
  1992. # Define the current match
  1993. if match_link and match_named:
  1994. # Both types found, which is the first?
  1995. m = match_link
  1996. if match_named.start() < match_link.start():
  1997. m = match_named
  1998. else:
  1999. # Just one type found, we're fine
  2000. m = match_link or match_named
  2001. # Extract link data and apply mask
  2002. if m == match_link: # plain link
  2003. link = m.group()
  2004. label = ''
  2005. link_re = regex['link']
  2006. else: # named link
  2007. link = m.group('link')
  2008. label = string.rstrip(m.group('label'))
  2009. link_re = regex['linkmark']
  2010. line = link_re.sub(self.linkmask,line,1)
  2011. # Save link data to the link bank
  2012. self.linkbank.append((label, link))
  2013. return line
  2014. def undo(self, line):
  2015. # url & email
  2016. for label,url in self.linkbank:
  2017. link = get_tagged_link(label, url)
  2018. line = string.replace(line, self.linkmask, link, 1)
  2019. # Expand macros
  2020. for macro in self.macrobank:
  2021. macro = self.macroman.expand(macro)
  2022. line = string.replace(line, self.macromask, macro, 1)
  2023. # Expand verb
  2024. for mono in self.monobank:
  2025. open,close = TAGS['fontMonoOpen'],TAGS['fontMonoClose']
  2026. tagged = open+mono+close
  2027. line = string.replace(line, self.monomask, tagged, 1)
  2028. # Expand raw
  2029. for raw in self.rawbank:
  2030. line = string.replace(line, self.rawmask, raw, 1)
  2031. return line
  2032. ##############################################################################
  2033. class TitleMaster:
  2034. "Title things"
  2035. def __init__(self):
  2036. self.count = ['',0,0,0,0,0]
  2037. self.toc = []
  2038. self.level = 0
  2039. self.kind = ''
  2040. self.txt = ''
  2041. self.label = ''
  2042. self.tag = ''
  2043. self.tag_hold = []
  2044. self.last_level = 0
  2045. self.count_id = ''
  2046. self.user_labels = {}
  2047. self.anchor_count = 0
  2048. self.anchor_prefix = 'toc'
  2049. def _open_close_blocks(self):
  2050. "Open new title blocks, closing the previous (if any)"
  2051. if not rules['titleblocks']: return
  2052. tag = ''
  2053. last = self.last_level
  2054. curr = self.level
  2055. # Same level, just close the previous
  2056. if curr == last:
  2057. tag = TAGS.get('title%dClose'%last)
  2058. if tag: self.tag_hold.append(tag)
  2059. # Section -> subsection, more depth
  2060. while curr > last:
  2061. last = last + 1
  2062. # Open the new block of subsections
  2063. tag = TAGS.get('blockTitle%dOpen'%last)
  2064. if tag: self.tag_hold.append(tag)
  2065. # Jump from title1 to title3 or more
  2066. # Fill the gap with an empty section
  2067. if curr - last > 0:
  2068. tag = TAGS.get('title%dOpen'%last)
  2069. tag = regex['x'].sub('', tag) # del \a
  2070. if tag: self.tag_hold.append(tag)
  2071. # Section <- subsection, less depth
  2072. while curr < last:
  2073. # Close the current opened subsection
  2074. tag = TAGS.get('title%dClose'%last)
  2075. if tag: self.tag_hold.append(tag)
  2076. # Close the current opened block of subsections
  2077. tag = TAGS.get('blockTitle%dClose'%last)
  2078. if tag: self.tag_hold.append(tag)
  2079. last = last - 1
  2080. # Close the previous section of the same level
  2081. # The subsections were under it
  2082. if curr == last:
  2083. tag = TAGS.get('title%dClose'%last)
  2084. if tag: self.tag_hold.append(tag)
  2085. def add(self, line):
  2086. "Parses a new title line."
  2087. if not line: return
  2088. self._set_prop(line)
  2089. self._open_close_blocks()
  2090. self._set_count_id()
  2091. self._set_label()
  2092. self._save_toc_info()
  2093. def close_all(self):
  2094. "Closes all opened title blocks"
  2095. ret = []
  2096. ret.extend(self.tag_hold)
  2097. while self.level:
  2098. tag = TAGS.get('title%dClose'%self.level)
  2099. if tag: ret.append(tag)
  2100. tag = TAGS.get('blockTitle%dClose'%self.level)
  2101. if tag: ret.append(tag)
  2102. self.level = self.level - 1
  2103. return ret
  2104. def _save_toc_info(self):
  2105. "Save TOC info, used by self.dump_marked_toc()"
  2106. self.toc.append((self.level, self.count_id,
  2107. self.txt , self.label ))
  2108. def _set_prop(self, line=''):
  2109. "Extract info from original line and set data holders."
  2110. # Detect title type (numbered or not)
  2111. id = string.lstrip(line)[0]
  2112. if id == '=': kind = 'title'
  2113. elif id == '+': kind = 'numtitle'
  2114. else: Error("Unknown Title ID '%s'"%id)
  2115. # Extract line info
  2116. match = regex[kind].search(line)
  2117. level = len(match.group('id'))
  2118. txt = string.strip(match.group('txt'))
  2119. label = match.group('label')
  2120. # Parse info & save
  2121. if CONF['enum-title']: kind = 'numtitle' # force
  2122. if rules['titleblocks']:
  2123. self.tag = TAGS.get('%s%dOpen'%(kind,level)) or \
  2124. TAGS.get('title%dOpen'%level)
  2125. else:
  2126. self.tag = TAGS.get(kind+`level`) or \
  2127. TAGS.get('title'+`level`)
  2128. self.last_level = self.level
  2129. self.kind = kind
  2130. self.level = level
  2131. self.txt = txt
  2132. self.label = label
  2133. def _set_count_id(self):
  2134. "Compose and save the title count identifier (if needed)."
  2135. count_id = ''
  2136. if self.kind == 'numtitle' and not rules['autonumbertitle']:
  2137. # Manually increase title count
  2138. self.count[self.level] = self.count[self.level] +1
  2139. # Reset sublevels count (if any)
  2140. max_levels = len(self.count)
  2141. if self.level < max_levels-1:
  2142. for i in xrange(self.level+1, max_levels):
  2143. self.count[i] = 0
  2144. # Compose count id from hierarchy
  2145. for i in xrange(self.level):
  2146. count_id= "%s%d."%(count_id, self.count[i+1])
  2147. self.count_id = count_id
  2148. def _set_label(self):
  2149. "Compose and save title label, used by anchors."
  2150. # Remove invalid chars from label set by user
  2151. self.label = re.sub('[^A-Za-z0-9_-]', '', self.label or '')
  2152. # Generate name as 15 first :alnum: chars
  2153. #TODO how to translate safely accented chars to plain?
  2154. #self.label = re.sub('[^A-Za-z0-9]', '', self.txt)[:15]
  2155. # 'tocN' label - sequential count, ignoring 'toc-level'
  2156. #self.label = self.anchor_prefix + str(len(self.toc)+1)
  2157. def _get_tagged_anchor(self):
  2158. "Return anchor if user defined a label, or TOC is on."
  2159. ret = ''
  2160. label = self.label
  2161. if CONF['toc'] and self.level <= CONF['toc-level']:
  2162. # This count is needed bcos self.toc stores all
  2163. # titles, regardless of the 'toc-level' setting,
  2164. # so we can't use self.toc length to number anchors
  2165. self.anchor_count = self.anchor_count + 1
  2166. # Autonumber label (if needed)
  2167. label = label or '%s%s'%(
  2168. self.anchor_prefix, self.anchor_count)
  2169. if label and TAGS['anchor']:
  2170. ret = regex['x'].sub(label,TAGS['anchor'])
  2171. return ret
  2172. def _get_full_title_text(self):
  2173. "Returns the full title contents, already escaped."
  2174. ret = self.txt
  2175. # Insert count_id (if any) before text
  2176. if self.count_id:
  2177. ret = '%s %s'%(self.count_id, ret)
  2178. # Escape specials
  2179. ret = doEscape(TARGET, ret)
  2180. # Same targets needs final escapes on title lines
  2181. # It's here because there is a 'continue' after title
  2182. if rules['finalescapetitle']:
  2183. ret = doFinalEscape(TARGET, ret)
  2184. return ret
  2185. def get(self):
  2186. "Returns the tagged title as a list."
  2187. ret = []
  2188. # Maybe some anchoring before?
  2189. anchor = self._get_tagged_anchor()
  2190. self.tag = regex['_anchor'].sub(anchor, self.tag)
  2191. ### Compose & escape title text (TOC uses unescaped)
  2192. full_title = self._get_full_title_text()
  2193. # Close previous section area
  2194. ret.extend(self.tag_hold)
  2195. self.tag_hold = []
  2196. # Finish title, adding "underline" on TXT target
  2197. tagged = regex['x'].sub(full_title, self.tag)
  2198. if TARGET == 'txt':
  2199. ret.append('') # blank line before
  2200. ret.append(tagged)
  2201. ret.append(regex['x'].sub('='*len(full_title),self.tag))
  2202. ret.append('') # blank line after
  2203. else:
  2204. ret.append(tagged)
  2205. return ret
  2206. def dump_marked_toc(self, max_level=99):
  2207. "Dumps all toc itens as a valid t2t markup list"
  2208. #TODO maybe use quote+linebreaks instead lists
  2209. ret = []
  2210. toc_count = 1
  2211. for level, count_id, txt, label in self.toc:
  2212. if level > max_level: continue # ignore
  2213. indent = ' '*level
  2214. id_txt = string.lstrip('%s %s'%(count_id, txt))
  2215. label = label or self.anchor_prefix+`toc_count`
  2216. toc_count = toc_count + 1
  2217. # TOC will have links
  2218. if TAGS['anchor']:
  2219. # TOC is more readable with master topics
  2220. # not linked at number. This is a stoled
  2221. # idea from Windows .CHM help files
  2222. if CONF['enum-title'] and level == 1:
  2223. tocitem = '%s+ [""%s"" #%s]'%(
  2224. indent, txt, label)
  2225. else:
  2226. tocitem = '%s- [""%s"" #%s]'%(
  2227. indent, id_txt, label)
  2228. # No links on TOC, just text
  2229. else:
  2230. # man don't reformat TOC lines, cool!
  2231. if TARGET == 'txt' or TARGET == 'man':
  2232. tocitem = '%s""%s""' %(
  2233. indent, id_txt)
  2234. else:
  2235. tocitem = '%s- ""%s""'%(
  2236. indent, id_txt)
  2237. ret.append(tocitem)
  2238. return ret
  2239. ##############################################################################
  2240. #TODO check all this table mess
  2241. # Trata linhas TABLE, com as prop do parse_row
  2242. # O metodo table() do BLOCK xunxa e troca as celulas pelas parseadas
  2243. class TableMaster:
  2244. def __init__(self, line=''):
  2245. self.rows = []
  2246. self.border = 0
  2247. self.align = 'Left'
  2248. self.cellalign = []
  2249. self.cellspan = []
  2250. if line:
  2251. prop = self.parse_row(line)
  2252. self.border = prop['border']
  2253. self.align = prop['align']
  2254. self.cellalign = prop['cellalign']
  2255. self.cellspan = prop['cellspan']
  2256. def _get_open_tag(self):
  2257. topen = TAGS['tableOpen']
  2258. tborder = TAGS['tableBorder']
  2259. talign = TAGS['tableAlign'+self.align]
  2260. calignsep = TAGS['tableColAlignSep']
  2261. calign = ''
  2262. # The first line defines if table has border or not
  2263. if not self.border: tborder = ''
  2264. # Set the columns alignment
  2265. if rules['tablecellaligntype'] == 'column':
  2266. calign = map(lambda x: TAGS['tableColAlign%s'%x],
  2267. self.cellalign)
  2268. calign = string.join(calign, calignsep)
  2269. # Align full table, set border and Column align (if any)
  2270. topen = regex['_tableAlign' ].sub(talign , topen)
  2271. topen = regex['_tableBorder' ].sub(tborder, topen)
  2272. topen = regex['_tableColAlign'].sub(calign , topen)
  2273. # Tex table spec, border or not: {|l|c|r|} , {lcr}
  2274. if calignsep and not self.border:
  2275. # Remove cell align separator
  2276. topen = string.replace(topen, calignsep, '')
  2277. return topen
  2278. def _get_cell_align(self, cells):
  2279. ret = []
  2280. for cell in cells:
  2281. align = 'Left'
  2282. if string.strip(cell):
  2283. if cell[0] == ' ' and cell[-1] == ' ':
  2284. align = 'Center'
  2285. elif cell[0] == ' ':
  2286. align = 'Right'
  2287. ret.append(align)
  2288. return ret
  2289. def _get_cell_span(self, cells):
  2290. ret = []
  2291. for cell in cells:
  2292. span = 0
  2293. m = re.search('\a(\|+)$', cell)
  2294. if m: span = len(m.group(1))+1
  2295. ret.append(span)
  2296. return ret
  2297. def _tag_cells(self, rowdata):
  2298. row = []
  2299. cells = rowdata['cells']
  2300. open = TAGS['tableCellOpen']
  2301. close = TAGS['tableCellClose']
  2302. sep = TAGS['tableCellSep']
  2303. calign = map(lambda x: TAGS['tableCellAlign'+x],
  2304. rowdata['cellalign'])
  2305. # Populate the span tag
  2306. cspan = []
  2307. for i in rowdata['cellspan']:
  2308. if i > 0:
  2309. cspan.append(regex['x'].sub(
  2310. str(i), TAGS['tableCellColSpan']))
  2311. else:
  2312. cspan.append('')
  2313. # Maybe is it a title row?
  2314. if rowdata['title']:
  2315. open = TAGS['tableTitleCellOpen'] or open
  2316. close = TAGS['tableTitleCellClose'] or close
  2317. sep = TAGS['tableTitleCellSep'] or sep
  2318. # Should we break the line on *each* table cell?
  2319. if rules['breaktablecell']: close = close+'\n'
  2320. # Cells pre processing
  2321. if rules['tablecellstrip']:
  2322. cells = map(lambda x: string.strip(x), cells)
  2323. if rowdata['title'] and rules['tabletitlerowinbold']:
  2324. cells = map(lambda x: enclose_me('fontBold',x), cells)
  2325. # Add cell BEGIN/END tags
  2326. for cell in cells:
  2327. copen = open
  2328. # Make sure we will pop from some filled lists
  2329. # Fixes empty line bug '| |'
  2330. this_align = this_span = ''
  2331. if calign: this_align = calign.pop(0)
  2332. if cspan : this_span = cspan.pop(0)
  2333. # Insert cell align into open tag (if cell is alignable)
  2334. if rules['tablecellaligntype'] == 'cell':
  2335. copen = regex['_tableCellAlign'].sub(
  2336. this_align, copen)
  2337. if rules['tablecellspannable']:
  2338. copen = regex['_tableCellColSpan'].sub(
  2339. this_span, copen)
  2340. row.append(copen + cell + close)
  2341. # Maybe there are cell separators?
  2342. return string.join(row, sep)
  2343. def add_row(self, cells):
  2344. self.rows.append(cells)
  2345. def parse_row(self, line):
  2346. # Default table properties
  2347. ret = {'border':0,'title':0,'align':'Left',
  2348. 'cells':[],'cellalign':[], 'cellspan':[]}
  2349. # Detect table align (and remove spaces mark)
  2350. if line[0] == ' ': ret['align'] = 'Center'
  2351. line = string.lstrip(line)
  2352. # Detect title mark
  2353. if line[1] == '|': ret['title'] = 1
  2354. # Detect border mark and normalize the EOL
  2355. m = re.search(' (\|+) *$', line)
  2356. if m: line = line+' ' ; ret['border'] = 1
  2357. else: line = line+' | '
  2358. # Delete table mark
  2359. line = regex['table'].sub('', line)
  2360. # Detect colspan | foo | bar baz |||
  2361. line = re.sub(' (\|+)\| ', '\a\\1 | ', line)
  2362. # Split cells (the last is fake)
  2363. ret['cells'] = string.split(line, ' | ')[:-1]
  2364. # Find cells span
  2365. ret['cellspan'] = self._get_cell_span(ret['cells'])
  2366. # Remove span ID
  2367. ret['cells'] = map(lambda x:re.sub('\a\|+$','',x),ret['cells'])
  2368. # Find cells align
  2369. ret['cellalign'] = self._get_cell_align(ret['cells'])
  2370. # Hooray!
  2371. Debug('Table Prop: %s' % ret, 7)
  2372. return ret
  2373. def dump(self):
  2374. open = self._get_open_tag()
  2375. rows = self.rows
  2376. close = TAGS['tableClose']
  2377. rowopen = TAGS['tableRowOpen']
  2378. rowclose = TAGS['tableRowClose']
  2379. rowsep = TAGS['tableRowSep']
  2380. titrowopen = TAGS['tableTitleRowOpen'] or rowopen
  2381. titrowclose = TAGS['tableTitleRowClose'] or rowclose
  2382. if rules['breaktablelineopen']:
  2383. rowopen = rowopen + '\n'
  2384. titrowopen = titrowopen + '\n'
  2385. # Tex gotchas
  2386. if TARGET == 'tex':
  2387. if not self.border:
  2388. rowopen = titrowopen = ''
  2389. else:
  2390. close = rowopen + close
  2391. # Now we tag all the table cells on each row
  2392. #tagged_cells = map(lambda x: self._tag_cells(x), rows) #!py15
  2393. tagged_cells = []
  2394. for cell in rows: tagged_cells.append(self._tag_cells(cell))
  2395. # Add row separator tags between lines
  2396. tagged_rows = []
  2397. if rowsep:
  2398. #!py15
  2399. #tagged_rows = map(lambda x:x+rowsep, tagged_cells)
  2400. for cell in tagged_cells:
  2401. tagged_rows.append(cell+rowsep)
  2402. # Remove last rowsep, because the table is over
  2403. tagged_rows[-1] = string.replace(
  2404. tagged_rows[-1], rowsep, '')
  2405. # Add row BEGIN/END tags for each line
  2406. else:
  2407. for rowdata in rows:
  2408. if rowdata['title']:
  2409. o,c = titrowopen, titrowclose
  2410. else:
  2411. o,c = rowopen, rowclose
  2412. row = tagged_cells.pop(0)
  2413. tagged_rows.append(o + row + c)
  2414. fulltable = [open] + tagged_rows + [close]
  2415. if rules['blankendtable']: fulltable.append('')
  2416. return fulltable
  2417. ##############################################################################
  2418. class BlockMaster:
  2419. "TIP: use blockin/out to add/del holders"
  2420. def __init__(self):
  2421. self.BLK = []
  2422. self.HLD = []
  2423. self.PRP = []
  2424. self.depth = 0
  2425. self.last = ''
  2426. self.tableparser = None
  2427. self.contains = {
  2428. 'para' :['comment','raw'],
  2429. 'verb' :[],
  2430. 'table' :['comment'],
  2431. 'raw' :[],
  2432. 'tagged' :[],
  2433. 'comment' :[],
  2434. 'quote' :['quote','comment','raw'],
  2435. 'list' :['list' ,'numlist' ,'deflist','para','verb',
  2436. 'comment', 'raw'],
  2437. 'numlist' :['list' ,'numlist' ,'deflist','para','verb',
  2438. 'comment', 'raw'],
  2439. 'deflist' :['list' ,'numlist' ,'deflist','para','verb',
  2440. 'comment', 'raw']
  2441. }
  2442. self.allblocks = self.contains.keys()
  2443. # If one found inside another, ignore the marks
  2444. self.exclusive = ['comment','verb','raw']
  2445. def block(self):
  2446. if not self.BLK: return ''
  2447. return self.BLK[-1]
  2448. def isblock(self, name=''):
  2449. return self.block() == name
  2450. def prop(self, key):
  2451. if not self.PRP: return ''
  2452. return self.PRP[-1].get(key) or ''
  2453. def propset(self, key, val):
  2454. self.PRP[-1][key] = val
  2455. #Debug('BLOCK prop ++: %s->%s'%(key,repr(val)), 1)
  2456. #Debug('BLOCK props: %s'%(repr(self.PRP)), 1)
  2457. def hold(self):
  2458. if not self.HLD: return []
  2459. return self.HLD[-1]
  2460. def holdadd(self, line):
  2461. if self.block()[-4:] == 'list': line = [line]
  2462. self.HLD[-1].append(line)
  2463. Debug('HOLD add: %s'%repr(line), 4)
  2464. Debug('FULL HOLD: %s'%self.HLD, 4)
  2465. def holdaddsub(self, line):
  2466. self.HLD[-1][-1].append(line)
  2467. Debug('HOLD addsub: %s'%repr(line), 4)
  2468. Debug('FULL HOLD: %s'%self.HLD, 4)
  2469. def holdextend(self, lines):
  2470. if self.block()[-4:] == 'list': lines = [lines]
  2471. self.HLD[-1].extend(lines)
  2472. Debug('HOLD extend: %s'%repr(lines), 4)
  2473. Debug('FULL HOLD: %s'%self.HLD, 4)
  2474. def blockin(self, block):
  2475. ret = []
  2476. if block not in self.allblocks:
  2477. Error("Invalid block '%s'"%block)
  2478. # First, let's close other possible open blocks
  2479. while self.block() and block not in self.contains[self.block()]:
  2480. ret.extend(self.blockout())
  2481. # Now we can gladly add this new one
  2482. self.BLK.append(block)
  2483. self.HLD.append([])
  2484. self.PRP.append({})
  2485. if block == 'table': self.tableparser = TableMaster()
  2486. # Deeper and deeper
  2487. self.depth = len(self.BLK)
  2488. Debug('block ++ (%s): %s' % (block,self.BLK), 3)
  2489. return ret
  2490. def blockout(self):
  2491. if not self.BLK: Error('No block to pop')
  2492. self.last = self.BLK.pop()
  2493. result = getattr(self, self.last)()
  2494. parsed = self.HLD.pop()
  2495. self.PRP.pop()
  2496. self.depth = len(self.BLK)
  2497. if self.last == 'table': del self.tableparser
  2498. # Inserting a nested block into mother
  2499. if self.block():
  2500. if self.last != 'comment': # ignore comment blocks
  2501. if self.block()[-4:] == 'list':
  2502. self.HLD[-1][-1].append(result)
  2503. else:
  2504. self.HLD[-1].append(result)
  2505. # Reset now. Mother block will have it all
  2506. result = []
  2507. Debug('block -- (%s): %s' % (self.last,self.BLK), 3)
  2508. Debug('RELEASED (%s): %s' % (self.last,parsed), 3)
  2509. if result: Debug('BLOCK: %s'%result, 6)
  2510. return result
  2511. def _last_escapes(self, line):
  2512. return doFinalEscape(TARGET, line)
  2513. def _get_escaped_hold(self):
  2514. ret = []
  2515. for line in self.hold():
  2516. linetype = type(line)
  2517. if linetype == type(''):
  2518. ret.append(self._last_escapes(line))
  2519. elif linetype == type([]):
  2520. ret.extend(line)
  2521. else:
  2522. Error("BlockMaster: Unknown HOLD item type:"
  2523. " %s"%linetype)
  2524. return ret
  2525. def _remove_twoblanks(self, lastitem):
  2526. if len(lastitem) > 1 and lastitem[-2:] == ['','']:
  2527. return lastitem[:-2]
  2528. return lastitem
  2529. def tagged(self):
  2530. return self.hold()
  2531. def comment(self):
  2532. return ''
  2533. def raw(self):
  2534. lines = self.hold()
  2535. return map(lambda x: doEscape(TARGET, x), lines)
  2536. def para(self):
  2537. result = []
  2538. open = TAGS['paragraphOpen']
  2539. close = TAGS['paragraphClose']
  2540. lines = self._get_escaped_hold()
  2541. # Open (or not) paragraph
  2542. if not open+close and self.last == 'para':
  2543. pass # avoids multiple blank lines
  2544. else:
  2545. result.append(open)
  2546. # Pagemaker likes a paragraph as a single long line
  2547. if rules['onelinepara']:
  2548. result.append(string.join(lines,' '))
  2549. # Others are normal :)
  2550. else:
  2551. result.extend(lines)
  2552. result.append(close)
  2553. # Very very very very very very very very very UGLY fix
  2554. # Needed because <center> can't appear inside <p>
  2555. try:
  2556. if len(lines) == 1 and \
  2557. TARGET in ('html', 'xhtml') and \
  2558. re.match('^\s*<center>.*</center>\s*$', lines[0]):
  2559. result = [lines[0]]
  2560. except: pass
  2561. return result
  2562. def verb(self):
  2563. "Verbatim lines are not masked, so there's no need to unmask"
  2564. result = []
  2565. result.append(TAGS['blockVerbOpen'])
  2566. for line in self.hold():
  2567. if self.prop('mapped') == 'table':
  2568. line = MacroMaster().expand(line)
  2569. if not rules['verbblocknotescaped']:
  2570. line = doEscape(TARGET,line)
  2571. if rules['indentverbblock']:
  2572. line = ' '+line
  2573. if rules['verbblockfinalescape']:
  2574. line = doFinalEscape(TARGET, line)
  2575. result.append(line)
  2576. #TODO maybe use if not TAGS['blockVerbClose']
  2577. if TARGET != 'pm6':
  2578. result.append(TAGS['blockVerbClose'])
  2579. return result
  2580. def table(self):
  2581. # Rewrite all table cells by the unmasked and escaped data
  2582. lines = self._get_escaped_hold()
  2583. for i in xrange(len(lines)):
  2584. cells = string.split(lines[i], SEPARATOR)
  2585. self.tableparser.rows[i]['cells'] = cells
  2586. return self.tableparser.dump()
  2587. def quote(self):
  2588. result = []
  2589. myre = regex['quote']
  2590. open = TAGS['blockQuoteOpen'] # block based
  2591. close = TAGS['blockQuoteClose']
  2592. qline = TAGS['blockQuoteLine'] # line based
  2593. indent = tagindent = '\t'*self.depth
  2594. if rules['tagnotindentable']: tagindent = ''
  2595. if not rules['keepquoteindent']: indent = ''
  2596. if open: result.append(tagindent+open) # open block
  2597. for item in self.hold():
  2598. if type(item) == type([]):
  2599. result.extend(item) # subquotes
  2600. else:
  2601. item = myre.sub('', item) # del TABs
  2602. if rules['barinsidequote']:
  2603. item = get_tagged_bar(item)
  2604. item = self._last_escapes(item)
  2605. item = qline*self.depth + item
  2606. result.append(indent+item) # quote line
  2607. if close: result.append(tagindent+close) # close block
  2608. return result
  2609. def deflist(self): return self.list('deflist')
  2610. def numlist(self): return self.list('numlist')
  2611. def list(self, name='list'):
  2612. result = []
  2613. items = self.hold()
  2614. indent = self.prop('indent')
  2615. tagindent = indent
  2616. listopen = TAGS.get(name+'Open')
  2617. listclose = TAGS.get(name+'Close')
  2618. listline = TAGS.get(name+'ItemLine')
  2619. itemcount = 0
  2620. if rules['tagnotindentable']: tagindent = ''
  2621. if not rules['keeplistindent']: indent = ''
  2622. if name == 'deflist':
  2623. itemopen = TAGS[name+'Item1Open']
  2624. itemclose = TAGS[name+'Item2Close']
  2625. itemsep = TAGS[name+'Item1Close']+\
  2626. TAGS[name+'Item2Open']
  2627. else:
  2628. itemopen = TAGS[name+'ItemOpen']
  2629. itemclose = TAGS[name+'ItemClose']
  2630. itemsep = ''
  2631. # ItemLine: number of leading chars identifies list depth
  2632. if listline:
  2633. itemopen = listline*self.depth
  2634. # Dirty fix for mgp
  2635. if name == 'numlist': itemopen = itemopen + '\a. '
  2636. # Remove two-blanks from list ending mark, to avoid <p>
  2637. items[-1] = self._remove_twoblanks(items[-1])
  2638. # Open list (not nestable lists are only opened at mother)
  2639. if listopen and not \
  2640. (rules['listnotnested'] and BLOCK.depth != 1):
  2641. result.append(tagindent+listopen)
  2642. # Tag each list item (multiline items)
  2643. itemopenorig = itemopen
  2644. for item in items:
  2645. # Add "manual" item count for noautonum targets
  2646. itemcount = itemcount + 1
  2647. if name == 'numlist' and not rules['autonumberlist']:
  2648. n = str(itemcount)
  2649. itemopen = regex['x'].sub(n, itemopenorig)
  2650. del n
  2651. item[0] = self._last_escapes(item[0])
  2652. if name == 'deflist':
  2653. z,term,rest = string.split(item[0],SEPARATOR,2)
  2654. item[0] = rest
  2655. if not item[0]: del item[0] # to avoid <p>
  2656. result.append(tagindent+itemopen+term+itemsep)
  2657. else:
  2658. fullitem = tagindent+itemopen
  2659. result.append(string.replace(
  2660. item[0], SEPARATOR, fullitem))
  2661. del item[0]
  2662. # Process next lines for this item (if any)
  2663. for line in item:
  2664. if type(line) == type([]): # sublist inside
  2665. result.extend(line)
  2666. else:
  2667. line = self._last_escapes(line)
  2668. # Blank lines turns to <p>
  2669. if not line and rules['parainsidelist']:
  2670. line = string.rstrip(indent +\
  2671. TAGS['paragraphOpen']+\
  2672. TAGS['paragraphClose'])
  2673. if not rules['keeplistindent']:
  2674. line = string.lstrip(line)
  2675. result.append(line)
  2676. # Close item (if needed)
  2677. if itemclose: result.append(tagindent+itemclose)
  2678. # Close list (not nestable lists are only closed at mother)
  2679. if listclose and not \
  2680. (rules['listnotnested'] and BLOCK.depth != 1):
  2681. result.append(tagindent+listclose)
  2682. if rules['blankendmotherlist'] and BLOCK.depth == 1:
  2683. result.append('')
  2684. return result
  2685. ##############################################################################
  2686. class MacroMaster:
  2687. def __init__(self, config={}):
  2688. self.name = ''
  2689. self.config = config or CONF
  2690. self.infile = self.config['sourcefile']
  2691. self.outfile = self.config['outfile']
  2692. self.currdate = time.localtime(time.time())
  2693. self.rgx = regex.get('macros') or getRegexes()['macros']
  2694. self.fileinfo = { 'infile': None, 'outfile': None }
  2695. self.dft_fmt = MACROS
  2696. def walk_file_format(self, fmt):
  2697. "Walks the %%{in/out}file format string, expanding the % flags"
  2698. i = 0; ret = '' # counter/hold
  2699. while i < len(fmt): # char by char
  2700. c = fmt[i]; i = i + 1
  2701. if c == '%': # hot char!
  2702. if i == len(fmt): # % at the end
  2703. ret = ret + c
  2704. break
  2705. c = fmt[i]; i = i + 1 # read next
  2706. ret = ret + self.expand_file_flag(c)
  2707. else:
  2708. ret = ret +c # common char
  2709. return ret
  2710. def expand_file_flag(self, flag):
  2711. "%f: filename %F: filename (w/o extension)"
  2712. "%d: dirname %D: dirname (only parent dir)"
  2713. "%p: file path %e: extension"
  2714. info = self.fileinfo[self.name] # get dict
  2715. if flag == '%': x = '%' # %% -> %
  2716. elif flag == 'f': x = info['name']
  2717. elif flag == 'F': x = re.sub('\.[^.]*$','',info['name'])
  2718. elif flag == 'd': x = info['dir']
  2719. elif flag == 'D': x = os.path.split(info['dir'])[-1]
  2720. elif flag == 'p': x = info['path']
  2721. elif flag == 'e': x = re.search('.(\.([^.]+))?$',info['name']
  2722. ).group(2) or ''
  2723. #TODO simpler way for %e ?
  2724. else : x = '%'+flag # false alarm
  2725. return x
  2726. def set_file_info(self, macroname):
  2727. if self.fileinfo.get(macroname): return # already done
  2728. file = getattr(self, self.name) # self.infile
  2729. if file == STDOUT or file == MODULEOUT:
  2730. dir = ''; path = name = file
  2731. else:
  2732. path = os.path.abspath(file)
  2733. dir = os.path.dirname(path)
  2734. name = os.path.basename(path)
  2735. self.fileinfo[macroname] = {'path':path,'dir':dir,'name':name}
  2736. def expand(self, line=''):
  2737. "Expand all macros found on the line"
  2738. while self.rgx.search(line):
  2739. m = self.rgx.search(line)
  2740. name = self.name = string.lower(m.group('name'))
  2741. fmt = m.group('fmt') or self.dft_fmt.get(name)
  2742. if name == 'date':
  2743. txt = time.strftime(fmt,self.currdate)
  2744. elif name == 'mtime':
  2745. if self.infile in (STDIN, MODULEIN):
  2746. fdate = self.currdate
  2747. else:
  2748. mtime = os.path.getmtime(self.infile)
  2749. fdate = time.localtime(mtime)
  2750. txt = time.strftime(fmt,fdate)
  2751. elif name == 'infile' or name == 'outfile':
  2752. self.set_file_info(name)
  2753. txt = self.walk_file_format(fmt)
  2754. else:
  2755. Error("Unknown macro name '%s'"%name)
  2756. line = self.rgx.sub(txt,line,1)
  2757. return line
  2758. ##############################################################################
  2759. def dumpConfig(source_raw, parsed_config):
  2760. onoff = {1:_('ON'), 0:_('OFF')}
  2761. data = [
  2762. (_('RC file') , RC_RAW ),
  2763. (_('source document'), source_raw ),
  2764. (_('command line') , CMDLINE_RAW)
  2765. ]
  2766. # First show all RAW data found
  2767. for label, cfg in data:
  2768. print _('RAW config for %s')%label
  2769. for target,key,val in cfg:
  2770. target = '(%s)'%target
  2771. key = dotted_spaces("%-14s"%key)
  2772. val = val or _('ON')
  2773. print ' %-8s %s: %s'%(target,key,val)
  2774. print
  2775. # Then the parsed results of all of them
  2776. print _('Full PARSED config')
  2777. keys = parsed_config.keys() ; keys.sort() # sorted
  2778. for key in keys:
  2779. val = parsed_config[key]
  2780. # Filters are the last
  2781. if key == 'preproc' or key == 'postproc':
  2782. continue
  2783. # Flag beautifier
  2784. if key in FLAGS.keys() or key in ACTIONS.keys():
  2785. val = onoff.get(val) or val
  2786. # List beautifier
  2787. if type(val) == type([]):
  2788. if key == 'options': sep = ' '
  2789. else : sep = ', '
  2790. val = string.join(val, sep)
  2791. print "%25s: %s"%(dotted_spaces("%-14s"%key),val)
  2792. print
  2793. print _('Active filters')
  2794. for filter in ['preproc','postproc']:
  2795. for rule in parsed_config.get(filter) or []:
  2796. print "%25s: %s -> %s"%(
  2797. dotted_spaces("%-14s"%filter),rule[0],rule[1])
  2798. def get_file_body(file):
  2799. "Returns all the document BODY lines"
  2800. return process_source_file(file, noconf=1)[1][2]
  2801. def finish_him(outlist, config):
  2802. "Writing output to screen or file"
  2803. outfile = config['outfile']
  2804. outlist = unmaskEscapeChar(outlist)
  2805. outlist = expandLineBreaks(outlist)
  2806. # Apply PostProc filters
  2807. if config['postproc']:
  2808. filters = compile_filters(config['postproc'],
  2809. _('Invalid PostProc filter regex'))
  2810. postoutlist = []
  2811. errmsg = _('Invalid PostProc filter replacement')
  2812. for line in outlist:
  2813. for rgx,repl in filters:
  2814. try: line = rgx.sub(repl, line)
  2815. except: Error("%s: '%s'"%(errmsg, repl))
  2816. postoutlist.append(line)
  2817. outlist = postoutlist[:]
  2818. if outfile == MODULEOUT:
  2819. return outlist
  2820. elif outfile == STDOUT:
  2821. if GUI:
  2822. return outlist, config
  2823. else:
  2824. for line in outlist: print line
  2825. else:
  2826. Savefile(outfile, addLineBreaks(outlist))
  2827. if not GUI and not QUIET:
  2828. print _('%s wrote %s')%(my_name,outfile)
  2829. if config['split']:
  2830. if not QUIET: print "--- html..."
  2831. sgml2html = 'sgml2html -s %s -l %s %s'%(
  2832. config['split'],config['lang'] or lang,outfile)
  2833. if not QUIET: print "Running system command:", sgml2html
  2834. os.system(sgml2html)
  2835. def toc_inside_body(body, toc, config):
  2836. ret = []
  2837. if AUTOTOC: return body # nothing to expand
  2838. toc_mark = MaskMaster().tocmask
  2839. # Expand toc mark with TOC contents
  2840. for line in body:
  2841. if string.count(line, toc_mark): # toc mark found
  2842. if config['toc']:
  2843. ret.extend(toc) # include if --toc
  2844. else:
  2845. pass # or remove %%toc line
  2846. else:
  2847. ret.append(line) # common line
  2848. return ret
  2849. def toc_tagger(toc, config):
  2850. "Convert t2t-marked TOC (it is a list) to target-tagged TOC"
  2851. ret = []
  2852. # Tag if TOC-only TOC "by hand" (target don't have a TOC tag)
  2853. if config['toc-only'] or (config['toc'] and not TAGS['TOC']):
  2854. fakeconf = config.copy()
  2855. fakeconf['headers'] = 0
  2856. fakeconf['toc-only'] = 0
  2857. fakeconf['mask-email'] = 0
  2858. fakeconf['preproc'] = []
  2859. fakeconf['postproc'] = []
  2860. fakeconf['css-sugar'] = 0
  2861. ret,foo = convert(toc, fakeconf)
  2862. set_global_config(config) # restore config
  2863. # Target TOC is a tag
  2864. elif config['toc'] and TAGS['TOC']:
  2865. ret = [TAGS['TOC']]
  2866. return ret
  2867. def toc_formatter(toc, config):
  2868. "Formats TOC for automatic placement between headers and body"
  2869. if config['toc-only']: return toc # no formatting needed
  2870. if not config['toc'] : return [] # TOC disabled
  2871. ret = toc
  2872. # TOC open/close tags (if any)
  2873. if TAGS['tocOpen' ]: ret.insert(0, TAGS['tocOpen'])
  2874. if TAGS['tocClose']: ret.append(TAGS['tocClose'])
  2875. # Autotoc specific formatting
  2876. if AUTOTOC:
  2877. if rules['autotocwithbars']: # TOC between bars
  2878. para = TAGS['paragraphOpen']+TAGS['paragraphClose']
  2879. bar = regex['x'].sub('-'*72,TAGS['bar1'])
  2880. tocbar = [para, bar, para]
  2881. ret = tocbar + ret + tocbar
  2882. if rules['blankendautotoc']: # blank line after TOC
  2883. ret.append('')
  2884. if rules['autotocnewpagebefore']: # page break before TOC
  2885. ret.insert(0,TAGS['pageBreak'])
  2886. if rules['autotocnewpageafter']: # page break after TOC
  2887. ret.append(TAGS['pageBreak'])
  2888. return ret
  2889. def doHeader(headers, config):
  2890. if not config['headers']: return []
  2891. if not headers: headers = ['','','']
  2892. target = config['target']
  2893. if not HEADER_TEMPLATE.has_key(target):
  2894. Error("doheader: Unknow target '%s'"%target)
  2895. if target in ('html','xhtml') and config.get('css-sugar'):
  2896. template = string.split(HEADER_TEMPLATE[target+'css'], '\n')
  2897. else:
  2898. template = string.split(HEADER_TEMPLATE[target], '\n')
  2899. head_data = {'STYLE':[], 'ENCODING':''}
  2900. for key in head_data.keys():
  2901. val = config.get(string.lower(key))
  2902. # Remove .sty extension from each style filename (freaking tex)
  2903. # XXX Can't handle --style foo.sty,bar.sty
  2904. if target == 'tex' and key == 'STYLE':
  2905. val = map(lambda x:re.sub('(?i)\.sty$','',x), val)
  2906. if key == 'ENCODING':
  2907. val = get_encoding_string(val, target)
  2908. head_data[key] = val
  2909. # Parse header contents
  2910. for i in 0,1,2:
  2911. # Expand macros
  2912. contents = MacroMaster(config=config).expand(headers[i])
  2913. # Escapes - on tex, just do it if any \tag{} present
  2914. if target != 'tex' or \
  2915. (target == 'tex' and re.search(r'\\\w+{', contents)):
  2916. contents = doEscape(target, contents)
  2917. if target == 'lout':
  2918. contents = doFinalEscape(target, contents)
  2919. head_data['HEADER%d'%(i+1)] = contents
  2920. # css-inside removes STYLE line
  2921. #XXX In tex, this also removes the modules call (%!style:amsfonts)
  2922. if target in ('html','xhtml') and config.get('css-inside') and \
  2923. config.get('style'):
  2924. head_data['STYLE'] = []
  2925. Debug("Header Data: %s"%head_data, 1)
  2926. # Scan for empty dictionary keys
  2927. # If found, scan template lines for that key reference
  2928. # If found, remove the reference
  2929. # If there isn't any other key reference on the same line, remove it
  2930. #TODO loop by template line > key
  2931. for key in head_data.keys():
  2932. if head_data.get(key): continue
  2933. for line in template:
  2934. if string.count(line, '%%(%s)s'%key):
  2935. sline = string.replace(line, '%%(%s)s'%key, '')
  2936. if not re.search(r'%\([A-Z0-9]+\)s', sline):
  2937. template.remove(line)
  2938. # Style is a multiple tag.
  2939. # - If none or just one, use default template
  2940. # - If two or more, insert extra lines in a loop (and remove original)
  2941. styles = head_data['STYLE']
  2942. if len(styles) == 1:
  2943. head_data['STYLE'] = styles[0]
  2944. elif len(styles) > 1:
  2945. style_mark = '%(STYLE)s'
  2946. for i in xrange(len(template)):
  2947. if string.count(template[i], style_mark):
  2948. while styles:
  2949. template.insert(i+1,
  2950. string.replace(
  2951. template[i],
  2952. style_mark,
  2953. styles.pop()))
  2954. del template[i]
  2955. break
  2956. # Populate template with data (dict expansion)
  2957. template = string.join(template, '\n') % head_data
  2958. # Adding CSS contents into template (for --css-inside)
  2959. # This code sux. Dirty++
  2960. if target in ('html','xhtml') and config.get('css-inside') and \
  2961. config.get('style'):
  2962. set_global_config(config) # usually on convert(), needed here
  2963. for i in xrange(len(config['style'])):
  2964. cssfile = config['style'][i]
  2965. if not os.path.isabs(cssfile):
  2966. infile = config.get('sourcefile')
  2967. cssfile = os.path.join(
  2968. os.path.dirname(infile), cssfile)
  2969. try:
  2970. contents = Readfile(cssfile, 1)
  2971. css = "\n%s\n%s\n%s\n%s\n" % (
  2972. doCommentLine("Included %s" % cssfile),
  2973. TAGS['cssOpen'],
  2974. string.join(contents, '\n'),
  2975. TAGS['cssClose'])
  2976. # Style now is content, needs escaping (tex)
  2977. #css = maskEscapeChar(css)
  2978. except:
  2979. errmsg = "CSS include failed for %s" % cssfile
  2980. css = "\n%s\n" % (doCommentLine(errmsg))
  2981. # Insert this CSS file contents on the template
  2982. template = re.sub('(?i)(</HEAD>)', css+r'\1', template)
  2983. # template = re.sub(r'(?i)(\\begin{document})',
  2984. # css+'\n'+r'\1', template) # tex
  2985. # The last blank line to keep everything separated
  2986. template = re.sub('(?i)(</HEAD>)', '\n'+r'\1', template)
  2987. return string.split(template, '\n')
  2988. def doCommentLine(txt):
  2989. # The -- string ends a (h|sg|xht)ml comment :(
  2990. txt = maskEscapeChar(txt)
  2991. if string.count(TAGS['comment'], '--') and \
  2992. string.count(txt, '--'):
  2993. txt = re.sub('-(?=-)', r'-\\', txt)
  2994. if TAGS['comment']:
  2995. return regex['x'].sub(txt, TAGS['comment'])
  2996. return ''
  2997. def doFooter(config):
  2998. if not config['headers']: return []
  2999. ret = []
  3000. target = config['target']
  3001. cmdline = config['realcmdline']
  3002. typename = target
  3003. if target == 'tex': typename = 'LaTeX2e'
  3004. ppgd = '%s code generated by %s %s (%s)'%(
  3005. typename,my_name,my_version,my_url)
  3006. cmdline = 'cmdline: %s %s'%(my_name, string.join(cmdline, ' '))
  3007. ret.append('')
  3008. ret.append(doCommentLine(ppgd))
  3009. ret.append(doCommentLine(cmdline))
  3010. ret.append(TAGS['EOD'])
  3011. return ret
  3012. def doEscape(target,txt):
  3013. "Target-specific special escapes. Apply *before* insert any tag."
  3014. tmpmask = 'vvvvThisEscapingSuxvvvv'
  3015. if target in ('html','sgml','xhtml'):
  3016. txt = re.sub('&','&amp;',txt)
  3017. txt = re.sub('<','&lt;',txt)
  3018. txt = re.sub('>','&gt;',txt)
  3019. if target == 'sgml':
  3020. txt = re.sub('\xff','&yuml;',txt) # "+y
  3021. elif target == 'pm6':
  3022. txt = re.sub('<','<\#60>',txt)
  3023. elif target == 'mgp':
  3024. txt = re.sub('^%',' %',txt) # add leading blank to avoid parse
  3025. elif target == 'man':
  3026. txt = re.sub("^([.'])", '\\&\\1',txt) # command ID
  3027. txt = string.replace(txt,ESCCHAR, ESCCHAR+'e') # \e
  3028. elif target == 'lout':
  3029. # TIP: / moved to FinalEscape to avoid //italic//
  3030. # TIP: these are also converted by lout: ... --- --
  3031. txt = string.replace(txt, ESCCHAR, tmpmask) # \
  3032. txt = string.replace(txt, '"', '"%s""'%ESCCHAR) # "\""
  3033. txt = re.sub('([|&{}@#^~])', '"\\1"',txt) # "@"
  3034. txt = string.replace(txt, tmpmask, '"%s"'%(ESCCHAR*2)) # "\\"
  3035. elif target == 'tex':
  3036. # Mark literal \ to be changed to $\backslash$ later
  3037. txt = string.replace( txt, ESCCHAR, tmpmask)
  3038. txt = re.sub('([#$&%{}])', ESCCHAR+r'\1' , txt) # \%
  3039. txt = re.sub('([~^])' , ESCCHAR+r'\1{}', txt) # \~{}
  3040. txt = re.sub('([<|>])' , r'$\1$', txt) # $>$
  3041. txt = string.replace(txt, tmpmask,
  3042. maskEscapeChar(r'$\backslash$'))
  3043. # TIP the _ is escaped at the end
  3044. return txt
  3045. # TODO man: where - really needs to be escaped?
  3046. def doFinalEscape(target, txt):
  3047. "Last escapes of each line"
  3048. if target == 'pm6' : txt = string.replace(txt,ESCCHAR+'<',r'<\#92><')
  3049. elif target == 'man' : txt = string.replace(txt, '-', r'\-')
  3050. elif target == 'sgml': txt = string.replace(txt, '[', '&lsqb;')
  3051. elif target == 'lout': txt = string.replace(txt, '/', '"/"')
  3052. elif target == 'tex' :
  3053. txt = string.replace(txt, '_', r'\_')
  3054. txt = string.replace(txt, 'vvvvTexUndervvvv', '_') # shame!
  3055. return txt
  3056. def EscapeCharHandler(action, data):
  3057. "Mask/Unmask the Escape Char on the given string"
  3058. if not string.strip(data): return data
  3059. if action not in ('mask','unmask'):
  3060. Error("EscapeCharHandler: Invalid action '%s'"%action)
  3061. if action == 'mask': return string.replace(data,'\\',ESCCHAR)
  3062. else: return string.replace(data,ESCCHAR,'\\')
  3063. def maskEscapeChar(data):
  3064. "Replace any Escape Char \ with a text mask (Input: str or list)"
  3065. if type(data) == type([]):
  3066. return map(lambda x: EscapeCharHandler('mask', x), data)
  3067. return EscapeCharHandler('mask',data)
  3068. def unmaskEscapeChar(data):
  3069. "Undo the Escape char \ masking (Input: str or list)"
  3070. if type(data) == type([]):
  3071. return map(lambda x: EscapeCharHandler('unmask', x), data)
  3072. return EscapeCharHandler('unmask',data)
  3073. def addLineBreaks(mylist):
  3074. "use LB to respect sys.platform"
  3075. ret = []
  3076. for line in mylist:
  3077. line = string.replace(line,'\n',LB) # embedded \n's
  3078. ret.append(line+LB) # add final line break
  3079. return ret
  3080. # Convert ['foo\nbar'] to ['foo', 'bar']
  3081. def expandLineBreaks(mylist):
  3082. ret = []
  3083. for line in mylist:
  3084. ret.extend(string.split(line, '\n'))
  3085. return ret
  3086. def compile_filters(filters, errmsg='Filter'):
  3087. if filters:
  3088. for i in xrange(len(filters)):
  3089. patt,repl = filters[i]
  3090. try: rgx = re.compile(patt)
  3091. except: Error("%s: '%s'"%(errmsg, patt))
  3092. filters[i] = (rgx,repl)
  3093. return filters
  3094. def enclose_me(tagname, txt):
  3095. return TAGS.get(tagname+'Open') + txt + TAGS.get(tagname+'Close')
  3096. def beautify_me(name, line):
  3097. "where name is: bold, italic or underline"
  3098. name = 'font%s' % string.capitalize(name)
  3099. open = TAGS['%sOpen'%name]
  3100. close = TAGS['%sClose'%name]
  3101. txt = r'%s\1%s'%(open, close)
  3102. line = regex[name].sub(txt,line)
  3103. return line
  3104. def get_tagged_link(label, url):
  3105. ret = ''
  3106. target = CONF['target']
  3107. image_re = regex['img']
  3108. # Set link type
  3109. if regex['email'].match(url):
  3110. linktype = 'email'
  3111. else:
  3112. linktype = 'url';
  3113. # Escape specials from TEXT parts
  3114. label = doEscape(target,label)
  3115. # Escape specials from link URL
  3116. if not rules['linkable'] or rules['escapeurl']:
  3117. url = doEscape(target, url)
  3118. # Adding protocol to guessed link
  3119. guessurl = ''
  3120. if linktype == 'url' and \
  3121. re.match('(?i)'+regex['_urlskel']['guess'], url):
  3122. if url[0] in 'Ww': guessurl = 'http://' +url
  3123. else : guessurl = 'ftp://' +url
  3124. # Not link aware targets -> protocol is useless
  3125. if not rules['linkable']: guessurl = ''
  3126. # Simple link (not guessed)
  3127. if not label and not guessurl:
  3128. if CONF['mask-email'] and linktype == 'email':
  3129. # Do the email mask feature (no TAGs, just text)
  3130. url = string.replace(url,'@',' (a) ')
  3131. url = string.replace(url,'.',' ')
  3132. url = "<%s>" % url
  3133. if rules['linkable']: url = doEscape(target, url)
  3134. ret = url
  3135. else:
  3136. # Just add link data to tag
  3137. tag = TAGS[linktype]
  3138. ret = regex['x'].sub(url,tag)
  3139. # Named link or guessed simple link
  3140. else:
  3141. # Adjusts for guessed link
  3142. if not label: label = url # no protocol
  3143. if guessurl : url = guessurl # with protocol
  3144. # Image inside link!
  3145. if image_re.match(label):
  3146. if rules['imglinkable']: # get image tag
  3147. label = parse_images(label)
  3148. else: # img@link !supported
  3149. label = "(%s)"%image_re.match(label).group(1)
  3150. # Putting data on the right appearance order
  3151. if rules['linkable']:
  3152. urlorder = [url, label] # link before label
  3153. else:
  3154. urlorder = [label, url] # label before link
  3155. # Add link data to tag (replace \a's)
  3156. ret = TAGS["%sMark"%linktype]
  3157. for data in urlorder:
  3158. ret = regex['x'].sub(data,ret,1)
  3159. return ret
  3160. def parse_deflist_term(line):
  3161. "Extract and parse definition list term contents"
  3162. img_re = regex['img']
  3163. term = regex['deflist'].search(line).group(3)
  3164. # Mask image inside term as (image.jpg), where not supported
  3165. if not rules['imgasdefterm'] and img_re.search(term):
  3166. while img_re.search(term):
  3167. imgfile = img_re.search(term).group(1)
  3168. term = img_re.sub('(%s)'%imgfile, term, 1)
  3169. #TODO tex: escape ] on term. \], \rbrack{} and \verb!]! don't work :(
  3170. return term
  3171. def get_tagged_bar(line):
  3172. m = regex['bar'].search(line)
  3173. if not m: return line
  3174. txt = m.group(2)
  3175. # Map strong bar to pagebreak
  3176. if rules['mapbar2pagebreak'] and TAGS['pageBreak']:
  3177. TAGS['bar2'] = TAGS['pageBreak']
  3178. # Set bar type
  3179. if txt[0] == '=': bar = TAGS['bar2']
  3180. else : bar = TAGS['bar1']
  3181. # To avoid comment tag confusion like <!-- ------ -->
  3182. if string.count(TAGS['comment'], '--'):
  3183. txt = string.replace(txt,'--','__')
  3184. # Tag line
  3185. return regex['x'].sub(txt, bar)
  3186. def get_image_align(line):
  3187. "Return the image (first found) align for the given line"
  3188. # First clear marks that can mess align detection
  3189. line = re.sub(SEPARATOR+'$', '', line) # remove deflist sep
  3190. line = re.sub('^'+SEPARATOR, '', line) # remove list sep
  3191. line = re.sub('^[\t]+' , '', line) # remove quote mark
  3192. # Get image position on the line
  3193. m = regex['img'].search(line)
  3194. ini = m.start() ; head = 0
  3195. end = m.end() ; tail = len(line)
  3196. # The align detection algorithm
  3197. if ini == head and end != tail: align = 'left' # ^img + text$
  3198. elif ini != head and end == tail: align = 'right' # ^text + img$
  3199. else : align = 'center' # default align
  3200. # Some special cases
  3201. if BLOCK.isblock('table'): align = 'center' # ignore when table
  3202. # if TARGET == 'mgp' and align == 'center': align = 'center'
  3203. return align
  3204. # Reference: http://www.iana.org/assignments/character-sets
  3205. # http://www.drclue.net/F1.cgi/HTML/META/META.html
  3206. def get_encoding_string(enc, target):
  3207. if not enc: return ''
  3208. # Target specific translation table
  3209. translate = {
  3210. 'tex': {
  3211. # missing: ansinew , applemac , cp437 , cp437de , cp865
  3212. 'us-ascii' : 'ascii',
  3213. 'windows-1250': 'cp1250',
  3214. 'windows-1252': 'cp1252',
  3215. 'ibm850' : 'cp850',
  3216. 'ibm852' : 'cp852',
  3217. 'iso-8859-1' : 'latin1',
  3218. 'iso-8859-2' : 'latin2',
  3219. 'iso-8859-3' : 'latin3',
  3220. 'iso-8859-4' : 'latin4',
  3221. 'iso-8859-5' : 'latin5',
  3222. 'iso-8859-9' : 'latin9',
  3223. 'koi8-r' : 'koi8-r'
  3224. }
  3225. }
  3226. # Normalization
  3227. enc = re.sub('(?i)(us[-_]?)?ascii|us|ibm367','us-ascii' , enc)
  3228. enc = re.sub('(?i)(ibm|cp)?85([02])' ,'ibm85\\2' , enc)
  3229. enc = re.sub('(?i)(iso[_-]?)?8859[_-]?' ,'iso-8859-' , enc)
  3230. enc = re.sub('iso-8859-($|[^1-9]).*' ,'iso-8859-1', enc)
  3231. # Apply translation table
  3232. try: enc = translate[target][string.lower(enc)]
  3233. except: pass
  3234. return enc
  3235. ##############################################################################
  3236. ##MerryChristmas,IdontwanttofighttonightwithyouImissyourbodyandIneedyourlove##
  3237. ##############################################################################
  3238. def process_source_file(file='', noconf=0, contents=[]):
  3239. """
  3240. Find and Join all the configuration available for a source file.
  3241. No sanity checking is done on this step.
  3242. It also extracts the source document parts into separate holders.
  3243. The config scan order is:
  3244. 1. The user configuration file (i.e. $HOME/.txt2tagsrc)
  3245. 2. The source document's CONF area
  3246. 3. The command line options
  3247. The return data is a tuple of two items:
  3248. 1. The parsed config dictionary
  3249. 2. The document's parts, as a (head, conf, body) tuple
  3250. All the conversion process will be based on the data and
  3251. configuration returned by this function.
  3252. The source files is read on this step only.
  3253. """
  3254. if contents:
  3255. source = SourceDocument(contents=contents)
  3256. else:
  3257. source = SourceDocument(file)
  3258. head, conf, body = source.split()
  3259. Message(_("Source document contents stored"),2)
  3260. if not noconf:
  3261. # Read document config
  3262. source_raw = source.get_raw_config()
  3263. # Join all the config directives found, then parse it
  3264. full_raw = RC_RAW + source_raw + CMDLINE_RAW
  3265. Message(_("Parsing and saving all config found (%03d items)")%(
  3266. len(full_raw)),1)
  3267. full_parsed = ConfigMaster(full_raw).parse()
  3268. # Add manually the filename to the conf dic
  3269. if contents:
  3270. full_parsed['sourcefile'] = MODULEIN
  3271. full_parsed['infile'] = MODULEIN
  3272. full_parsed['outfile'] = MODULEOUT
  3273. else:
  3274. full_parsed['sourcefile'] = file
  3275. # Maybe should we dump the config found?
  3276. if full_parsed.get('dump-config'):
  3277. dumpConfig(source_raw, full_parsed)
  3278. Quit()
  3279. # Okay, all done
  3280. Debug("FULL config for this file: %s"%full_parsed, 1)
  3281. else:
  3282. full_parsed = {}
  3283. return full_parsed, (head,conf,body)
  3284. def get_infiles_config(infiles):
  3285. """
  3286. Find and Join into a single list, all configuration available
  3287. for each input file. This function is supposed to be the very
  3288. first one to be called, before any processing.
  3289. """
  3290. return map(process_source_file, infiles)
  3291. def convert_this_files(configs):
  3292. global CONF
  3293. for myconf,doc in configs: # multifile support
  3294. target_head = []
  3295. target_toc = []
  3296. target_body = []
  3297. target_foot = []
  3298. source_head, source_conf, source_body = doc
  3299. myconf = ConfigMaster().sanity(myconf)
  3300. # Compose the target file Headers
  3301. #TODO escape line before?
  3302. #TODO see exceptions by tex and mgp
  3303. Message(_("Composing target Headers"),1)
  3304. target_head = doHeader(source_head, myconf)
  3305. # Parse the full marked body into tagged target
  3306. first_body_line = (len(source_head) or 1)+ len(source_conf) + 1
  3307. Message(_("Composing target Body"),1)
  3308. target_body, marked_toc = convert(source_body, myconf,
  3309. firstlinenr=first_body_line)
  3310. # If dump-source, we're done
  3311. if myconf['dump-source']:
  3312. for line in source_head+source_conf+target_body:
  3313. print line
  3314. return
  3315. # Make TOC (if needed)
  3316. Message(_("Composing target TOC"),1)
  3317. tagged_toc = toc_tagger(marked_toc, myconf)
  3318. target_toc = toc_formatter(tagged_toc, myconf)
  3319. target_body = toc_inside_body(target_body, target_toc, myconf)
  3320. if not AUTOTOC and not myconf['toc-only']: target_toc = []
  3321. # Compose the target file Footer
  3322. Message(_("Composing target Footer"),1)
  3323. target_foot = doFooter(myconf)
  3324. # Finally, we have our document
  3325. outlist = target_head + target_toc + target_body + target_foot
  3326. # If on GUI, abort before finish_him
  3327. # If module, return finish_him as list
  3328. # Else, write results to file or STDOUT
  3329. if GUI:
  3330. return outlist, myconf
  3331. elif myconf.get('outfile') == MODULEOUT:
  3332. return finish_him(outlist, myconf), myconf
  3333. else:
  3334. Message(_("Saving results to the output file"),1)
  3335. finish_him(outlist, myconf)
  3336. def parse_images(line):
  3337. "Tag all images found"
  3338. while regex['img'].search(line) and TAGS['img'] != '[\a]':
  3339. txt = regex['img'].search(line).group(1)
  3340. tag = TAGS['img']
  3341. # HTML, XHTML and mgp!
  3342. if rules['imgalignable']:
  3343. align = get_image_align(line)
  3344. # Add align on tag
  3345. align_name = string.capitalize(align)
  3346. align_tag = TAGS['imgAlign'+align_name]
  3347. tag = regex['_imgAlign'].sub(align_tag, tag, 1)
  3348. # Dirty fix to allow centered solo images
  3349. if align == 'center' and TARGET in ('html','xhtml'):
  3350. rest = regex['img'].sub('',line,1)
  3351. if re.match('^\s+$', rest):
  3352. tag = "<center>%s</center>" %tag
  3353. if TARGET == 'tex':
  3354. tag = re.sub(r'\\b',r'\\\\b',tag)
  3355. txt = string.replace(txt, '_', 'vvvvTexUndervvvv')
  3356. line = regex['img'].sub(tag,line,1)
  3357. line = regex['x'].sub(txt,line,1)
  3358. return line
  3359. def add_inline_tags(line):
  3360. # Beautifiers
  3361. for beauti in ('Bold', 'Italic', 'Underline'):
  3362. if regex['font%s'%beauti].search(line):
  3363. line = beautify_me(beauti, line)
  3364. line = parse_images(line)
  3365. return line
  3366. def get_include_contents(file, path=''):
  3367. "Parses %!include: value and extract file contents"
  3368. ids = {'`':'verb', '"':'raw', "'":'tagged' }
  3369. id = 't2t'
  3370. # Set include type and remove identifier marks
  3371. mark = file[0]
  3372. if mark in ids.keys():
  3373. if file[:2] == file[-2:] == mark*2:
  3374. id = ids[mark] # set type
  3375. file = file[2:-2] # remove marks
  3376. # Handle remote dir execution
  3377. filepath = os.path.join(path, file)
  3378. # Read included file contents
  3379. lines = Readfile(filepath, remove_linebreaks=1)
  3380. # Default txt2tags marked text, just BODY matters
  3381. if id == 't2t':
  3382. lines = get_file_body(filepath)
  3383. lines.insert(0, '%%INCLUDED(%s) starts here: %s'%(id,file))
  3384. # This appears when included hit EOF with verbatim area open
  3385. #lines.append('%%INCLUDED(%s) ends here: %s'%(id,file))
  3386. return id, lines
  3387. def set_global_config(config):
  3388. global CONF, TAGS, regex, rules, TARGET
  3389. CONF = config
  3390. TAGS = getTags(CONF)
  3391. rules = getRules(CONF)
  3392. regex = getRegexes()
  3393. TARGET = config['target'] # save for buggy functions that need global
  3394. def convert(bodylines, config, firstlinenr=1):
  3395. global BLOCK
  3396. set_global_config(config)
  3397. target = config['target']
  3398. BLOCK = BlockMaster()
  3399. MASK = MaskMaster()
  3400. TITLE = TitleMaster()
  3401. ret = []
  3402. dump_source = []
  3403. f_lastwasblank = 0
  3404. # Compiling all PreProc regexes
  3405. pre_filter = compile_filters(
  3406. CONF['preproc'], _('Invalid PreProc filter regex'))
  3407. # Let's mark it up!
  3408. linenr = firstlinenr-1
  3409. lineref = 0
  3410. while lineref < len(bodylines):
  3411. # Defaults
  3412. MASK.reset()
  3413. results_box = ''
  3414. untouchedline = bodylines[lineref]
  3415. dump_source.append(untouchedline)
  3416. line = re.sub('[\n\r]+$','',untouchedline) # del line break
  3417. # Apply PreProc filters
  3418. if pre_filter:
  3419. errmsg = _('Invalid PreProc filter replacement')
  3420. for rgx,repl in pre_filter:
  3421. try: line = rgx.sub(repl, line)
  3422. except: Error("%s: '%s'"%(errmsg, repl))
  3423. line = maskEscapeChar(line) # protect \ char
  3424. linenr = linenr +1
  3425. lineref = lineref +1
  3426. Debug(repr(line), 2, linenr) # heavy debug: show each line
  3427. #------------------[ Comment Block ]------------------------
  3428. # We're already on a comment block
  3429. if BLOCK.block() == 'comment':
  3430. # Closing comment
  3431. if regex['blockCommentClose'].search(line):
  3432. ret.extend(BLOCK.blockout() or [])
  3433. continue
  3434. # Normal comment-inside line. Ignore it.
  3435. continue
  3436. # Detecting comment block init
  3437. if regex['blockCommentOpen'].search(line) \
  3438. and BLOCK.block() not in BLOCK.exclusive:
  3439. ret.extend(BLOCK.blockin('comment'))
  3440. continue
  3441. #-------------------------[ Raw Text ]----------------------
  3442. # We're already on a raw block
  3443. if BLOCK.block() == 'raw':
  3444. # Closing raw
  3445. if regex['blockRawClose'].search(line):
  3446. ret.extend(BLOCK.blockout())
  3447. continue
  3448. # Normal raw-inside line
  3449. BLOCK.holdadd(line)
  3450. continue
  3451. # Detecting raw block init
  3452. if regex['blockRawOpen'].search(line) \
  3453. and BLOCK.block() not in BLOCK.exclusive:
  3454. ret.extend(BLOCK.blockin('raw'))
  3455. continue
  3456. # One line raw text
  3457. if regex['1lineRaw'].search(line) \
  3458. and BLOCK.block() not in BLOCK.exclusive:
  3459. ret.extend(BLOCK.blockin('raw'))
  3460. line = regex['1lineRaw'].sub('',line)
  3461. BLOCK.holdadd(line)
  3462. ret.extend(BLOCK.blockout())
  3463. continue
  3464. #------------------------[ Verbatim ]----------------------
  3465. #TIP We'll never support beautifiers inside verbatim
  3466. # Closing table mapped to verb
  3467. if BLOCK.block() == 'verb' \
  3468. and BLOCK.prop('mapped') == 'table' \
  3469. and not regex['table'].search(line):
  3470. ret.extend(BLOCK.blockout())
  3471. # We're already on a verb block
  3472. if BLOCK.block() == 'verb':
  3473. # Closing verb
  3474. if regex['blockVerbClose'].search(line):
  3475. ret.extend(BLOCK.blockout())
  3476. continue
  3477. # Normal verb-inside line
  3478. BLOCK.holdadd(line)
  3479. continue
  3480. # Detecting verb block init
  3481. if regex['blockVerbOpen'].search(line) \
  3482. and BLOCK.block() not in BLOCK.exclusive:
  3483. ret.extend(BLOCK.blockin('verb'))
  3484. f_lastwasblank = 0
  3485. continue
  3486. # One line verb-formatted text
  3487. if regex['1lineVerb'].search(line) \
  3488. and BLOCK.block() not in BLOCK.exclusive:
  3489. ret.extend(BLOCK.blockin('verb'))
  3490. line = regex['1lineVerb'].sub('',line)
  3491. BLOCK.holdadd(line)
  3492. ret.extend(BLOCK.blockout())
  3493. f_lastwasblank = 0
  3494. continue
  3495. # Tables are mapped to verb when target is not table-aware
  3496. if not rules['tableable'] and regex['table'].search(line):
  3497. if not BLOCK.isblock('verb'):
  3498. ret.extend(BLOCK.blockin('verb'))
  3499. BLOCK.propset('mapped', 'table')
  3500. BLOCK.holdadd(line)
  3501. continue
  3502. #---------------------[ blank lines ]-----------------------
  3503. if regex['blankline'].search(line):
  3504. # Close open paragraph
  3505. if BLOCK.isblock('para'):
  3506. ret.extend(BLOCK.blockout())
  3507. f_lastwasblank = 1
  3508. continue
  3509. # Close all open tables
  3510. if BLOCK.isblock('table'):
  3511. ret.extend(BLOCK.blockout())
  3512. f_lastwasblank = 1
  3513. continue
  3514. # Close all open quotes
  3515. while BLOCK.isblock('quote'):
  3516. ret.extend(BLOCK.blockout())
  3517. # Closing all open lists
  3518. if f_lastwasblank: # 2nd consecutive blank
  3519. if BLOCK.block()[-4:] == 'list':
  3520. BLOCK.holdaddsub('') # helps parser
  3521. while BLOCK.depth: # closes list (if any)
  3522. ret.extend(BLOCK.blockout())
  3523. continue # ignore consecutive blanks
  3524. # Paragraph (if any) is wanted inside lists also
  3525. if BLOCK.block()[-4:] == 'list':
  3526. BLOCK.holdaddsub('')
  3527. else:
  3528. # html: show blank line (needs tag)
  3529. if target in ('html','xhtml'):
  3530. ret.append(TAGS['paragraphOpen']+\
  3531. TAGS['paragraphClose'])
  3532. # Otherwise we just show a blank line
  3533. else:
  3534. ret.append('')
  3535. f_lastwasblank = 1
  3536. continue
  3537. #---------------------[ special ]---------------------------
  3538. if regex['special'].search(line):
  3539. # Include command
  3540. targ, key, val = ConfigLines().parse_line(
  3541. line, 'include', target)
  3542. if key:
  3543. Debug("Found config '%s', value '%s'"%(
  3544. key,val),1,linenr)
  3545. incpath = os.path.dirname(CONF['sourcefile'])
  3546. incfile = val
  3547. err = _('A file cannot include itself (loop!)')
  3548. if CONF['sourcefile'] == incfile:
  3549. Error("%s: %s"%(err,incfile))
  3550. inctype, inclines = get_include_contents(
  3551. incfile, incpath)
  3552. # Verb, raw and tagged are easy
  3553. if inctype != 't2t':
  3554. ret.extend(BLOCK.blockin(inctype))
  3555. BLOCK.holdextend(inclines)
  3556. ret.extend(BLOCK.blockout())
  3557. else:
  3558. # Insert include lines into body
  3559. #TODO include maxdepth limit
  3560. bodylines = bodylines[:lineref] \
  3561. +inclines \
  3562. +bodylines[lineref:]
  3563. #TODO fix path if include@include
  3564. # Remove %!include call
  3565. if CONF['dump-source']:
  3566. dump_source.pop()
  3567. continue
  3568. else:
  3569. Debug('Bogus Special Line',1,linenr)
  3570. #---------------------[ dump-source ]-----------------------
  3571. # We don't need to go any further
  3572. if CONF['dump-source']:
  3573. continue
  3574. #---------------------[ Comments ]--------------------------
  3575. # Just skip them (if not macro)
  3576. if regex['comment'].search(line) and not \
  3577. regex['macros'].match(line) and not \
  3578. regex['toc'].match(line):
  3579. continue
  3580. #---------------------[ Triggers ]--------------------------
  3581. # Valid line, reset blank status
  3582. f_lastwasblank = 0
  3583. # Any NOT quote line closes all open quotes
  3584. if BLOCK.isblock('quote') and not regex['quote'].search(line):
  3585. while BLOCK.isblock('quote'):
  3586. ret.extend(BLOCK.blockout())
  3587. # Any NOT table line closes an open table
  3588. if BLOCK.isblock('table') and not regex['table'].search(line):
  3589. ret.extend(BLOCK.blockout())
  3590. #---------------------[ Horizontal Bar ]--------------------
  3591. if regex['bar'].search(line):
  3592. # A bar closes a paragraph
  3593. if BLOCK.isblock('para'):
  3594. ret.extend(BLOCK.blockout())
  3595. # We need to close all opened quote blocks
  3596. # if bar isn't allowed inside or if not a quote line
  3597. if BLOCK.isblock('quote'):
  3598. if not rules['barinsidequote'] or \
  3599. not regex['quote'].search(line):
  3600. while BLOCK.isblock('quote'):
  3601. ret.extend(BLOCK.blockout())
  3602. # Quote + bar: continue processing for quoting
  3603. if rules['barinsidequote'] and \
  3604. regex['quote'].search(line):
  3605. pass
  3606. # Just bar: save tagged line and we're done
  3607. else:
  3608. line = get_tagged_bar(line)
  3609. if BLOCK.block()[-4:] == 'list':
  3610. BLOCK.holdaddsub(line)
  3611. elif BLOCK.block():
  3612. BLOCK.holdadd(line)
  3613. else:
  3614. ret.append(line)
  3615. Debug("BAR: %s"%line, 6)
  3616. continue
  3617. #---------------------[ Title ]-----------------------------
  3618. #TODO set next blank and set f_lastwasblank or f_lasttitle
  3619. if (regex['title'].search(line) or
  3620. regex['numtitle'].search(line)) and \
  3621. BLOCK.block()[-4:] != 'list':
  3622. # A title closes a paragraph
  3623. if BLOCK.isblock('para'):
  3624. ret.extend(BLOCK.blockout())
  3625. TITLE.add(line)
  3626. tagged_title = TITLE.get()
  3627. ret.extend(tagged_title)
  3628. Debug("TITLE: %s"%tagged_title, 6)
  3629. f_lastwasblank = 1
  3630. continue
  3631. #---------------------[ %%toc ]-----------------------
  3632. # %%toc line closes paragraph
  3633. if BLOCK.block() == 'para' and regex['toc'].search(line):
  3634. ret.extend(BLOCK.blockout())
  3635. #---------------------[ apply masks ]-----------------------
  3636. line = MASK.mask(line)
  3637. #XXX from here, only block-inside lines will pass
  3638. #---------------------[ Quote ]-----------------------------
  3639. if regex['quote'].search(line):
  3640. # Store number of leading TABS
  3641. quotedepth = len(regex['quote'].search(line).group(0))
  3642. # SGML doesn't support nested quotes
  3643. if rules['quotenotnested']: quotedepth = 1
  3644. # Don't cross depth limit
  3645. maxdepth = rules['quotemaxdepth']
  3646. if maxdepth and quotedepth > maxdepth:
  3647. quotedepth = maxdepth
  3648. # New quote
  3649. if not BLOCK.isblock('quote'):
  3650. ret.extend(BLOCK.blockin('quote'))
  3651. # New subquotes
  3652. while BLOCK.depth < quotedepth:
  3653. BLOCK.blockin('quote')
  3654. # Closing quotes
  3655. while quotedepth < BLOCK.depth:
  3656. ret.extend(BLOCK.blockout())
  3657. #---------------------[ Lists ]-----------------------------
  3658. # An empty item also closes the current list
  3659. if BLOCK.block()[-4:] == 'list':
  3660. m = regex['listclose'].match(line)
  3661. if m:
  3662. listindent = m.group(1)
  3663. listtype = m.group(2)
  3664. currlisttype = BLOCK.prop('type')
  3665. currlistindent = BLOCK.prop('indent')
  3666. if listindent == currlistindent and \
  3667. listtype == currlisttype:
  3668. ret.extend(BLOCK.blockout())
  3669. continue
  3670. if regex['list'].search(line) or \
  3671. regex['numlist'].search(line) or \
  3672. regex['deflist'].search(line):
  3673. listindent = BLOCK.prop('indent')
  3674. listids = string.join(LISTNAMES.keys(), '')
  3675. m = re.match('^( *)([%s]) '%listids, line)
  3676. listitemindent = m.group(1)
  3677. listtype = m.group(2)
  3678. listname = LISTNAMES[listtype]
  3679. results_box = BLOCK.holdadd
  3680. # Del list ID (and separate term from definition)
  3681. if listname == 'deflist':
  3682. term = parse_deflist_term(line)
  3683. line = regex['deflist'].sub(
  3684. SEPARATOR+term+SEPARATOR,line)
  3685. else:
  3686. line = regex[listname].sub(SEPARATOR,line)
  3687. # Don't cross depth limit
  3688. maxdepth = rules['listmaxdepth']
  3689. if maxdepth and BLOCK.depth == maxdepth:
  3690. if len(listitemindent) > len(listindent):
  3691. listitemindent = listindent
  3692. # List bumping (same indent, diff mark)
  3693. # Close the currently open list to clear the mess
  3694. if BLOCK.block()[-4:] == 'list' \
  3695. and listname != BLOCK.block() \
  3696. and len(listitemindent) == len(listindent):
  3697. ret.extend(BLOCK.blockout())
  3698. listindent = BLOCK.prop('indent')
  3699. # Open mother list or sublist
  3700. if BLOCK.block()[-4:] != 'list' or \
  3701. len(listitemindent) > len(listindent):
  3702. ret.extend(BLOCK.blockin(listname))
  3703. BLOCK.propset('indent',listitemindent)
  3704. BLOCK.propset('type',listtype)
  3705. # Closing sublists
  3706. while len(listitemindent) < len(BLOCK.prop('indent')):
  3707. ret.extend(BLOCK.blockout())
  3708. # O-oh, sublist before list ("\n\n - foo\n- foo")
  3709. # Fix: close sublist (as mother), open another list
  3710. if BLOCK.block()[-4:] != 'list':
  3711. ret.extend(BLOCK.blockin(listname))
  3712. BLOCK.propset('indent',listitemindent)
  3713. BLOCK.propset('type',listtype)
  3714. #---------------------[ Table ]-----------------------------
  3715. #TODO escape undesired format inside table
  3716. #TODO add pm6 target
  3717. if regex['table'].search(line):
  3718. if not BLOCK.isblock('table'): # first table line!
  3719. ret.extend(BLOCK.blockin('table'))
  3720. BLOCK.tableparser.__init__(line)
  3721. tablerow = TableMaster().parse_row(line)
  3722. BLOCK.tableparser.add_row(tablerow) # save config
  3723. # Maintain line to unmask and inlines
  3724. line = string.join(tablerow['cells'], SEPARATOR)
  3725. #---------------------[ Paragraph ]-------------------------
  3726. if not BLOCK.block() and \
  3727. not string.count(line, MASK.tocmask): # new para!
  3728. ret.extend(BLOCK.blockin('para'))
  3729. ############################################################
  3730. ############################################################
  3731. ############################################################
  3732. #---------------------[ Final Parses ]----------------------
  3733. # The target-specific special char escapes for body lines
  3734. line = doEscape(target,line)
  3735. line = add_inline_tags(line)
  3736. line = MASK.undo(line)
  3737. #---------------------[ Hold or Return? ]-------------------
  3738. ### Now we must choose where to put the parsed line
  3739. #
  3740. if not results_box:
  3741. # List item extra lines
  3742. if BLOCK.block()[-4:] == 'list':
  3743. results_box = BLOCK.holdaddsub
  3744. # Other blocks
  3745. elif BLOCK.block():
  3746. results_box = BLOCK.holdadd
  3747. # No blocks
  3748. else:
  3749. line = doFinalEscape(target, line)
  3750. results_box = ret.append
  3751. results_box(line)
  3752. # EOF: close any open para/verb/lists/table/quotes
  3753. Debug('EOF',7)
  3754. while BLOCK.block():
  3755. ret.extend(BLOCK.blockout())
  3756. # Maybe close some opened title area?
  3757. if rules['titleblocks']:
  3758. ret.extend(TITLE.close_all())
  3759. # Maybe a major tag to enclose body? (like DIV for CSS)
  3760. if TAGS['bodyOpen' ]: ret.insert(0, TAGS['bodyOpen'])
  3761. if TAGS['bodyClose']: ret.append(TAGS['bodyClose'])
  3762. if CONF['toc-only']: ret = []
  3763. marked_toc = TITLE.dump_marked_toc(CONF['toc-level'])
  3764. # If dump-source, all parsing is ignored
  3765. if CONF['dump-source']: ret = dump_source[:]
  3766. return ret, marked_toc
  3767. ##############################################################################
  3768. ################################### GUI ######################################
  3769. ##############################################################################
  3770. #
  3771. # Tk help: http://python.org/topics/tkinter/
  3772. # Tuto: http://ibiblio.org/obp/py4fun/gui/tkPhone.html
  3773. # /usr/lib/python*/lib-tk/Tkinter.py
  3774. #
  3775. # grid table : row=0, column=0, columnspan=2, rowspan=2
  3776. # grid align : sticky='n,s,e,w' (North, South, East, West)
  3777. # pack place : side='top,bottom,right,left'
  3778. # pack fill : fill='x,y,both,none', expand=1
  3779. # pack align : anchor='n,s,e,w' (North, South, East, West)
  3780. # padding : padx=10, pady=10, ipadx=10, ipady=10 (internal)
  3781. # checkbox : offvalue is return if the _user_ deselected the box
  3782. # label align: justify=left,right,center
  3783. def load_GUI_resources():
  3784. "Load all extra modules and methods used by GUI"
  3785. global askopenfilename, showinfo, showwarning, showerror, Tkinter
  3786. from tkFileDialog import askopenfilename
  3787. from tkMessageBox import showinfo,showwarning,showerror
  3788. import Tkinter
  3789. class Gui:
  3790. "Graphical Tk Interface"
  3791. def __init__(self, conf={}):
  3792. self.root = Tkinter.Tk() # mother window, come to butthead
  3793. self.root.title(my_name) # window title bar text
  3794. self.window = self.root # variable "focus" for inclusion
  3795. self.row = 0 # row count for grid()
  3796. self.action_length = 150 # left column length (pixel)
  3797. self.frame_margin = 10 # frame margin size (pixel)
  3798. self.frame_border = 6 # frame border size (pixel)
  3799. # The default Gui colors, can be changed by %!guicolors
  3800. self.dft_gui_colors = ['#6c6','white','#cf9','#030']
  3801. self.gui_colors = []
  3802. self.bg1 = self.fg1 = self.bg2 = self.fg2 = ''
  3803. # On Tk, vars need to be set/get using setvar()/get()
  3804. self.infile = self.setvar('')
  3805. self.target = self.setvar('')
  3806. self.target_name = self.setvar('')
  3807. # The checks appearance order
  3808. self.checks = [
  3809. 'headers','enum-title','toc','mask-email',
  3810. 'toc-only','stdout']
  3811. # Creating variables for all checks
  3812. for check in self.checks:
  3813. setattr(self, 'f_'+check, self.setvar(''))
  3814. # Load RC config
  3815. self.conf = {}
  3816. if conf: self.load_config(conf)
  3817. def load_config(self, conf):
  3818. self.conf = conf
  3819. self.gui_colors = conf.get('guicolors') or self.dft_gui_colors
  3820. self.bg1, self.fg1, self.bg2, self.fg2 = self.gui_colors
  3821. self.root.config(bd=15,bg=self.bg1)
  3822. ### Config as dic for python 1.5 compat (**opts don't work :( )
  3823. def entry(self, **opts): return Tkinter.Entry(self.window, opts)
  3824. def label(self, txt='', bg=None, **opts):
  3825. opts.update({'text':txt,'bg':bg or self.bg1})
  3826. return Tkinter.Label(self.window, opts)
  3827. def button(self,name,cmd,**opts):
  3828. opts.update({'text':name,'command':cmd})
  3829. return Tkinter.Button(self.window, opts)
  3830. def check(self,name,checked=0,**opts):
  3831. bg, fg = self.bg2, self.fg2
  3832. opts.update({
  3833. 'text':name, 'onvalue':1, 'offvalue':0,
  3834. 'activeforeground':fg, 'fg':fg,
  3835. 'activebackground':bg, 'bg':bg,
  3836. 'highlightbackground':bg, 'anchor':'w'
  3837. })
  3838. chk = Tkinter.Checkbutton(self.window, opts)
  3839. if checked: chk.select()
  3840. chk.grid(columnspan=2, sticky='w', padx=0)
  3841. def menu(self,sel,items):
  3842. return apply(Tkinter.OptionMenu,(self.window,sel)+tuple(items))
  3843. # Handy auxiliary functions
  3844. def action(self, txt):
  3845. self.label(txt, fg=self.fg1, bg=self.bg1,
  3846. wraplength=self.action_length).grid(column=0,row=self.row)
  3847. def frame_open(self):
  3848. self.window = Tkinter.Frame(self.root,bg=self.bg2,
  3849. borderwidth=self.frame_border)
  3850. def frame_close(self):
  3851. self.window.grid(column=1, row=self.row, sticky='w',
  3852. padx=self.frame_margin)
  3853. self.window = self.root
  3854. self.label('').grid()
  3855. self.row = self.row + 2 # update row count
  3856. def target_name2key(self):
  3857. name = self.target_name.get()
  3858. target = filter(lambda x: TARGET_NAMES[x] == name, TARGETS)
  3859. try : key = target[0]
  3860. except: key = ''
  3861. self.target = self.setvar(key)
  3862. def target_key2name(self):
  3863. key = self.target.get()
  3864. name = TARGET_NAMES.get(key) or key
  3865. self.target_name = self.setvar(name)
  3866. def exit(self): self.root.destroy()
  3867. def setvar(self, val): z = Tkinter.StringVar() ; z.set(val) ; return z
  3868. def askfile(self):
  3869. ftypes= [(_('txt2tags files'),('*.t2t','*.txt')),
  3870. (_('All files'),'*')]
  3871. newfile = askopenfilename(filetypes=ftypes)
  3872. if newfile:
  3873. self.infile.set(newfile)
  3874. newconf = process_source_file(newfile)[0]
  3875. newconf = ConfigMaster().sanity(newconf, gui=1)
  3876. # Restate all checkboxes after file selection
  3877. #TODO how to make a refresh without killing it?
  3878. self.root.destroy()
  3879. self.__init__(newconf)
  3880. self.mainwindow()
  3881. def scrollwindow(self, txt='no text!', title=''):
  3882. # Create components
  3883. win = Tkinter.Toplevel() ; win.title(title)
  3884. frame = Tkinter.Frame(win)
  3885. scroll = Tkinter.Scrollbar(frame)
  3886. text = Tkinter.Text(frame,yscrollcommand=scroll.set)
  3887. button = Tkinter.Button(win)
  3888. # Config
  3889. text.insert(Tkinter.END, string.join(txt,'\n'))
  3890. scroll.config(command=text.yview)
  3891. button.config(text=_('Close'), command=win.destroy)
  3892. button.focus_set()
  3893. # Packing
  3894. text.pack(side='left', fill='both', expand=1)
  3895. scroll.pack(side='right', fill='y')
  3896. frame.pack(fill='both', expand=1)
  3897. button.pack(ipadx=30)
  3898. def runprogram(self):
  3899. global CMDLINE_RAW
  3900. # Prepare
  3901. self.target_name2key()
  3902. infile, target = self.infile.get(), self.target.get()
  3903. # Sanity
  3904. if not target:
  3905. showwarning(my_name,_("You must select a target type!"))
  3906. return
  3907. if not infile:
  3908. showwarning(my_name,
  3909. _("You must provide the source file location!"))
  3910. return
  3911. # Compose cmdline
  3912. guiflags = []
  3913. real_cmdline_conf = ConfigMaster(CMDLINE_RAW).parse()
  3914. if real_cmdline_conf.has_key('infile'):
  3915. del real_cmdline_conf['infile']
  3916. if real_cmdline_conf.has_key('target'):
  3917. del real_cmdline_conf['target']
  3918. real_cmdline = CommandLine().compose_cmdline(real_cmdline_conf)
  3919. default_outfile = ConfigMaster().get_outfile_name(
  3920. {'sourcefile':infile, 'outfile':'', 'target':target})
  3921. for opt in self.checks:
  3922. val = int(getattr(self, 'f_%s'%opt).get() or "0")
  3923. if opt == 'stdout': opt = 'outfile'
  3924. on_config = self.conf.get(opt) or 0
  3925. on_cmdline = real_cmdline_conf.get(opt) or 0
  3926. if opt == 'outfile':
  3927. if on_config == STDOUT: on_config = 1
  3928. else: on_config = 0
  3929. if on_cmdline == STDOUT: on_cmdline = 1
  3930. else: on_cmdline = 0
  3931. if val != on_config or (
  3932. val == on_config == on_cmdline and
  3933. real_cmdline_conf.has_key(opt)):
  3934. if val:
  3935. # Was not set, but user selected on GUI
  3936. Debug("user turned ON: %s"%opt)
  3937. if opt == 'outfile': opt = '-o-'
  3938. else: opt = '--%s'%opt
  3939. else:
  3940. # Was set, but user deselected on GUI
  3941. Debug("user turned OFF: %s"%opt)
  3942. if opt == 'outfile':
  3943. opt = "-o%s"%default_outfile
  3944. else: opt = '--no-%s'%opt
  3945. guiflags.append(opt)
  3946. cmdline = [my_name, '-t', target] +real_cmdline \
  3947. +guiflags +[infile]
  3948. Debug('Gui/Tk cmdline: %s'%cmdline,5)
  3949. # Run!
  3950. cmdline_raw_orig = CMDLINE_RAW
  3951. try:
  3952. # Fake the GUI cmdline as the real one, and parse file
  3953. CMDLINE_RAW = CommandLine().get_raw_config(cmdline[1:])
  3954. data = process_source_file(infile)
  3955. # On GUI, convert_* returns the data, not finish_him()
  3956. outlist, config = convert_this_files([data])
  3957. # On GUI and STDOUT, finish_him() returns the data
  3958. result = finish_him(outlist, config)
  3959. # Show outlist in s a nice new window
  3960. if result:
  3961. outlist, config = result
  3962. title = _('%s: %s converted to %s')%(
  3963. my_name, os.path.basename(infile),
  3964. string.upper(config['target']))
  3965. self.scrollwindow(outlist, title)
  3966. # Show the "file saved" message
  3967. else:
  3968. msg = "%s\n\n %s\n%s\n\n %s\n%s"%(
  3969. _('Conversion done!'),
  3970. _('FROM:'), infile,
  3971. _('TO:'), config['outfile'])
  3972. showinfo(my_name, msg)
  3973. except error: # common error (windowed), not quit
  3974. pass
  3975. except: # fatal error (windowed and printed)
  3976. errormsg = getUnknownErrorMessage()
  3977. print errormsg
  3978. showerror(_('%s FATAL ERROR!')%my_name,errormsg)
  3979. self.exit()
  3980. CMDLINE_RAW = cmdline_raw_orig
  3981. def mainwindow(self):
  3982. self.infile.set(self.conf.get('sourcefile') or '')
  3983. self.target.set(self.conf.get('target') or \
  3984. _('-- select one --'))
  3985. outfile = self.conf.get('outfile')
  3986. if outfile == STDOUT: # map -o-
  3987. self.conf['stdout'] = 1
  3988. if self.conf.get('headers') == None:
  3989. self.conf['headers'] = 1 # map default
  3990. action1 = _("Enter the source file location:")
  3991. action2 = _("Choose the target document type:")
  3992. action3 = _("Some options you may check:")
  3993. action4 = _("Some extra options:")
  3994. checks_txt = {
  3995. 'headers' : _("Include headers on output"),
  3996. 'enum-title': _("Number titles (1, 1.1, 1.1.1, etc)"),
  3997. 'toc' : _("Do TOC also (Table of Contents)"),
  3998. 'mask-email': _("Hide e-mails from SPAM robots"),
  3999. 'toc-only' : _("Just do TOC, nothing more"),
  4000. 'stdout' : _("Dump to screen (Don't save target file)")
  4001. }
  4002. targets_menu = map(lambda x: TARGET_NAMES[x], TARGETS)
  4003. # Header
  4004. self.label("%s %s"%(string.upper(my_name), my_version),
  4005. bg=self.bg2, fg=self.fg2).grid(columnspan=2, ipadx=10)
  4006. self.label(_("ONE source, MULTI targets")+'\n%s\n'%my_url,
  4007. bg=self.bg1, fg=self.fg1).grid(columnspan=2)
  4008. self.row = 2
  4009. # Choose input file
  4010. self.action(action1) ; self.frame_open()
  4011. e_infile = self.entry(textvariable=self.infile,width=25)
  4012. e_infile.grid(row=self.row, column=0, sticky='e')
  4013. if not self.infile.get(): e_infile.focus_set()
  4014. self.button(_("Browse"), self.askfile).grid(
  4015. row=self.row, column=1, sticky='w', padx=10)
  4016. # Show outfile name, style and encoding (if any)
  4017. txt = ''
  4018. if outfile:
  4019. txt = outfile
  4020. if outfile == STDOUT: txt = _('<screen>')
  4021. l_output = self.label(_('Output: ')+txt,
  4022. fg=self.fg2,bg=self.bg2)
  4023. l_output.grid(columnspan=2, sticky='w')
  4024. for setting in ['style','encoding']:
  4025. if self.conf.get(setting):
  4026. name = string.capitalize(setting)
  4027. val = self.conf[setting]
  4028. self.label('%s: %s'%(name, val),
  4029. fg=self.fg2, bg=self.bg2).grid(
  4030. columnspan=2, sticky='w')
  4031. # Choose target
  4032. self.frame_close() ; self.action(action2)
  4033. self.frame_open()
  4034. self.target_key2name()
  4035. self.menu(self.target_name, targets_menu).grid(
  4036. columnspan=2, sticky='w')
  4037. # Options checkboxes label
  4038. self.frame_close() ; self.action(action3)
  4039. self.frame_open()
  4040. # Compose options check boxes, example:
  4041. # self.check(checks_txt['toc'],1,variable=self.f_toc)
  4042. for check in self.checks:
  4043. # Extra options label
  4044. if check == 'toc-only':
  4045. self.frame_close() ; self.action(action4)
  4046. self.frame_open()
  4047. txt = checks_txt[check]
  4048. var = getattr(self, 'f_'+check)
  4049. checked = self.conf.get(check)
  4050. self.check(txt,checked,variable=var)
  4051. self.frame_close()
  4052. # Spacer and buttons
  4053. self.label('').grid() ; self.row = self.row + 1
  4054. b_quit = self.button(_("Quit"), self.exit)
  4055. b_quit.grid(row=self.row, column=0, sticky='w', padx=30)
  4056. b_conv = self.button(_("Convert!"), self.runprogram)
  4057. b_conv.grid(row=self.row, column=1, sticky='e', padx=30)
  4058. if self.target.get() and self.infile.get():
  4059. b_conv.focus_set()
  4060. # As documentation told me
  4061. if sys.platform[:3] == 'win':
  4062. self.root.iconify()
  4063. self.root.update()
  4064. self.root.deiconify()
  4065. self.root.mainloop()
  4066. ##############################################################################
  4067. ##############################################################################
  4068. def exec_command_line(user_cmdline=[]):
  4069. global CMDLINE_RAW, RC_RAW, DEBUG, VERBOSE, QUIET, GUI, Error
  4070. # Extract command line data
  4071. cmdline_data = user_cmdline or sys.argv[1:]
  4072. CMDLINE_RAW = CommandLine().get_raw_config(cmdline_data, relative=1)
  4073. cmdline_parsed = ConfigMaster(CMDLINE_RAW).parse()
  4074. DEBUG = cmdline_parsed.get('debug' ) or 0
  4075. VERBOSE = cmdline_parsed.get('verbose') or 0
  4076. QUIET = cmdline_parsed.get('quiet' ) or 0
  4077. GUI = cmdline_parsed.get('gui' ) or 0
  4078. infiles = cmdline_parsed.get('infile' ) or []
  4079. Message(_("Txt2tags %s processing begins")%my_version,1)
  4080. # The easy ones
  4081. if cmdline_parsed.get('help' ): Quit(USAGE)
  4082. if cmdline_parsed.get('version'): Quit(VERSIONSTR)
  4083. # Multifile haters
  4084. if len(infiles) > 1:
  4085. errmsg=_("Option --%s can't be used with multiple input files")
  4086. for option in NO_MULTI_INPUT:
  4087. if cmdline_parsed.get(option):
  4088. Error(errmsg%option)
  4089. Debug("system platform: %s"%sys.platform)
  4090. Debug("python version: %s"%(string.split(sys.version,'(')[0]))
  4091. Debug("line break char: %s"%repr(LB))
  4092. Debug("command line: %s"%sys.argv)
  4093. Debug("command line raw config: %s"%CMDLINE_RAW,1)
  4094. # Extract RC file config
  4095. if cmdline_parsed.get('rc') == 0:
  4096. Message(_("Ignoring user configuration file"),1)
  4097. else:
  4098. rc_file = get_rc_path()
  4099. if os.path.isfile(rc_file):
  4100. Message(_("Loading user configuration file"),1)
  4101. RC_RAW = ConfigLines(file=rc_file).get_raw_config()
  4102. Debug("rc file: %s"%rc_file)
  4103. Debug("rc file raw config: %s"%RC_RAW,1)
  4104. # Get all infiles config (if any)
  4105. infiles_config = get_infiles_config(infiles)
  4106. # Is GUI available?
  4107. # Try to load and start GUI interface for --gui
  4108. # If program was called with no arguments, try GUI also
  4109. if GUI or not infiles:
  4110. try:
  4111. load_GUI_resources()
  4112. Debug("GUI resources OK (Tk module is installed)")
  4113. winbox = Gui()
  4114. Debug("GUI display OK")
  4115. GUI = 1
  4116. except:
  4117. Debug("GUI Error: no Tk module or no DISPLAY")
  4118. GUI = 0
  4119. # User forced --gui, but it's not available
  4120. if cmdline_parsed.get('gui') and not GUI:
  4121. print getTraceback(); print
  4122. Error("Sorry, I can't run my Graphical Interface - GUI\n"
  4123. "- Check if Python Tcl/Tk module is installed (Tkinter)\n"
  4124. "- Make sure you are in a graphical environment (like X)")
  4125. # Okay, we will use GUI
  4126. if GUI:
  4127. Message(_("We are on GUI interface"),1)
  4128. # Redefine Error function to raise exception instead sys.exit()
  4129. def Error(msg):
  4130. showerror(_('txt2tags ERROR!'), msg)
  4131. raise error
  4132. # If no input file, get RC+cmdline config, else full config
  4133. if not infiles:
  4134. gui_conf = ConfigMaster(RC_RAW+CMDLINE_RAW).parse()
  4135. else:
  4136. try : gui_conf = infiles_config[0][0]
  4137. except: gui_conf = {}
  4138. # Sanity is needed to set outfile and other things
  4139. gui_conf = ConfigMaster().sanity(gui_conf, gui=1)
  4140. Debug("GUI config: %s"%gui_conf,5)
  4141. # Insert config and populate the nice window!
  4142. winbox.load_config(gui_conf)
  4143. winbox.mainwindow()
  4144. # Console mode rocks forever!
  4145. else:
  4146. Message(_("We are on Command Line interface"),1)
  4147. # Called with no arguments, show error
  4148. if not infiles: Error(_('Missing input file (try --help)'))
  4149. convert_this_files(infiles_config)
  4150. Message(_("Txt2tags finished sucessfuly"),1)
  4151. if __name__ == '__main__':
  4152. try:
  4153. exec_command_line()
  4154. except error, msg:
  4155. sys.stderr.write("%s\n"%msg)
  4156. sys.stderr.flush()
  4157. sys.exit(1)
  4158. except SystemExit:
  4159. pass
  4160. except:
  4161. sys.stderr.write(getUnknownErrorMessage())
  4162. sys.stderr.flush()
  4163. sys.exit(1)
  4164. Quit()
  4165. # vim: ts=8