Selfie
Loading...
Searching...
No Matches
EscapeLeadingWhitespace.py
Go to the documentation of this file.
1from enum import Enum, auto
2
3
5 ALWAYS = auto()
6 NEVER = auto()
7 ONLY_ON_SPACE = auto()
8 ONLY_ON_TAB = auto()
9
10 def escape_line(self, line: str, space: str, tab: str) -> str:
11 if line.startswith(" "):
12 if (
13 self == EscapeLeadingWhitespace.ALWAYS
14 or self == EscapeLeadingWhitespace.ONLY_ON_SPACE
15 ):
16 return f"{space}{line[1:]}"
17 else:
18 return line
19 elif line.startswith("\t"):
20 if (
21 self == EscapeLeadingWhitespace.ALWAYS
22 or self == EscapeLeadingWhitespace.ONLY_ON_TAB
23 ):
24 return f"{tab}{line[1:]}"
25 else:
26 return line
27 else:
28 return line
29
30 @classmethod
31 def appropriate_for(cls, file_content: str) -> "EscapeLeadingWhitespace":
32 MIXED = "m"
33 common_whitespace = None
34
35 for line in file_content.splitlines():
36 whitespace = "".join(c for c in line if c.isspace())
37 if not whitespace:
38 continue
39 elif all(c == " " for c in whitespace):
40 whitespace = " "
41 elif all(c == "\t" for c in whitespace):
42 whitespace = "\t"
43 else:
44 whitespace = MIXED
45
46 if common_whitespace is None:
47 common_whitespace = whitespace
48 elif common_whitespace != whitespace:
49 common_whitespace = MIXED
50 break
51
52 if common_whitespace == " ":
53 return cls.ONLY_ON_TAB
54 elif common_whitespace == "\t":
55 return cls.ONLY_ON_SPACE
56 else:
57 return cls.ALWAYS
"EscapeLeadingWhitespace" appropriate_for(cls, str file_content)