File indexing completed on 2024-12-17 18:40:00 UTC
view on githubraw file Latest commit d775ee35 on 2024-05-14 13:31:51 UTC
8fbfd1f382 Oliv*0001 """ Indentation utilities for Cog.
0002 """
0003
0004 import re
d775ee353a Oliv*0005
8fbfd1f382 Oliv*0006
0007 def whitePrefix(strings):
0008 """ Determine the whitespace prefix common to all non-blank lines
0009 in the argument list.
0010 """
0011
0012 strings = [s for s in strings if s.strip() != '']
0013
0014 if not strings: return ''
0015
0016
0017
0018 pat = r'\s*'
d775ee353a Oliv*0019 if isinstance(strings[0], bytes):
0020 pat = pat.encode("utf-8")
8fbfd1f382 Oliv*0021 prefix = re.match(pat, strings[0]).group(0)
0022
0023
0024
0025 for s in strings:
0026 for i in range(len(prefix)):
0027 if prefix[i] != s[i]:
0028 prefix = prefix[:i]
0029 break
0030 return prefix
0031
0032 def reindentBlock(lines, newIndent=''):
0033 """ Take a block of text as a string or list of lines.
0034 Remove any common whitespace indentation.
0035 Re-indent using newIndent, and return it as a single string.
0036 """
0037 sep, nothing = '\n', ''
d775ee353a Oliv*0038 if isinstance(lines, bytes):
0039 sep, nothing = b'\n', b''
0040 if isinstance(lines, (bytes, str)):
8fbfd1f382 Oliv*0041 lines = lines.split(sep)
0042 oldIndent = whitePrefix(lines)
0043 outLines = []
0044 for l in lines:
0045 if oldIndent:
0046 l = l.replace(oldIndent, nothing, 1)
0047 if l and newIndent:
0048 l = newIndent + l
0049 outLines.append(l)
0050 return sep.join(outLines)
0051
0052 def commonPrefix(strings):
0053 """ Find the longest string that is a prefix of all the strings.
0054 """
0055 if not strings:
0056 return ''
0057 prefix = strings[0]
0058 for s in strings:
0059 if len(s) < len(prefix):
0060 prefix = prefix[:len(s)]
0061 if not prefix:
0062 return ''
0063 for i in range(len(prefix)):
0064 if prefix[i] != s[i]:
0065 prefix = prefix[:i]
0066 break
0067 return prefix