1"""
2WordWrapping
3"""
4
5
6import os, sys, string, time, getopt
7import re
8
9def WordWrap(text, cols=70, detect_paragraphs = 0, is_header = 0):
10  text =  string.replace(text,"\r\n", "\n") # remove CRLF
11  def nlrepl(matchobj):
12    if matchobj.group(1) != ' ' and matchobj.group(2) != ' ':
13      repl_with = ' '
14    else:
15      repl_with = ''
16
17    return matchobj.group(1) + repl_with + matchobj.group(2)
18
19  if detect_paragraphs:
20    text = re.sub("([^\n])\n([^\n])",nlrepl,text)
21
22  body = []
23  i = 0
24  j = 0
25  ltext = len(text)
26
27  while i<ltext:
28    if i+cols < ltext:
29      r = string.find(text, "\n", i, i+cols)
30      j = r
31      if r == -1:
32        j = string.rfind(text, " ", i, i+cols)
33        if j == -1:
34          r = string.find(text, "\n", i+cols)
35          if r == -1: r = ltext
36	  j = string.find(text, " ", i+cols)
37	  if j == -1: j = ltext
38          j = min(j, r)
39    else:
40      j = ltext
41
42    body.append(string.strip(text[i:j]))
43    i = j+1
44
45  if is_header:
46    body = string.join(body, "\n ")
47  else:
48    body = string.join(body, "\n")
49  return body
50
51