PageRenderTime 79ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/old/txt2tags-2.1.py

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