xsl-list
[Top] [All Lists]

Re: [xsl] Line break algorithm

2020-05-03 08:04:12
Hi Rick,

I pulled this function using regular expressions (assuming there are no inline 
elements present) from some past project (no XSLT 3, sorry):

  <!--
    try to break a string at the latest space character before the defined width
    returns a sequence of strings
  -->
  <xsl:function name="dy:wrapTextToLines" as="xs:string+">
    <xsl:param name="text" as="xs:string" />
    <xsl:param name="width" as="xs:integer" />
    <xsl:choose>
      <xsl:when test="normalize-space($text) = ''">
        <!-- return empty string -->
        <xsl:value-of select="''"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:variable name="cleaned" select="mormalize-space($text)"/>
        <xsl:variable name="wrapped" select="
          replace(concat($cleaned,' '),
          concat('(.{0,', $width, '}) '), concat('$1', $gLF))"/>
        <xsl:sequence select="tokenize(replace($wrapped, concat($gLF, '$'), 
''), $gLF)"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:function>

It works by adding a space to the end and then using a regular expression to 
select up to the max characters followed by a space. Since regexes are greedy 
by default, it will try to capture as many words as possible within the given 
limit. 

In my situation $gLF was a linefeed character, and in the last line I removed 
the closing LF before tokenizing the result.

HTH,

- Michael

PS: Always nice remembering our FrameMaker times…



Am 03.05.2020 um 02:45 schrieb Rick Quatro rick(_at_)rickquatro(_dot_)com 
<mailto:rick(_at_)rickquatro(_dot_)com> 
<xsl-list-service(_at_)lists(_dot_)mulberrytech(_dot_)com 
<mailto:xsl-list-service(_at_)lists(_dot_)mulberrytech(_dot_)com>>:

Hi All, 
 
I have lines in my input that I want to add <break> elements to in my output. 
For example, this might be the input:
 
<xsl:param name="line" select="'Takeoff from Unlisted and Alternate 
Airports'"/>
 
and I want to replace a space with a <break> so that each line doesn't 
exceed, for example, 35 characters
 
<line>Takeoff from Unlisted and Alternate<break/>Airports</line>
 
I am thinking the I can tokenize the line and then recursively build the 
string back up from the beginning, checking its length. Any other suggestions 
on a general-purpose algorithm that I can use in XSLT 3 would be appreciated. 
Thanks in advance.
 
Rick
--~----------------------------------------------------------------
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
EasyUnsubscribe: http://lists.mulberrytech.com/unsub/xsl-list/1167547
or by email: xsl-list-unsub(_at_)lists(_dot_)mulberrytech(_dot_)com
--~--
<Prev in Thread] Current Thread [Next in Thread>