Coverage for src/renaissance/utils/text_utils.py: 65%

74 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-16 16:04 +0000

1# Copyright (C) 2024-2026 TNO 

2# 

3# Licensed under the terms specified in the LICENSE file in the root directory 

4# of this repository, also available at: 

5# https://github.com/TNO/Renaissance.Py/blob/main/LICENSE 

6 

7"""AI: Text manipulation utilities for shifting, indenting, and clipboard operations on source text.""" 

8 

9import re 

10from pathlib import Path 

11 

12import pyperclip 

13 

14 

15class TextUtils: 

16 """AI: Text manipulation utilities for shifting, indenting, and clipboard operations on source text.""" 

17 

18 __PRECEDING_SPACES_PATTERN = re.compile(r"([\t\s]*)") 

19 

20 @staticmethod 

21 def shift_left(text: str, shift: int, start_line: int = 0) -> str: 

22 """Shifts each line of the given text to the left by the specified number of spaces. Only spaces are shifted.""" 

23 # TODO(FrancescoPezzella): every line is shifted, also inside a multi-line string literal, changing its value. 

24 # https://github.com/TNO/Renaissance.Py/issues/283 

25 if shift == 0: 

26 return text 

27 pattern = re.compile(r"\s{0," + str(shift) + "}(.*)") 

28 lines = text.split("\n") 

29 for idx, line in enumerate(lines[start_line:]): 

30 lines[idx + start_line] = pattern.sub(r"\1", line) 

31 return "\n".join(lines) 

32 

33 @staticmethod 

34 def correct_indent(text: str, indent: int, depth: int = 0) -> str: 

35 """Shifts each line of the given text to the left by the specified number of spaces. Only spaces are shifted.""" 

36 lines = text.split("\n") 

37 for idx, line in enumerate(lines): 

38 depth -= line.count("}") 

39 stripped = re.sub(r"^\s*", "", line) 

40 lines[idx] = " " * depth * indent + stripped if stripped else stripped 

41 depth += line.count("{") 

42 

43 return "\n".join(lines) 

44 

45 @staticmethod 

46 def strip_indent(text: str, start_line: int = 0) -> str: 

47 """Shift the text left so the first line has no leading spaces. 

48 

49 All other lines are shifted left by the same amount. 

50 """ 

51 matcher = TextUtils.__PRECEDING_SPACES_PATTERN.search(text) 

52 if matcher: 

53 spaces = matcher[1] 

54 text = TextUtils.shift_left(text, len(spaces), start_line) 

55 return text.strip() 

56 

57 @staticmethod 

58 def shift_right(text: str, shift: int, start_line: int = 0) -> str: 

59 """Shifts each line of the given text to the right by the specified number of spaces.""" 

60 # TODO(FrancescoPezzella): every line is shifted, also inside a multi-line string literal, changing its value. 

61 # https://github.com/TNO/Renaissance.Py/issues/283 

62 if shift == 0: 

63 return text 

64 lines = text.split("\n") 

65 spaces = " " * shift 

66 for idx, line in enumerate(lines[start_line:]): 

67 lines[idx + start_line] = spaces + line if line else line 

68 return "\n".join(lines) 

69 

70 @staticmethod 

71 def get_indent(content: bytes, offset: int) -> int: 

72 """Calculate the indentation level of a line in a byte string. 

73 

74 Args: 

75 content (bytes): The byte string containing the text. 

76 offset (int): The position within the byte string to start calculating the indentation from. 

77 

78 Returns: 

79 int: The number of leading whitespace characters (tabs or spaces) from the start of the line to the given offset. 

80 

81 """ 

82 indent = offset 

83 while indent > 1: 

84 if content[indent - 1] in b"\n\r": 

85 break 

86 indent -= 1 

87 start_of_line = indent 

88 while indent < offset: 

89 if content[indent] not in b"\t ": 

90 break 

91 indent += 1 

92 return indent - start_of_line 

93 

94 @staticmethod 

95 def get_spaces_before(content: bytes, offset: int) -> int: 

96 """Calculate the indentation level of a line in a byte string. 

97 

98 Args: 

99 content (bytes): The byte string containing the text. 

100 offset (int): The position within the byte string to start calculating the indentation from. 

101 

102 Returns: 

103 int: The number of leading whitespace characters (tabs or spaces) from the start of the line to the given offset. 

104 

105 """ 

106 indent = offset - 1 

107 while indent > 0: 

108 if content[indent] not in b" \t": 

109 break 

110 indent -= 1 

111 return offset - indent - 1 

112 

113 @staticmethod 

114 def to_clipboard(text: str) -> None: 

115 """AI: Copy the given text to the system clipboard.""" 

116 pyperclip.copy(text) 

117 

118 @staticmethod 

119 def to_file(filename: str, text: str) -> None: 

120 """Write the given text to a file with the specified filename.""" 

121 with Path(filename).open("w") as f: 

122 f.write(text) 

123 

124 

125def signature_to_id(signature: str) -> str: 

126 """AI: Derive a short, filesystem/identifier-safe id from a node signature.""" 

127 text = signature.replace("\n", " ") 

128 return re.sub(r"[^\w\s]", "", text)[:30] # Remove punctuation, limit length 

129 

130 

131def snake_case(snippet: str) -> str: 

132 """Convert a camelCase or PascalCase string to snake_case, preserving acronyms as single words. 

133 

134 Leaves a string already in snake_case unchanged. 

135 """ 

136 snippet = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", snippet) 

137 snippet = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", snippet) 

138 return snippet.lower()