File: wordwrap.py

package info (click to toggle)
clearsilver 0.10.5-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,304 kB
  • sloc: ansic: 24,586; python: 4,233; sh: 2,502; cs: 1,429; ruby: 819; java: 735; makefile: 589; perl: 120; lisp: 34; sql: 21
file content (50 lines) | stat: -rwxr-xr-x 1,060 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
WordWrapping
"""


import os, sys, string, time, getopt
import re

def WordWrap(text, cols=70, detect_paragraphs = 0, is_header = 0):
  text =  string.replace(text,"\r\n", "\n") # remove CRLF
  def nlrepl(matchobj):
    if matchobj.group(1) != ' ' and matchobj.group(2) != ' ':
      repl_with = ' '
    else:
      repl_with = ''

    return matchobj.group(1) + repl_with + matchobj.group(2)

  if detect_paragraphs:
    text = re.sub("([^\n])\n([^\n])",nlrepl,text)

  body = []
  i = 0
  j = 0
  ltext = len(text)

  while i<ltext:
    if i+cols < ltext:
      r = string.find(text, "\n", i, i+cols)
      j = r
      if r == -1:
        j = string.rfind(text, " ", i, i+cols)
        if j == -1:
          r = string.find(text, "\n", i+cols)
          if r == -1: r = ltext
	  j = string.find(text, " ", i+cols)
	  if j == -1: j = ltext
          j = min(j, r)
    else:
      j = ltext

    body.append(string.strip(text[i:j]))
    i = j+1

  if is_header:
    body = string.join(body, "\n ")
  else:
    body = string.join(body, "\n")
  return body