def render(self, context, mimetype, content, filename=None, rev=None): # -n to ignore php.ini so we're using default colors cmdline = '%s -sn' % self.path self.log.debug("PHP command line: %s" % cmdline) content = content_to_unicode(self.env, content, mimetype) content = content.encode('utf-8') np = NaivePopen(cmdline, content, capturestderr=1) if (os.name != 'nt' and np.errorlevel) or np.err: msg = 'Running (%s) failed: %s, %s.' % (cmdline, np.errorlevel, np.err) raise Exception(msg) odata = ''.join(np.out.splitlines()[1:-1]) if odata.startswith('X-Powered-By:') or \ odata.startswith('Content-type:'): raise TracError(_('You appear to be using the PHP CGI ' 'binary. Trac requires the CLI version ' 'for syntax highlighting.')) epilogues = ["</span>", "</font>"] for e in epilogues: if odata.endswith(e): odata = odata[:-len(e)] break html = PhpDeuglifier().format(odata.decode('utf-8')) # PHP generates _way_ too many non-breaking spaces... # We don't need them anyway, so replace them by normal spaces return [Markup(line.replace(' ', ' ')) for line in html.split('<br />')]
def render(self, req, mimetype, content, filename=None, rev=None): """Returns wikicreole text as html""" text = content_to_unicode(self.env, content, mimetype) if text.startswith(u"\ufeff"): text = text[1:] html = creoleparser.creole2html(text) return html
def render(self, req, mimetype, content, filename=None, rev=None): # -n to ignore php.ini so we're using default colors cmdline = '%s -sn' % self.path self.env.log.debug("PHP command line: %s" % cmdline) content = content_to_unicode(self.env, content, mimetype) content = content.encode('utf-8') np = NaivePopen(cmdline, content, capturestderr=1) if (os.name != 'nt' and np.errorlevel) or np.err: msg = u'L\'exécution de la commande (%s) a echoué : %s, %s.' \ % (cmdline, np.errorlevel, np.err) raise Exception(msg) odata = ''.join(np.out.splitlines()[1:-1]) if odata.startswith('X-Powered-By:') or \ odata.startswith('Content-type:'): raise TracError( u'Apparemment, vous utilisez la version CGI de PHP. ' u'Trac a besoin de la version CLI pour réaliser la ' u'coloration syntaxique.') epilogues = ["</span>", "</font>"] for e in epilogues: if odata.endswith(e): odata = odata[:-len(e)] break html = PhpDeuglifier().format(odata.decode('utf-8')) for line in html.split('<br />'): # PHP generates _way_ too many non-breaking spaces... # We don't need them anyway, so replace them by normal spaces yield line.replace(' ', ' ')
def render(self, context, mimetype, content, filename=None, rev=None): req = context.req content = content_to_unicode(self.env, content, mimetype) changes = self._diff_to_hdf(content.splitlines(), Mimeview(self.env).tab_width) if not changes or not any(c['diffs'] for c in changes): self.log.debug( "Invalid unified diff content: %.40r... (%d " "characters)", content, len(content)) return data = { 'diff': { 'style': 'inline' }, 'no_id': True, 'changes': changes, 'longcol': 'File', 'shortcol': '' } add_script(req, 'common/js/diff.js') add_stylesheet(req, 'common/css/diff.css') return Chrome(self.env).render_template(req, 'diff_div.html', data, fragment=True)
def render(self, req, mimetype, content, filename=None, rev=None): # -n to ignore php.ini so we're using default colors cmdline = '%s -sn' % self.path self.env.log.debug("PHP command line: %s" % cmdline) content = content_to_unicode(self.env, content, mimetype) content = content.encode('utf-8') np = NaivePopen(cmdline, content, capturestderr=1) if (os.name != 'nt' and np.errorlevel) or np.err: msg = u'L\'exécution de la commande (%s) a echoué : %s, %s.' \ % (cmdline, np.errorlevel, np.err) raise Exception(msg) odata = ''.join(np.out.splitlines()[1:-1]) if odata.startswith('X-Powered-By:') or \ odata.startswith('Content-type:'): raise TracError(u'Apparemment, vous utilisez la version CGI de PHP. ' u'Trac a besoin de la version CLI pour réaliser la ' u'coloration syntaxique.') epilogues = ["</span>", "</font>"] for e in epilogues: if odata.endswith(e): odata = odata[:-len(e)] break html = PhpDeuglifier().format(odata.decode('utf-8')) for line in html.split('<br />'): # PHP generates _way_ too many non-breaking spaces... # We don't need them anyway, so replace them by normal spaces yield line.replace(' ', ' ')
def render(self, context, mimetype, content, filename=None, rev=None): # -n to ignore php.ini so we're using default colors cmdline = '%s -sn' % self.path self.log.debug("PHP command line: %s" % cmdline) content = content_to_unicode(self.env, content, mimetype) content = content.encode('utf-8') np = NaivePopen(cmdline, content, capturestderr=1) if (os.name != 'nt' and np.errorlevel) or np.err: msg = 'Running (%s) failed: %s, %s.' % (cmdline, np.errorlevel, np.err) raise Exception(msg) odata = ''.join(np.out.splitlines()[1:-1]) if odata.startswith('X-Powered-By:') or \ odata.startswith('Content-type:'): raise TracError( _('You appear to be using the PHP CGI ' 'binary. Trac requires the CLI version ' 'for syntax highlighting.')) epilogues = ["</span>", "</font>"] for e in epilogues: if odata.endswith(e): odata = odata[:-len(e)] break html = PhpDeuglifier().format(odata.decode('utf-8')) # PHP generates _way_ too many non-breaking spaces... # We don't need them anyway, so replace them by normal spaces return [ Markup(line.replace(' ', ' ')) for line in html.split('<br />') ]
def render(self, context, mimetype, content, filename=None, rev=None): # Minimize visual impact of errors from docutils.writers import html4css1 class TracHTMLTranslator(html4css1.HTMLTranslator): """Specialized translator with unobtrusive error reporting""" def visit_system_message(self, node): paragraph = node.children.pop(0) message = escape(paragraph.astext()) if paragraph else '' backrefs = node['backrefs'] if backrefs: span = ('<span class="system-message">%s</span>' % (''.join('<a href="#%s" title="%s">?</a>' % (backref, message) for backref in backrefs))) else: span = ('<span class="system-message" title="%s">?</span>' % message) self.body.append(span) def depart_system_message(self, node): pass writer = html4css1.Writer() writer.translator_class = TracHTMLTranslator inliner = rst.states.Inliner() inliner.trac = (self.env, context) parser = rst.Parser(inliner=inliner) content = content_to_unicode(self.env, content, mimetype) parts = publish_parts(content, writer=writer, parser=parser, settings_overrides={'halt_level': 6, 'warning_stream': False, 'file_insertion_enabled': 0, 'raw_enabled': 0, 'warning_stream': False}) return parts['html_body']
def render(self, context, mimetype, content, filename=None, rev=None): # Minimize visual impact of errors class TracHTMLTranslator(html4css1.HTMLTranslator): """Specialized translator with unobtrusive error reporting and some extra security features""" def __init__(self, *args, **kwargs): self._render_unsafe_content = wikisys.render_unsafe_content self._safe_schemes = set(wikisys.safe_schemes) html4css1.HTMLTranslator.__init__(self, *args, **kwargs) def visit_system_message(self, node): paragraph = node.children.pop(0) message = escape(paragraph.astext()) if paragraph else '' backrefs = node['backrefs'] if backrefs: span = ('<span class="system-message">%s</span>' % (''.join('<a href="#%s" title="%s">?</a>' % (backref, message) for backref in backrefs))) else: span = ('<span class="system-message" title="%s">?</span>' % message) self.body.append(span) def depart_system_message(self, node): pass def visit_image(self, node): html4css1.HTMLTranslator.visit_image(self, node) uri = node.attributes.get('uri') if not wikisys.is_safe_origin(uri, context.req): self.body[-1] = self.body[-1].replace( '<img ', '<img crossorigin="anonymous" ') def visit_reference(self, node): if self._is_safe_uri(node.get('refuri')): html4css1.HTMLTranslator.visit_reference(self, node) def depart_reference(self, node): if self._is_safe_uri(node.get('refuri')): html4css1.HTMLTranslator.depart_reference(self, node) def _is_safe_uri(self, uri): if self._render_unsafe_content or not uri: return True else: pos = uri.find(':') return pos < 0 or uri[0:pos] in self._safe_schemes wikisys = WikiSystem(self.env) writer = html4css1.Writer() writer.translator_class = TracHTMLTranslator inliner = rst.states.Inliner() inliner.trac = (self.env, context) parser = rst.Parser(inliner=inliner) content = content_to_unicode(self.env, content, mimetype) # The default Reader is explicitly passed as a workaround for #11248 parts = publish_parts(content, writer=writer, parser=parser, reader=standalone.Reader(parser), settings_overrides={'halt_level': 6, 'file_insertion_enabled': 0, 'raw_enabled': 0, 'warning_stream': False}) return parts['html_body']
def render(self, context, mimetype, content, filename=None, url=None): self.log.debug("Using Markdown Mimeviewer") req = context.req add_stylesheet(req, 'readme/readme.css') content = content_to_unicode(self.env, content, mimetype) # for some insane reason genshi will only preserve whitespace of # <pre> elements, trac calls Stream.render() inappropriately. return tag.pre(content.encode('utf-8'))
def render(self, context, mimetype, content, filename=None, url=None): self.log.debug("Using Markdown Mimeviewer") req = context.req add_stylesheet(req, 'readme/readme.css') add_script(req, 'readme/marked.js') content = content_to_unicode(self.env, content, mimetype) # for some insane reason genshi will only preserve whitespace of <pre> elements, trac calls Stream.render() inappropriately. return tag.pre(content.encode('utf-8'))
def render(self, context, mimetype, content, filename=None, rev=None): inliner = rst.states.Inliner() inliner.trac = (self.env, context) parser = rst.Parser(inliner=inliner) content = content_to_unicode(self.env, content, mimetype) parts = publish_parts(content, writer_name='html', parser=parser, settings_overrides={'halt_level': 6, 'file_insertion_enabled': 0, 'raw_enabled': 0}) return parts['html_body']
def render(self, req, mimetype, content, filename=None, rev=None): from trac.web.clearsilver import HDFWrapper content = content_to_unicode(self.env, content, mimetype) d = self._diff_to_hdf(content.splitlines(), Mimeview(self.env).tab_width) if not d: raise TracError, 'Invalid unified diff content' hdf = HDFWrapper(loadpaths=[self.env.get_templates_dir(), self.config.get('trac', 'templates_dir')]) hdf['diff.files'] = d add_stylesheet(req, 'common/css/diff.css') return hdf.render(hdf.parse(self.diff_cs))
def render(self, req, mimetype, content, filename=None, rev=None): from trac.web.clearsilver import HDFWrapper content = content_to_unicode(self.env, content, mimetype) d = self._diff_to_hdf(content.splitlines(), Mimeview(self.env).tab_width) if not d: raise TracError, u'Contenu diff unifié invalide' hdf = HDFWrapper(loadpaths=[self.env.get_templates_dir(), self.config.get('trac', 'templates_dir')]) hdf['diff.files'] = d add_stylesheet(req, 'common/css/diff.css') return hdf.render(hdf.parse(self.diff_cs))
def render(self, context, mimetype, content, filename=None, rev=None): inliner = rst.states.Inliner() inliner.trac = (self.env, context) parser = rst.Parser(inliner=inliner) content = content_to_unicode(self.env, content, mimetype) parts = publish_parts(content, writer_name='html', parser=parser, settings_overrides={ 'halt_level': 6, 'file_insertion_enabled': 0, 'raw_enabled': 0 }) return parts['html_body']
def render(self, context, mimetype, content, filename=None, rev=None): req = context.req content = content_to_unicode(self.env, content, mimetype) changes = self._diff_to_hdf(content.splitlines(), Mimeview(self.env).tab_width) if not changes or not any(c['diffs'] for c in changes): self.log.warning('Invalid unified diff content') return data = {'diff': {'style': 'inline'}, 'no_id': True, 'changes': changes, 'longcol': 'File', 'shortcol': ''} add_script(req, 'common/js/diff.js') add_stylesheet(req, 'common/css/diff.css') return Chrome(self.env).render_template(req, 'diff_div.html', data, fragment=True)
def render(self, context, mimetype, content, filename=None, rev=None): req = context.req from trac.web.chrome import Chrome content = content_to_unicode(self.env, content, mimetype) changes = self._diff_to_hdf(content.splitlines(), Mimeview(self.env).tab_width) if not changes: raise TracError(_('Invalid unified diff content')) data = {'diff': {'style': 'inline'}, 'no_id': True, 'changes': changes, 'longcol': 'File', 'shortcol': ''} add_script(req, 'common/js/diff.js') add_stylesheet(req, 'common/css/diff.css') return Chrome(self.env).render_template(req, 'diff_div.html', data, fragment=True)
def render(self, req, mimetype, content, filename=None, rev=None): #cmdline = '/usr/bin/groff -Tutf8 -a -mandoc ' cmdline = self.config.get('mimeviewer', 'groff_path') if len(cmdline) == 0: cmdline = '/usr/bin/groff' self.env.log.debug("groff got command line: %s" % cmdline) cmdline += ' -Thtml -P -r -P -l -mandoc ' self.env.log.debug("groff command line: %s" % cmdline) content = content_to_unicode(self.env, content, mimetype) cont=content.encode('utf-8') np = NaivePopen(cmdline, cont, capturestderr=1) if np.errorlevel or np.err: err = 'Running (%s) failed: %s, %s.' % (cmdline, np.errorlevel, np.err) raise Exception, err return np.out
def render(self, req, mimetype, content, filename=None, rev=None): #cmdline = '/usr/bin/groff -Tutf8 -a -mandoc ' cmdline = self.config.get('mimeviewer', 'groff_path') if len(cmdline) == 0: cmdline = '/usr/bin/groff' self.env.log.debug("groff got command line: %s" % cmdline) cmdline += ' -Thtml -P -r -P -l -mandoc ' self.env.log.debug("groff command line: %s" % cmdline) content = content_to_unicode(self.env, content, mimetype) cont = content.encode('utf-8') np = NaivePopen(cmdline, cont, capturestderr=1) if np.errorlevel or np.err: err = 'Running (%s) failed: %s, %s.' % (cmdline, np.errorlevel, np.err) raise Exception, err return np.out
def render(self, req, mimetype, content, filename=None, rev=None): try: from docutils import nodes from docutils.core import publish_parts from docutils.parsers import rst from docutils import __version__ except ImportError: raise TracError, u'La bibliothèque Docutils est introuvable' if StrictVersion(__version__) < StrictVersion('0.3.9'): raise TracError, u'Une version >= %s de Docutils est requise, la version %s a été détectée' \ % ('0.3.9', __version__) def trac_get_reference(rawtext, target, text): fulltext = text and target + ' ' + text or target link = wiki_to_link(fulltext, self.env, req) uri = None missing = False if isinstance(link, Element): linktext = Markup(link).striptags() # the following is a bit hackish, but it takes into account: # - an eventual trailing '?' for missing wiki pages # - space eventually introduced due to split_page_names option if linktext.rstrip('?').replace(' ', '') != target: text = linktext uri = link.attr.get('href', '') missing = 'missing' in link.attr.get('class_', '') else: uri = req.href.wiki(target) missing = not WikiSystem(self.env).has_page(target) if uri: reference = nodes.reference(rawtext, text or target) reference['refuri'] = uri if missing: reference.set_class('missing') return reference return None def trac(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Inserts a `reference` node into the document for a given `TracLink`_, based on the content of the arguments. Usage:: .. trac:: target [text] ``target`` may be any `TracLink`_, provided it doesn't embed a space character (e.g. wiki:"..." notation won't work). ``[text]`` is optional. If not given, ``target`` is used as the reference text. .. _TracLink: http://trac.edgewall.org/wiki/TracLinks """ link = arguments[0] if len(arguments) == 2: text = arguments[1] else: text = None reference = trac_get_reference(block_text, link, text) if reference: p = nodes.paragraph() p += reference return p # didn't find a match (invalid TracLink), # report a warning warning = state_machine.reporter.warning( u'%s n\'est pas un lien Trac correct' % (arguments[0]), nodes.literal_block(block_text, block_text), line=lineno) return [warning] def trac_role(name, rawtext, text, lineno, inliner, options={}, content=[]): args = text.split(" ", 1) link = args[0] if len(args) == 2: text = args[1] else: text = None reference = trac_get_reference(rawtext, link, text) if reference: return [reference], [] warning = nodes.warning( None, nodes.literal_block( text, u'ATTENTION: %s n\'est pas un lien Trac correct' % rawtext)) return warning, [] # 1 required arg, 1 optional arg, spaces allowed in last arg trac.arguments = (1, 1, 1) trac.options = None trac.content = None rst.directives.register_directive('trac', trac) rst.roles.register_local_role('trac', trac_role) # The code_block could is taken from the leo plugin rst2 def code_formatter(language, text): processor = WikiProcessor(self.env, language) html = processor.process(req, text) raw = nodes.raw('', html, format='html') return raw def code_role(name, rawtext, text, lineno, inliner, options={}, content=[]): language = options.get('language') if not language: args = text.split(':', 1) language = args[0] if len(args) == 2: text = args[1] else: text = '' reference = code_formatter(language, text) return [reference], [] def code_block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Create a code-block directive for docutils. Usage: .. code-block:: language If the language can be syntax highlighted it will be. """ language = arguments[0] text = '\n'.join(content) reference = code_formatter(language, text) return [reference] # These are documented # at http://docutils.sourceforge.net/spec/howto/rst-directives.html. code_block.arguments = ( 1, # Number of required arguments. 0, # Number of optional arguments. 0) # True if final argument may contain whitespace. # A mapping from option name to conversion function. code_role.options = code_block.options = { 'language': rst.directives.unchanged # Return the text argument, unchanged } code_block.content = 1 # True if content is allowed. # Register the directive with docutils. rst.directives.register_directive('code-block', code_block) rst.roles.register_local_role('code-block', code_role) _inliner = rst.states.Inliner() _parser = rst.Parser(inliner=_inliner) content = content_to_unicode(self.env, content, mimetype) parts = publish_parts(content, writer_name='html', parser=_parser, settings_overrides={ 'halt_level': 6, 'file_insertion_enabled': 0, 'raw_enabled': 0 }) return parts['html_body']
def render(self, req, mimetype, content, filename=None, rev=None): try: from docutils import nodes from docutils.core import publish_parts from docutils.parsers import rst from docutils import __version__ except ImportError: raise TracError, u'La bibliothèque Docutils est introuvable' if StrictVersion(__version__) < StrictVersion('0.3.9'): raise TracError, u'Une version >= %s de Docutils est requise, la version %s a été détectée' \ % ('0.3.9', __version__) def trac_get_reference(rawtext, target, text): fulltext = text and target+' '+text or target link = wiki_to_link(fulltext, self.env, req) uri = None missing = False if isinstance(link, Element): linktext = Markup(link).striptags() # the following is a bit hackish, but it takes into account: # - an eventual trailing '?' for missing wiki pages # - space eventually introduced due to split_page_names option if linktext.rstrip('?').replace(' ', '') != target: text = linktext uri = link.attr.get('href', '') missing = 'missing' in link.attr.get('class_', '') else: uri = req.href.wiki(target) missing = not WikiSystem(self.env).has_page(target) if uri: reference = nodes.reference(rawtext, text or target) reference['refuri']= uri if missing: reference.set_class('missing') return reference return None def trac(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Inserts a `reference` node into the document for a given `TracLink`_, based on the content of the arguments. Usage:: .. trac:: target [text] ``target`` may be any `TracLink`_, provided it doesn't embed a space character (e.g. wiki:"..." notation won't work). ``[text]`` is optional. If not given, ``target`` is used as the reference text. .. _TracLink: http://trac.edgewall.org/wiki/TracLinks """ link = arguments[0] if len(arguments) == 2: text = arguments[1] else: text = None reference = trac_get_reference(block_text, link, text) if reference: p = nodes.paragraph() p += reference return p # didn't find a match (invalid TracLink), # report a warning warning = state_machine.reporter.warning( u'%s n\'est pas un lien Trac correct' % (arguments[0]), nodes.literal_block(block_text, block_text), line=lineno) return [warning] def trac_role(name, rawtext, text, lineno, inliner, options={}, content=[]): args = text.split(" ",1) link = args[0] if len(args)==2: text = args[1] else: text = None reference = trac_get_reference(rawtext, link, text) if reference: return [reference], [] warning = nodes.warning(None, nodes.literal_block(text, u'ATTENTION: %s n\'est pas un lien Trac correct' % rawtext)) return warning, [] # 1 required arg, 1 optional arg, spaces allowed in last arg trac.arguments = (1,1,1) trac.options = None trac.content = None rst.directives.register_directive('trac', trac) rst.roles.register_local_role('trac', trac_role) # The code_block could is taken from the leo plugin rst2 def code_formatter(language, text): processor = WikiProcessor(self.env, language) html = processor.process(req, text) raw = nodes.raw('', html, format='html') return raw def code_role(name, rawtext, text, lineno, inliner, options={}, content=[]): language = options.get('language') if not language: args = text.split(':', 1) language = args[0] if len(args) == 2: text = args[1] else: text = '' reference = code_formatter(language, text) return [reference], [] def code_block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Create a code-block directive for docutils. Usage: .. code-block:: language If the language can be syntax highlighted it will be. """ language = arguments[0] text = '\n'.join(content) reference = code_formatter(language, text) return [reference] # These are documented # at http://docutils.sourceforge.net/spec/howto/rst-directives.html. code_block.arguments = ( 1, # Number of required arguments. 0, # Number of optional arguments. 0) # True if final argument may contain whitespace. # A mapping from option name to conversion function. code_role.options = code_block.options = { 'language' : rst.directives.unchanged # Return the text argument, unchanged } code_block.content = 1 # True if content is allowed. # Register the directive with docutils. rst.directives.register_directive('code-block', code_block) rst.roles.register_local_role('code-block', code_role) _inliner = rst.states.Inliner() _parser = rst.Parser(inliner=_inliner) content = content_to_unicode(self.env, content, mimetype) parts = publish_parts(content, writer_name='html', parser=_parser, settings_overrides={'halt_level': 6, 'file_insertion_enabled': 0, 'raw_enabled': 0}) return parts['html_body']
def render(self, req, mimetype, content, filename=None, rev=None): """Returns wikicreole text as html""" text = content_to_unicode(self.env, content, mimetype) return render_creole(text)