ztfy/utils/text.py
changeset 32 266139614a46
child 40 16c94c509933
equal deleted inserted replaced
31:f7cd6dbc6dd8 32:266139614a46
       
     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 
       
    26 # import local packages
       
    27 
       
    28 
       
    29 def textStart(text, length, max=0):
       
    30     """Get first words of given text with maximum given length
       
    31     
       
    32     If @max is specified, text is shortened only if remaining text is longer than @max
       
    33     
       
    34     @param text: initial text
       
    35     @param length: maximum length of resulting text
       
    36     @param max: if > 0, @text is shortened only if remaining text is longer than max
       
    37     """
       
    38     result = text or ''
       
    39     if length > len(result):
       
    40         return result
       
    41     index = length - 1
       
    42     text_length = len(result)
       
    43     while (index > 0) and (result[index] != ' '):
       
    44         index -= 1
       
    45     if (index > 0) and (text_length > index + max):
       
    46         return result[:index] + '&#133;'
       
    47     return text