blob: e3ca7b9b3d4e6380f9904a687c9ecb75fdd997e9 [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001# Extension to format a paragraph
2
3# Does basic, standard text formatting, and also understands Python
4# comment blocks. Thus, for editing Python source code, this
5# extension is really only suitable for reformatting these comment
6# blocks or triple-quoted strings.
7
8# Known problems with comment reformatting:
9# * If there is a selection marked, and the first line of the
10# selection is not complete, the block will probably not be detected
11# as comments, and will have the normal "text formatting" rules
12# applied.
13# * If a comment block has leading whitespace that mixes tabs and
14# spaces, they will not be considered part of the same block.
15# * Fancy comments, like this bulleted list, arent handled :-)
16
David Scherer7aced172000-08-15 01:13:23 +000017import re
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000018from idlelib.configHandler import idleConf
David Scherer7aced172000-08-15 01:13:23 +000019
20class FormatParagraph:
21
22 menudefs = [
23 ('format', [ # /s/edit/format dscherer@cmu.edu
24 ('Format Paragraph', '<<format-paragraph>>'),
25 ])
26 ]
27
David Scherer7aced172000-08-15 01:13:23 +000028 def __init__(self, editwin):
29 self.editwin = editwin
30
31 def close(self):
32 self.editwin = None
33
34 def format_paragraph_event(self, event):
Andrew Svetlov8a495a42012-12-24 13:15:43 +020035 maxformatwidth = int(idleConf.GetOption('main', 'FormatParagraph',
36 'paragraph', type='int'))
David Scherer7aced172000-08-15 01:13:23 +000037 text = self.editwin.text
38 first, last = self.editwin.get_selection_indices()
39 if first and last:
40 data = text.get(first, last)
41 comment_header = ''
42 else:
43 first, last, comment_header, data = \
44 find_paragraph(text, text.index("insert"))
45 if comment_header:
46 # Reformat the comment lines - convert to text sans header.
Kurt B. Kaiser75e37902002-09-16 02:22:19 +000047 lines = data.split("\n")
David Scherer7aced172000-08-15 01:13:23 +000048 lines = map(lambda st, l=len(comment_header): st[l:], lines)
Kurt B. Kaiser75e37902002-09-16 02:22:19 +000049 data = "\n".join(lines)
Andrew Svetlov8a495a42012-12-24 13:15:43 +020050 # Reformat to maxformatwidth chars or a 20 char width,
51 # whichever is greater.
Tim Peters16e3cf52004-10-24 23:45:42 +000052 format_width = max(maxformatwidth - len(comment_header), 20)
David Scherer7aced172000-08-15 01:13:23 +000053 newdata = reformat_paragraph(data, format_width)
54 # re-split and re-insert the comment header.
Kurt B. Kaiser75e37902002-09-16 02:22:19 +000055 newdata = newdata.split("\n")
David Scherer7aced172000-08-15 01:13:23 +000056 # If the block ends in a \n, we dont want the comment
57 # prefix inserted after it. (Im not sure it makes sense to
58 # reformat a comment block that isnt made of complete
Ezio Melotti13925002011-03-16 11:05:33 +020059 # lines, but whatever!) Can't think of a clean solution,
David Scherer7aced172000-08-15 01:13:23 +000060 # so we hack away
61 block_suffix = ""
62 if not newdata[-1]:
63 block_suffix = "\n"
64 newdata = newdata[:-1]
65 builder = lambda item, prefix=comment_header: prefix+item
Kurt B. Kaiser75e37902002-09-16 02:22:19 +000066 newdata = '\n'.join(map(builder, newdata)) + block_suffix
David Scherer7aced172000-08-15 01:13:23 +000067 else:
68 # Just a normal text format
Raymond Hettinger4e49b832004-06-04 06:31:08 +000069 newdata = reformat_paragraph(data, maxformatwidth)
David Scherer7aced172000-08-15 01:13:23 +000070 text.tag_remove("sel", "1.0", "end")
71 if newdata != data:
72 text.mark_set("insert", first)
73 text.undo_block_start()
74 text.delete(first, last)
75 text.insert(first, newdata)
76 text.undo_block_stop()
77 else:
78 text.mark_set("insert", last)
79 text.see("insert")
Christian Heimesb76922a2007-12-11 01:06:40 +000080 return "break"
David Scherer7aced172000-08-15 01:13:23 +000081
82def find_paragraph(text, mark):
Kurt B. Kaiser75e37902002-09-16 02:22:19 +000083 lineno, col = map(int, mark.split("."))
David Scherer7aced172000-08-15 01:13:23 +000084 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
85 while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line):
86 lineno = lineno + 1
87 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
88 first_lineno = lineno
89 comment_header = get_comment_header(line)
90 comment_header_len = len(comment_header)
91 while get_comment_header(line)==comment_header and \
92 not is_all_white(line[comment_header_len:]):
93 lineno = lineno + 1
94 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
95 last = "%d.0" % lineno
96 # Search back to beginning of paragraph
97 lineno = first_lineno - 1
98 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
99 while lineno > 0 and \
100 get_comment_header(line)==comment_header and \
101 not is_all_white(line[comment_header_len:]):
102 lineno = lineno - 1
103 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
104 first = "%d.0" % (lineno+1)
105 return first, last, comment_header, text.get(first, last)
106
Raymond Hettinger4e49b832004-06-04 06:31:08 +0000107def reformat_paragraph(data, limit):
Kurt B. Kaiser75e37902002-09-16 02:22:19 +0000108 lines = data.split("\n")
David Scherer7aced172000-08-15 01:13:23 +0000109 i = 0
110 n = len(lines)
111 while i < n and is_all_white(lines[i]):
112 i = i+1
113 if i >= n:
114 return data
115 indent1 = get_indent(lines[i])
116 if i+1 < n and not is_all_white(lines[i+1]):
117 indent2 = get_indent(lines[i+1])
118 else:
119 indent2 = indent1
120 new = lines[:i]
121 partial = indent1
122 while i < n and not is_all_white(lines[i]):
123 # XXX Should take double space after period (etc.) into account
124 words = re.split("(\s+)", lines[i])
125 for j in range(0, len(words), 2):
126 word = words[j]
127 if not word:
128 continue # Can happen when line ends in whitespace
Kurt B. Kaiser75e37902002-09-16 02:22:19 +0000129 if len((partial + word).expandtabs()) > limit and \
David Scherer7aced172000-08-15 01:13:23 +0000130 partial != indent1:
Kurt B. Kaiser75e37902002-09-16 02:22:19 +0000131 new.append(partial.rstrip())
David Scherer7aced172000-08-15 01:13:23 +0000132 partial = indent2
133 partial = partial + word + " "
134 if j+1 < len(words) and words[j+1] != " ":
135 partial = partial + " "
136 i = i+1
Kurt B. Kaiser75e37902002-09-16 02:22:19 +0000137 new.append(partial.rstrip())
David Scherer7aced172000-08-15 01:13:23 +0000138 # XXX Should reformat remaining paragraphs as well
139 new.extend(lines[i:])
Kurt B. Kaiser75e37902002-09-16 02:22:19 +0000140 return "\n".join(new)
David Scherer7aced172000-08-15 01:13:23 +0000141
142def is_all_white(line):
143 return re.match(r"^\s*$", line) is not None
144
145def get_indent(line):
146 return re.match(r"^(\s*)", line).group()
147
148def get_comment_header(line):
149 m = re.match(r"^(\s*#*)", line)
150 if m is None: return ""
151 return m.group(1)