|
1 ### -*- coding: utf-8 -*- #################################################### |
|
2 ############################################################################## |
|
3 # |
|
4 # Copyright (c) 2008-2010 Thierry Florac <tflorac AT ulthar.net> |
|
5 # All Rights Reserved. |
|
6 # |
|
7 # This software is subject to the provisions of the Zope Public License, |
|
8 # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. |
|
9 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED |
|
10 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
|
11 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS |
|
12 # FOR A PARTICULAR PURPOSE. |
|
13 # |
|
14 ############################################################################## |
|
15 |
|
16 __docformat__ = "restructuredtext" |
|
17 |
|
18 # import standard packages |
|
19 |
|
20 # import Zope3 interfaces |
|
21 |
|
22 # import local interfaces |
|
23 |
|
24 # import Zope3 packages |
|
25 from zope.component import createObject, queryMultiAdapter |
|
26 |
|
27 # import local packages |
|
28 from ztfy.utils.request import getRequest |
|
29 |
|
30 |
|
31 def textStart(text, length, max=0): |
|
32 """Get first words of given text with maximum given length |
|
33 |
|
34 If @max is specified, text is shortened only if remaining text is longer than @max |
|
35 |
|
36 @param text: initial text |
|
37 @param length: maximum length of resulting text |
|
38 @param max: if > 0, @text is shortened only if remaining text is longer than max |
|
39 """ |
|
40 result = text or '' |
|
41 if length > len(result): |
|
42 return result |
|
43 index = length - 1 |
|
44 text_length = len(result) |
|
45 while (index > 0) and (result[index] != ' '): |
|
46 index -= 1 |
|
47 if (index > 0) and (text_length > index + max): |
|
48 return result[:index] + '…' |
|
49 return text |
|
50 |
|
51 |
|
52 def textToHTML(text, renderer='zope.source.plaintext', request=None): |
|
53 if request is None: |
|
54 request = getRequest() |
|
55 formatter = createObject(renderer, text) |
|
56 renderer = queryMultiAdapter((formatter, request), name=u'') |
|
57 return renderer.render() |
|
58 |
|
59 |
|
60 class Renderer(object): |
|
61 |
|
62 def __init__(self, context): |
|
63 self.context = context |
|
64 |
|
65 def render(self, renderer, request=None): |
|
66 if not self.context: |
|
67 return u'' |
|
68 return textToHTML(self.context, renderer, request) |