当前位置: 首页>>代码示例>>Python>>正文


Python text.wrap函数代码示例

本文整理汇总了Python中trac.util.text.wrap函数的典型用法代码示例。如果您正苦于以下问题:Python wrap函数的具体用法?Python wrap怎么用?Python wrap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了wrap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _format_html

    def _format_html(self, event):
        ticket = event.target
        short_changes = {}
        long_changes = {}
        chrome = Chrome(self.env)        
        for field, old_value in event.changes.items():
            new_value = ticket[field]
            if (new_value and '\n' in new_value) or \
                    (old_value and '\n' in old_value):
                long_changes[field.capitalize()] = HTML(
                    "<pre>\n%s\n</pre>" % (
                        '\n'.join(
                            diff_cleanup(
                                difflib.unified_diff(
                                    wrap(old_value, cols=60).split('\n'), 
                                    wrap(new_value, cols=60).split('\n'),
                                    lineterm='', n=3
                                )
                            )
                        )
                    )
                )

            else:
                short_changes[field.capitalize()] = (old_value, new_value)
        data = dict(
            ticket = ticket,
            author = event.author,
            header = self._header_fields(ticket),
            comment = event.comment,
            category = event.category,
            ticket_link = self.env.abs_href('ticket', ticket.id),
            project_name = self.env.project_name,
            project_desc = self.env.project_description,
            project_link = self.env.project_url or self.env.abs_href(),
            has_changes = short_changes or long_changes,
            long_changes = long_changes,
            short_changes = short_changes,
            attachment= event.attachment
        )
        chrome = Chrome(self.env)
        dirs = []
        for provider in chrome.template_providers:
            dirs += provider.get_templates_dirs()
        templates = TemplateLoader(dirs, variable_lookup='lenient')
        template = templates.load('ticket_email_mimic.html', 
                cls=MarkupTemplate)
        if template:
            stream = template.generate(**data)
            output = stream.render()
        return output
开发者ID:lkraav,项目名称:trachacks,代码行数:51,代码来源:ticket_email.py

示例2: _format_html

    def _format_html(self, event):
        ticket = event.target
        attachment = event.attachment
        short_changes = {}
        long_changes = {}
        chrome = Chrome(self.env)
        for field, old_value in event.changes.items():
            new_value = ticket[field]
            if (new_value and '\n' in new_value) or \
                    (old_value and '\n' in old_value):
                long_changes[field.capitalize()] = HTML(
                    "<pre>\n%s\n</pre>" % (
                        '\n'.join(
                            diff_cleanup(
                                difflib.unified_diff(
                                    wrap(old_value, cols=60).split('\n'),
                                    wrap(new_value, cols=60).split('\n'),
                                    lineterm='', n=3
                                )
                            )
                        )
                    )
                )

            else:
                short_changes[field.capitalize()] = (old_value, new_value)

        def wiki_to_html(event, wikitext):
            if wikitext is None:
                return ""
            try:
                req = Mock(
                    href=Href(self.env.abs_href()),
                    abs_href=self.env.abs_href,
                    authname=event.author,
                    perm=MockPerm(),
                    chrome=dict(
                        warnings=[],
                        notices=[]
                    ),
                    args={}
                )
                context = Context.from_request(req, event.realm, event.target.id)
                formatter = HtmlFormatter(self.env, context, wikitext)
                return formatter.generate(True)
            except Exception, e:
                raise
                self.log.error("Failed to render %s", repr(wikitext))
                self.log.error(exception_to_unicode(e, traceback=True))
                return wikitext
开发者ID:lkraav,项目名称:trachacks,代码行数:50,代码来源:formatters.py

示例3: _format_html

    def _format_html(self, event):
        ticket = event.target
        short_changes = {}
        long_changes = {}
        chrome = Chrome(self.env)        
        for field, old_value in event.changes.items():
            new_value = ticket[field]
            if (new_value and '\n' in new_value) or \
                    (old_value and '\n' in old_value):
                long_changes[field.capitalize()] = HTML(
                    "<pre>\n%s\n</pre>" % (
                        '\n'.join(
                            diff_cleanup(
                                difflib.unified_diff(
                                    wrap(old_value, cols=60).split('\n'), 
                                    wrap(new_value, cols=60).split('\n'),
                                    lineterm='', n=3
                                )
                            )
                        )
                    )
                )

            else:
                short_changes[field.capitalize()] = (old_value, new_value)

        if event.comment:
            try:
                req = Mock(
                    href=Href(self.env.abs_href()),
                    abs_href=self.env.abs_href(),
                    authname=event.author, 
                    perm=MockPerm(),
                    chrome=dict(
                        warnings=[],
                        notices=[]
                    ),
                    args={}
                )
                context = Context.from_request(req, event.realm, event.target.id)
                formatter = HtmlFormatter(self.env, context, event.comment)
                temp = formatter.generate(True)
            except Exception, e:
                self.log.error(exception_to_unicode(e, traceback=True))
                temp = 'Comment in plain text: %s'%event.comment
开发者ID:lkraav,项目名称:trachacks,代码行数:45,代码来源:ticket_email.py

示例4: notify_attachment

    def notify_attachment(self, ticket, attachment, added=True):
        """Send ticket attachment notification (untranslated)"""
        self.ticket = ticket
        self.modtime = attachment.date or datetime.now(utc)
        self.newticket = False
        self.reporter = ''
        self.owner = ''
        link = self.env.abs_href.ticket(ticket.id)
        summary = self.ticket['summary']
        author = attachment.author

        # Note: no translation yet
        changes_body = wrap(" * Attachment \"%s\" %s."
                            % (attachment.filename,
                               "added" if added else "removed"),
                            self.COLS, ' ', ' ', '\n',
                            self.ambiwidth) + "\n"
        if attachment.description:
            changes_body += "\n" + wrap(attachment.description, self.COLS,
                                        ' ', ' ', '\n', self.ambiwidth)

        ticket_values = ticket.values.copy()
        ticket_values['id'] = ticket.id
        ticket_values['description'] = wrap(
            ticket_values.get('description', ''), self.COLS,
            initial_indent=' ', subsequent_indent=' ', linesep='\n',
            ambiwidth=self.ambiwidth)
        ticket_values['new'] = self.newticket
        ticket_values['link'] = link
        subject = self.format_subj(summary, False)
        with _translation_deactivated(ticket):
            self.data.update({
                'ticket_props': self.format_props(),
                'ticket_body_hdr': self.format_hdr(),
                'subject': subject,
                'ticket': ticket_values,
                'changes_body': changes_body,
                'changes_descr': '',
                'change': {'author': self.obfuscate_email(author)},
            })
            super(TicketNotifyEmail, self).notify(ticket.id, subject, author)
开发者ID:exocad,项目名称:exotrac,代码行数:41,代码来源:notification.py

示例5: test_wrap_ambiwidth_double

    def test_wrap_ambiwidth_double(self):
        text = u'Trac は BSD ライセンスのもとで配布されて' + \
               u'います。[1:]このライセンスの全文は、𠀋' + \
               u'配布ファイルに含まれている[3:CОPYING]ファ' + \
               u'イルと同じものが[2:オンライン]で参照でき' \
               u'ます。'
        wrapped = u"""\
> Trac は BSD ライセンスのもとで配布されています。[1:]この
| ライセンスの全文は、𠀋配布ファイルに含まれている
| [3:CОPYING]ファイルと同じものが[2:オンライン]で参照でき
| ます。"""
        self.assertEqual(wrapped, wrap(text, 59, '> ', '| ', '\n',
                                       ambiwidth=2))
开发者ID:thimalk,项目名称:bloodhound,代码行数:13,代码来源:text.py

示例6: notify_attachment

    def notify_attachment(self, ticket, author, filename, modtime, body):
        """Send ticket attachment notification (untranslated)"""
        t = deactivate()
        translated_fields = ticket.fields
        try:
            ticket.fields = TicketSystem(self.env).get_ticket_fields()

            self.ticket = ticket
            self.modtime = modtime
            self.newticket = False
            self.reporter = ''
            self.owner = ''

            link = self.env.abs_href.ticket(ticket.id)
            summary = self.ticket['summary']
            ticket_values = ticket.values.copy()
            ticket_values['id'] = ticket.id

            wrap_kargs = {
                'initial_indent': ' ',
                'subsequent_indent': ' ',
                'linesep': CRLF
            }
            if 'ambiwidth' in getargspec(wrap)[0]:
                wrap_kargs['ambiwidth'] = self.ambiwidth

            ticket_values['description'] = wrap(
                ticket_values.get('description', ''),
                self.COLS,
                **wrap_kargs
            )

            ticket_values['new'] = self.newticket
            ticket_values['link'] = link
            subject = 'Re: ' + self.format_subj(summary)
            author = obfuscate_email_address(author)
            change = { 'author': author }

            self.data.update({
                'ticket_props': self.format_props(),
                'ticket_body_hdr': self.format_hdr(),
                'subject': subject,
                'ticket': ticket_values,
                'change': change,
                'changes_body': body,
                })

            NotifyEmail.notify(self, ticket.id, subject)
        finally:
            ticket.fields = translated_fields
            reactivate(t)
开发者ID:Gasol,项目名称:trac-attachment-notify-plugin,代码行数:51,代码来源:notify.py

示例7: test_wrap_ambiwidth_double

    def test_wrap_ambiwidth_double(self):
        text = (
            u"Trac は BSD ライセンスのもとで配布されて"
            + u"います。[1:]このライセンスの全文は、𠀋"
            + u"配布ファイルに含まれている[3:CОPYING]ファ"
            + u"イルと同じものが[2:オンライン]で参照でき"
            u"ます。"
        )
        wrapped = u"""\
> Trac は BSD ライセンスのもとで配布されています。[1:]この
| ライセンスの全文は、𠀋配布ファイルに含まれている
| [3:CОPYING]ファイルと同じものが[2:オンライン]で参照でき
| ます。"""
        self.assertEqual(wrapped, wrap(text, 59, "> ", "| ", "\n", ambiwidth=2))
开发者ID:rvelezc,项目名称:rafaelvelez.us-backup,代码行数:14,代码来源:text.py

示例8: expand_macro

 def expand_macro(self, formatter, name, args):
     text = ''
     if args:
         lines = args.split('\n')
         if lines[0].startswith('cols:'):
             try:
                 width = int(lines[0][5:].strip())
                 lines.pop(0)
             except ValueError:
                 width = 72
         else:
             width = 72
         text = wrap('\n'.join(lines), cols=width)
     return '<pre class="wiki">%s</pre>' % escape(text)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:EmailProcessor.py

示例9: render_macro

 def render_macro(self, req, name, content):
     text = ""
     if content:
         lines = content.split("\n")
         if lines[0].startswith("cols:"):
             try:
                 width = int(lines[0][5:].strip())
                 lines.pop(0)
             except ValueError:
                 width = 72
         else:
             width = 72
         text = wrap("\n".join(lines), cols=width)
     return Markup("<pre class='wiki'>%s</pre>" % escape(text))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:EmailProcessor.py

示例10: _do_list

 def _do_list(self, user=None):
     permsys = PermissionSystem(self.env)
     if user:
         rows = []
         perms = permsys.get_user_permissions(user)
         for action in perms:
             if perms[action]:
                 rows.append((user, action))
     else:
         rows = permsys.get_all_permissions()
     rows.sort()
     print_table(rows, [_('User'), _('Action')])
     print
     printout(_("Available actions:"))
     actions = permsys.get_actions()
     actions.sort()
     text = ', '.join(actions)
     printout(wrap(text, initial_indent=' ', subsequent_indent=' ', 
                   linesep='\n'))
     print
开发者ID:zjj,项目名称:trac_hack,代码行数:20,代码来源:perm.py

示例11: test_wrap_ambiwidth_single

    def test_wrap_ambiwidth_single(self):
        text = u'Lorem ipsum dolor sit amet, consectetur adipisicing ' + \
               u'elit, sed do eiusmod tempor incididunt ut labore et ' + \
               u'dolore magna aliqua. Ut enim ad minim veniam, quis ' + \
               u'nostrud exercitation ullamco laboris nisi ut aliquip ex ' + \
               u'ea commodo consequat. Duis aute irure dolor in ' + \
               u'reprehenderit in voluptate velit esse cillum dolore eu ' + \
               u'fugiat nulla pariatur. Excepteur sint occaecat ' + \
               u'cupidatat non proident, sunt in culpa qui officia ' + \
               u'deserunt mollit anim id est laborum.'
        wrapped = u"""\
> Lorem ipsum dolor sit amet, consectetur adipisicing elit,
| sed do eiusmod tempor incididunt ut labore et dolore
| magna aliqua. Ut enim ad minim veniam, quis nostrud
| exercitation ullamco laboris nisi ut aliquip ex ea
| commodo consequat. Duis aute irure dolor in reprehenderit
| in voluptate velit esse cillum dolore eu fugiat nulla
| pariatur. Excepteur sint occaecat cupidatat non proident,
| sunt in culpa qui officia deserunt mollit anim id est
| laborum."""
        self.assertEqual(wrapped, wrap(text, 59, '> ', '| ', '\n'))
开发者ID:thimalk,项目名称:bloodhound,代码行数:21,代码来源:text.py

示例12: _format_plaintext

    def _format_plaintext(self, event):
        ticket = event.target
        short_changes = {}
        long_changes = {}
        changed_items = [(field, to_unicode(old_value)) for \
                field, old_value in event.changes.items()]
        for field, old_value in changed_items:
            new_value = to_unicode(ticket[field])
            if ('\n' in new_value) or ('\n' in old_value):
                long_changes[field.capitalize()] = '\n'.join(
                    lineup(wrap(new_value, cols=67).split('\n')))
            else:
                short_changes[field.capitalize()] = (old_value, new_value)

        data = dict(
            ticket = ticket,
            author = event.author,
            comment = event.comment,
            fields = self._header_fields(ticket),
            category = event.category,
            ticket_link = self._ticket_link(ticket),
            project_name = self.env.project_name,
            project_desc = self.env.project_description,
            project_link = self.env.project_url or self.env.abs_href(),
            has_changes = short_changes or long_changes,
            long_changes = long_changes,
            short_changes = short_changes,
            attachment= event.attachment
        )
        chrome = Chrome(self.env)        
        dirs = []
        for provider in chrome.template_providers:
            dirs += provider.get_templates_dirs()
        templates = TemplateLoader(dirs, variable_lookup='lenient')
        template = templates.load('ticket_email_plaintext.txt', 
                cls=NewTextTemplate)
        if template:
            stream = template.generate(**data)
            output = stream.render('text')
        return output
开发者ID:lkraav,项目名称:trachacks,代码行数:40,代码来源:ticket.py

示例13: test_wrap_ambiwidth_single

    def test_wrap_ambiwidth_single(self):
        text = (
            u"Lorem ipsum dolor sit amet, consectetur adipisicing "
            + u"elit, sed do eiusmod tempor incididunt ut labore et "
            + u"dolore magna aliqua. Ut enim ad minim veniam, quis "
            + u"nostrud exercitation ullamco laboris nisi ut aliquip ex "
            + u"ea commodo consequat. Duis aute irure dolor in "
            + u"reprehenderit in voluptate velit esse cillum dolore eu "
            + u"fugiat nulla pariatur. Excepteur sint occaecat "
            + u"cupidatat non proident, sunt in culpa qui officia "
            + u"deserunt mollit anim id est laborum."
        )
        wrapped = u"""\
> Lorem ipsum dolor sit amet, consectetur adipisicing elit,
| sed do eiusmod tempor incididunt ut labore et dolore
| magna aliqua. Ut enim ad minim veniam, quis nostrud
| exercitation ullamco laboris nisi ut aliquip ex ea
| commodo consequat. Duis aute irure dolor in reprehenderit
| in voluptate velit esse cillum dolore eu fugiat nulla
| pariatur. Excepteur sint occaecat cupidatat non proident,
| sunt in culpa qui officia deserunt mollit anim id est
| laborum."""
        self.assertEqual(wrapped, wrap(text, 59, "> ", "| ", "\n"))
开发者ID:rvelezc,项目名称:rafaelvelez.us-backup,代码行数:23,代码来源:text.py

示例14: format_hdr

 def format_hdr(self):
     return "#%s: %s" % (self.ticket.id, wrap(self.ticket["summary"], self.COLS, linesep=CRLF))
开发者ID:wiraqutra,项目名称:photrackjp,代码行数:2,代码来源:notification.py

示例15: _notify

    def _notify(self, ticket, newticket=True, modtime=None):
        self.ticket = ticket
        self.modtime = modtime
        self.newticket = newticket

        changes_body = ""
        self.reporter = ""
        self.owner = ""
        changes_descr = ""
        change_data = {}
        link = self.env.abs_href.ticket(ticket.id)
        summary = self.ticket["summary"]

        if not self.newticket and modtime:  # Ticket change
            from trac.ticket.web_ui import TicketModule

            for change in TicketModule(self.env).grouped_changelog_entries(ticket, self.db, when=modtime):
                if not change["permanent"]:  # attachment with same time...
                    continue
                change_data.update(
                    {
                        "author": obfuscate_email_address(change["author"]),
                        "comment": wrap(change["comment"], self.COLS, " ", " ", CRLF),
                    }
                )
                link += "#comment:%s" % str(change.get("cnum", ""))
                for field, values in change["fields"].iteritems():
                    old = values["old"]
                    new = values["new"]
                    newv = ""
                    if field == "description":
                        new_descr = wrap(new, self.COLS, " ", " ", CRLF)
                        old_descr = wrap(old, self.COLS, "> ", "> ", CRLF)
                        old_descr = old_descr.replace(2 * CRLF, CRLF + ">" + CRLF)
                        cdescr = CRLF
                        cdescr += "Old description:" + 2 * CRLF + old_descr + 2 * CRLF
                        cdescr += "New description:" + 2 * CRLF + new_descr + CRLF
                        changes_descr = cdescr
                    elif field == "summary":
                        summary = "%s (was: %s)" % (new, old)
                    elif field == "cc":
                        (addcc, delcc) = self.diff_cc(old, new)
                        chgcc = ""
                        if delcc:
                            chgcc += wrap(" * cc: %s (removed)" % ", ".join(delcc), self.COLS, " ", " ", CRLF) + CRLF
                        if addcc:
                            chgcc += wrap(" * cc: %s (added)" % ", ".join(addcc), self.COLS, " ", " ", CRLF) + CRLF
                        if chgcc:
                            changes_body += chgcc
                        self.prev_cc += old and self.parse_cc(old) or []
                    else:
                        if field in ["owner", "reporter"]:
                            old = obfuscate_email_address(old)
                            new = obfuscate_email_address(new)
                        newv = new
                        length = 7 + len(field)
                        spacer_old, spacer_new = " ", " "
                        if len(old + new) + length > self.COLS:
                            length = 5
                            if len(old) + length > self.COLS:
                                spacer_old = CRLF
                            if len(new) + length > self.COLS:
                                spacer_new = CRLF
                        chg = "* %s: %s%s%s=>%s%s" % (field, spacer_old, old, spacer_old, spacer_new, new)
                        chg = chg.replace(CRLF, CRLF + length * " ")
                        chg = wrap(chg, self.COLS, "", length * " ", CRLF)
                        changes_body += " %s%s" % (chg, CRLF)
                    if newv:
                        change_data[field] = {"oldvalue": old, "newvalue": new}

        ticket_values = ticket.values.copy()
        ticket_values["id"] = ticket.id
        ticket_values["description"] = wrap(
            ticket_values.get("description", ""), self.COLS, initial_indent=" ", subsequent_indent=" ", linesep=CRLF
        )
        ticket_values["new"] = self.newticket
        ticket_values["link"] = link

        subject = self.format_subj(summary)
        if not self.newticket:
            subject = "Re: " + subject
        self.data.update(
            {
                "ticket_props": self.format_props(),
                "ticket_body_hdr": self.format_hdr(),
                "subject": subject,
                "ticket": ticket_values,
                "changes_body": changes_body,
                "changes_descr": changes_descr,
                "change": change_data,
            }
        )
        NotifyEmail.notify(self, ticket.id, subject)
开发者ID:wiraqutra,项目名称:photrackjp,代码行数:93,代码来源:notification.py


注:本文中的trac.util.text.wrap函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。