Coverage for cogapp/whiteutils.py : 88.61%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1""" Indentation utilities for Cog.
2 http://nedbatchelder.com/code/cog
4 Copyright 2004-2019, Ned Batchelder.
5"""
7from __future__ import absolute_import
9import re
11from .backward import string_types, bytes_types, to_bytes
13def whitePrefix(strings):
14 """ Determine the whitespace prefix common to all non-blank lines
15 in the argument list.
16 """
17 # Remove all blank lines from the list
18 strings = [s for s in strings if s.strip() != '']
20 if not strings: return ''
22 # Find initial whitespace chunk in the first line.
23 # This is the best prefix we can hope for.
24 pat = r'\s*'
25 if isinstance(strings[0], bytes_types): 25 ↛ 26line 25 didn't jump to line 26, because the condition on line 25 was never true
26 pat = to_bytes(pat)
27 prefix = re.match(pat, strings[0]).group(0)
29 # Loop over the other strings, keeping only as much of
30 # the prefix as matches each string.
31 for s in strings:
32 for i in range(len(prefix)):
33 if prefix[i] != s[i]: 33 ↛ 34line 33 didn't jump to line 34, because the condition on line 33 was never true
34 prefix = prefix[:i]
35 break
36 return prefix
38def reindentBlock(lines, newIndent=''):
39 """ Take a block of text as a string or list of lines.
40 Remove any common whitespace indentation.
41 Re-indent using newIndent, and return it as a single string.
42 """
43 sep, nothing = '\n', ''
44 if isinstance(lines, bytes_types): 44 ↛ 45line 44 didn't jump to line 45, because the condition on line 44 was never true
45 sep, nothing = b'\n', b''
46 if isinstance(lines, string_types):
47 lines = lines.split(sep)
48 oldIndent = whitePrefix(lines)
49 outLines = []
50 for l in lines:
51 if oldIndent:
52 l = l.replace(oldIndent, nothing, 1)
53 if l and newIndent:
54 l = newIndent + l
55 outLines.append(l)
56 return sep.join(outLines)
58def commonPrefix(strings):
59 """ Find the longest string that is a prefix of all the strings.
60 """
61 if not strings: 61 ↛ 62line 61 didn't jump to line 62, because the condition on line 61 was never true
62 return ''
63 prefix = strings[0]
64 for s in strings:
65 if len(s) < len(prefix):
66 prefix = prefix[:len(s)]
67 if not prefix:
68 return ''
69 for i in range(len(prefix)):
70 if prefix[i] != s[i]:
71 prefix = prefix[:i]
72 break
73 return prefix