Пример #1
0
 def genRef(self, ref):
     node = self.doc.getLabel(ref.label)
     if not node:
         common.onWarning("label\"%s\" cannot be resolved" % ref.label)
     else:
         r = self.refs[node]
         self.out.write("<a href=\"%s\">%s</a>" % (r[0], r[1]))
Пример #2
0
def handleLabel(man, match):
    for item in man.iter():
        if item.acceptLabel():
            man.doc.addLabel(match.group(1), item)
            return
    common.onWarning(
        man.message("label %s out of any container" % match.group(1)))
Пример #3
0
    def gen(self, gen):

        # aggregate code
        text = ""
        for line in self.content:
            if text != "":
                text += '\n'
            text += line

        # generate the code
        type = gen.getType()
        if type == 'html':
            gen.genEmbeddedBegin(self)
            gen.genVerbatim('<pre class="code">\n')
            genCode(gen, self.lang, text, type, self.line_number)
            gen.genVerbatim('</pre>')
            gen.genEmbeddedEnd(self)
        elif type == 'latex':
            gen.genEmbeddedBegin(self)
            genCode(gen, self.lang, text, type, self.line_number)
            gen.genEmbeddedEnd(self)
        elif type == 'docbook':
            gen.genVerbatim('<programlisting xml:space="preserve" ')
            if self.lang in DOCBOOK_LANGS:
                gen.genVerbatim(' language="%s"' % DOCBOOK_LANGS[self.lang])
            gen.genVerbatim('>\n')
            gen.genText(self.toText())
            gen.genVerbatim('</programlisting>\n')
        else:
            common.onWarning('backend %s unsupported for code block' % type)
Пример #4
0
 def toText(self, code):
     """Transform the given code to text."""
     try:
         str, _ = self.encoder(unichr(code))
         return str
     except UnicodeEncodeError as e:
         if code in UNICODE_ESCAPES:
             return UNICODE_ESCAPES[code]
         if not (code in self.escaped):
             self.escaped.append(code)
             common.onWarning('encoding %s cannot support character %x' %
                              (self.encoding, code))
         return unicodedata.name(unichr(code))
Пример #5
0
def getCommand():
    global command
    global checked
    if not checked:
        checked = True
        (id, release) = common.getLinuxDistrib()
        if id == "LinuxMint":
            command = "/usr/bin/highlight"
            common.onWarning(
                "LinuxMint detected. Workaround to find 'highlight' command in /usr/bin/"
            )
        else:
            command = common.which("highlight")
            if not command:
                common.onWarning(
                    "no highlight command found: code will not be colored.")
    return command
Пример #6
0
    def genList(self, list):
        if list.kind == 'ul':
            self.out.write('<itemizedlist>\n')
        elif list.kind == 'ol':
            self.out.write('<orderedlist>\n')
        else:
            common.onWarning('docbook does not support %s list' % list.kind)

        for item in list.getItems():
            self.out.write('<listitem>')
            item.gen(self)
            self.out.write('</listitem>\n')

        if list.kind == 'ul':
            self.out.write('</itemizedlist>\n')
        elif list.kind == 'ol':
            self.out.write('</orderedlist>\n')
Пример #7
0
 def gen(self, gen):
     gen.genEmbeddedBegin(self)
     type = gen.getType()
     if type == 'html':
         gen.genVerbatim('<blockquote>\n')
         doc.Container.gen(self, gen)
         gen.genVerbatim('</blockquote>\n')
     elif type == 'latex':
         gen.genVerbatim('\\subparagraph{}\n')
         doc.Container.gen(self, gen)
     elif type == 'docbook':
         gen.genVerbatim('<blockquote>\n')
         doc.Container.gen(self, gen)
         gen.genVerbatim('</blockquote>\n')
     else:
         common.onWarning('%s back-end is not supported by file block' %
                          type)
     gen.genEmbeddedEnd(self)
Пример #8
0
 def gen(self, gen):
     gen.genEmbeddedBegin(self)
     type = gen.getType()
     if type == 'html':
         gen.genVerbatim('<p>\n')
         for line in self.content:
             gen.genText(line + "\n")
         gen.genVerbatim('</>\n')
     elif type == 'latex':
         for line in self.content:
             gen.genText(line + "\n")
     elif type == 'docbook':
         gen.genVerbatim('<para>\n')
         for line in self.content:
             gen.genText(line + "\n")
         gen.genVerbatim('</para>\n')
     else:
         common.onWarning('%s back-end is not supported by file block' %
                          type)
     gen.genEmbeddedEnd(self)
Пример #9
0
 def gen(self, gen):
     gen.genEmbeddedBegin(self)
     type = gen.getType()
     if type == 'html':
         gen.genVerbatim('<pre class="file">\n')
         for line in self.content:
             gen.genText(line + "\n")
         gen.genVerbatim('</pre>\n')
     elif type == 'latex':
         gen.genVerbatim('\\begin{verbatim}\n')
         for line in self.content:
             gen.genText(line + "\n")
         gen.genVerbatim('\\end{verbatim}\n')
     elif type == 'docbook':
         gen.genVerbatim('<screen>\n')
         for line in self.content:
             gen.genText(line + "\n")
         gen.genVerbatim('</screen>\n')
     else:
         common.onWarning('%s back-end is not supported by file block' %
                          type)
     gen.genEmbeddedEnd(self)
Пример #10
0
 def gen(self, gen):
     if gen.getType() == "html":
         self.gen_html(gen)
     else:
         common.onWarning("lexicon cannot be generated for %s" %
                          gen.getType())
Пример #11
0
def handleLexicon(man, match):
    if match.group("garbage"):
        common.onWarning(man.message("garbage after lexicon!"))
    man.send(
        doc.ObjectEvent(doc.L_PAR, doc.ID_NEW, Lexicon(man.lexicon.lexicon)))
Пример #12
0
 def warn(self, msg):
     """Display a warning with file and line."""
     common.onWarning(self.message(msg))
Пример #13
0
    def prepare(self, gen):
        type = gen.getType()
        command = getCommand()
        if not command:
            return

        # parse list of languages
        try:
            global LANGS
            ans = subprocess.check_output("%s -p" % command,
                                          shell=True).decode('utf-8')
            LANGS = []
            for line in ans.split("\n"):
                try:
                    p = line.index(":")
                    if p >= 0:
                        line = line[p + 1:]
                        for w in line.split():
                            if w != '(' and w != ')':
                                LANGS.append(w)
                except ValueError as e:
                    pass
        except subprocess.CalledProcessError as e:
            common.onWarning(
                "cannot get supported languages from %s, falling back to default list."
                % command)

        # build the CSS file
        if type in CSS_BACKS:
            try:
                css = gen.new_friend('highlight/highlight.css')
                cfd = True
                if os.name == "nt":
                    cfd = False
                process = subprocess.Popen(
                    ['%s -f --syntax=c --style-outfile=%s' % (command, css)],
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    close_fds=cfd,
                    shell=True)
                _ = process.communicate("")
            except OSError as e:
                sys.stderr.write("ERROR: can not call 'highlight'\n")
                sys.exit(1)

            # add the file to the style
            styles = gen.doc.getVar('HTML_STYLES')
            if styles:
                styles += ':'
            styles += css
            gen.doc.setVar('HTML_STYLES', styles)

        # build .sty
        if type == 'latex':
            try:
                css = gen.new_friend('highlight/highlight.sty')
                process = subprocess.Popen([
                    '%s -f --syntax=c --style-outfile=%s %s' %
                    (command, css, BACKS[type])
                ],
                                           stdin=subprocess.PIPE,
                                           stdout=subprocess.PIPE,
                                           close_fds=True,
                                           shell=True)
                _ = process.communicate("")
            except OSError as e:
                sys.stderr.write("ERROR: can not call 'highlight'\n")
                sys.exit(1)

            # build the preamble
            preamble = gen.doc.getVar('LATEX_PREAMBLE')
            preamble += '\\usepackage{color}\n'
            preamble += '\\usepackage{alltt}\n'
            preamble += '\\input {%s}\n' % css
            gen.doc.setVar('LATEX_PREAMBLE', preamble)
Пример #14
0
 def finalize_output(self, gen):
     try:
         shutil.move(self.out_path, self.get_path(gen))
     except IOError as e:
         common.onWarning(
             "plantuml error: %s. Cannot generate plantuml diagram." % e)
Пример #15
0
 def onWarning(self, msg):
     """Called to display a warning."""
     common.onWarning('%s:%d: %s' % (self.file, self.line, msg))
Пример #16
0
    def run(self):
        self.openMain('.tex')
        self.doc.pregen(self)

        # get class
        cls = self.doc.getVar('LATEX_CLASS')
        if not cls:
            cls = 'book'
        preamble = self.doc.getVar('LATEX_PREAMBLE')

        # look for internationalization
        lang = self.doc.getVar('LANG').lower().replace('-', '_')
        if lang:
            if lang in LANGUAGES:
                lang = LANGUAGES[lang]
            else:
                pos = lang.find('_')
                if pos < 0:
                    common.onError('cannot not support "%s"' % lang)
                else:
                    lang = lang[:pos]
                    if lang in LANGUAGES:
                        lang = LANGUAGES[lang]
                    else:
                        common.onError('cannot not support "%s"' % lang)

        # look for encoding
        self.encoding = self.doc.getVar('ENCODING').lower().replace('-', '_')
        if self.encoding:
            if self.encoding == 'utf_8':
                preamble += '\\usepackage{ucs}\n'
                preamble += '\\usepackage[utf8x]{inputenc}\n'
                self.encoder = UTF8Encoder()
            elif self.encoding == 'iso_8859_1':
                preamble += '\\usepackage[latin1]{inputenc}\n'
                self.encoder = NonUnicodeEncoder(self.encoding)
            else:
                common.onWarning('%s encoding is just ignored for latex' %
                                 self.encoding)

        # look paper size
        paper = self.doc.getVar('LATEX_PAPER')
        if not paper:
            paper = 'a4paper'

        # preamble
        self.out.write('\\documentclass[oneside,%s,%s]{%s}\n' %
                       (paper, lang, cls))
        self.out.write('\\usepackage[T1]{fontenc}\n')
        self.out.write('\\usepackage[pdftex]{graphicx}\n')
        self.out.write('\\usepackage{hyperref}\n')
        self.out.write('\\usepackage{verbatim}\n')
        #self.out.write('\\usepackage{fancyhdr}\n')
        self.out.write('\\usepackage[export]{adjustbox}\n')

        self.out.write(preamble)
        if lang:
            self.out.write('\\usepackage[%s]{babel}\n' % lang)
        is_koma = cls in KOMA_STYLES

        # add custom definitions
        self.out.write(
            '\\newcommand{\\superscript}[1]{\\ensuremath{^{\\textrm{#1}}}}\n')
        self.out.write(
            '\\newcommand{\\subscript}[1]{\\ensuremath{_{\\textrm{#1}}}}\n')
        self.out.write('\\headheight=20pt\n')
        self.out.write('\\headsep=10pt\n')

        self.out.write('\\begin{document}\n')

        # write title
        latex_title = self.doc.getVar("LATEX_TITLE")
        if not latex_title:
            self.out.write('\\title{%s}\n' %
                           self.escape(self.doc.getVar('TITLE')))
            subtitle = self.doc.getVar("SUBTITLE")
            if is_koma and subtitle:
                self.out.write("\\subtitle{%s}\n" % self.escape(subtitle))
            # NOTE: \thanks{...} allows to give the owner organization of an author
            self.out.write('\\author{%s}\n' % self.escape(
                self.doc.getVar('AUTHORS')).replace(",", " \\and "))
            organization = self.doc.getVar("ORGANIZATION")
            if is_koma and organization:
                self.out.write("\\publishers{%s}\n" %
                               self.escape(organization))
            self.out.write('\\maketitle\n\n')
        else:

            self.out.write("\\begin{titlepage}\n")
            self.out.write("\\newcommand{\\thotorganization}{%s}\n" %
                           self.escape(self.doc.getVar("ORGANIZATION")))
            self.out.write("\\newcommand{\\thottitle}{%s}\n" %
                           self.escape(self.doc.getVar("TITLE")))
            self.out.write("\\newcommand{\\thotsubtitle}{%s}\n" %
                           self.escape(self.doc.getVar("SUBTITLE")))
            self.out.write(
                "\\newcommand{\\thotauthors}{%s}\n" % ("{" + self.escape(
                    self.doc.getVar("AUTHORS")).replace(",", "} {") + "}"))
            logos = self.doc.getVar("LOGO")
            text = ""
            fst = True
            for logo in logos.split(","):
                if not fst:
                    text = text + " \\hfill "
                else:
                    fst = False
                text = text + "\includegraphics{%s}" % logo.strip()
            self.out.write("\\newcommand{\\thotlogos}{%s}\n" % text)
            file = open(latex_title)
            for l in file:
                self.out.write(l)
            self.out.write("\\end{titlepage}\n")

        # generate the content
        self.out.write('\\tableofcontents\n\n')
        self.out.write('\\pagebreak\n\n')

        # write body
        self.doc.gen(self)

        # write footer
        self.out.write('\\end{document}\n')
        self.out.close()

        # generate final format
        output = self.doc.getVar('OUTPUT')
        if not output or output == 'latex':
            print("SUCCESS: result in %s" % self.path)
        elif output == 'pdf':

            # perform compilation
            for i in xrange(0, 2):  # two times for TOC (sorry)
                dir, file = os.path.split(self.path)
                cmd = 'pdflatex -halt-on-error %s' % file
                if dir == "":
                    dir = "."
                process = subprocess.Popen(cmd,
                                           shell=True,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           cwd=dir)
                out, err = process.communicate('')
                if process.returncode != 0:
                    sys.stdout.write(out)
                    sys.stderr.write(err)
                    return

            # display result
            file, ext = os.path.splitext(self.path)
            if ext == ".tex":
                path = file
            else:
                path = self.path
            path = path + ".pdf"
            print("SUCCESS: result in %s" % path)
        else:
            common.onError('unknown output: %s' % output)