Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8234dfc

Browse files
committed
New version by Tim Peters improves block opening test.
1 parent 116b31b commit 8234dfc

1 file changed

Lines changed: 52 additions & 2 deletions

File tree

Tools/idle/AutoIndent.py

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
###$ unix <Alt-Key-6>
4040

4141
import re
42-
_is_block_opener = re.compile(r":\s*(#.*)?$").search
4342
_is_block_closer = re.compile(r"""
4443
\s*
4544
( return
@@ -50,6 +49,9 @@
5049
)
5150
\b
5251
""", re.VERBOSE).match
52+
53+
# colon followed by optional comment
54+
_looks_like_opener = re.compile(r":\s*(#.*)?$").search
5355
del re
5456

5557
class AutoIndent:
@@ -136,7 +138,7 @@ def set_indentation_params(self, ispythonsource, guess=1):
136138

137139
if guess and ispythonsource:
138140
i = self.guess_indent()
139-
import sys
141+
##import sys
140142
##sys.__stdout__.write("indent %d\n" % i)
141143
if 2 <= i <= 8:
142144
self.indentwidth = i
@@ -423,6 +425,54 @@ def classifyws(s, tabwidth):
423425
break
424426
return raw, effective
425427

428+
# Return true iff line probably opens a block. This is a limited
429+
# analysis based on whether the line's last "interesting" character
430+
# is a colon.
431+
432+
def _is_block_opener(line):
433+
if not _looks_like_opener(line):
434+
return 0
435+
# Looks like an opener, but possible we're in a comment
436+
# x = 3 # and then:
437+
# or a string
438+
# x = ":#"
439+
# If no comment character, we're not in a comment <duh>, and the
440+
# colon is the last non-ws char on the line so it's not in a
441+
# (single-line) string either.
442+
if string.find(line, '#') < 0:
443+
return 1
444+
# Now it's hard: There's a colon and a comment char. Brute force
445+
# approximation.
446+
lastch, i, n = 0, 0, len(line)
447+
while i < n:
448+
ch = line[i]
449+
if ch == '\\':
450+
lastch = ch
451+
i = i+2
452+
elif ch in "\"'":
453+
# consume string
454+
w = 1 # width of string quote
455+
if line[i:i+3] in ('"""', "'''"):
456+
w = 3
457+
ch = ch * 3
458+
i = i+w
459+
while i < n:
460+
if line[i] == '\\':
461+
i = i+2
462+
elif line[i:i+w] == ch:
463+
i = i+w
464+
break
465+
else:
466+
i = i+1
467+
lastch = ch
468+
elif ch == '#':
469+
break
470+
else:
471+
if ch not in string.whitespace:
472+
lastch = ch
473+
i = i+1
474+
return lastch == ':'
475+
426476
import tokenize
427477
_tokenize = tokenize
428478
del tokenize

0 commit comments

Comments
 (0)