diff --git a/app/search/search_utils.py b/app/search/search_utils.py index c648e7a9..64324657 100644 --- a/app/search/search_utils.py +++ b/app/search/search_utils.py @@ -233,36 +233,18 @@ def get_code_region_containing_code( pattern = re.compile(re.escape(code_str)) # each occurrence is a tuple of (line_no, code_snippet) (1-based line number) occurrences: list[tuple[int, str]] = [] + file_content_lines = file_content.splitlines() for match in pattern.finditer(file_content): matched_start_pos = match.start() - # first, find the line number of the matched start position (1-based) - matched_line_no = file_content.count("\n", 0, matched_start_pos) + 1 - # next, get a few surrounding lines as context - search_start = match.start() - 1 - search_end = match.end() + 1 - # from the matched position, go left to find 5 new lines. - for _ in range(context_size): - # find the \n to the left - left_newline = file_content.rfind("\n", 0, search_start) - if left_newline == -1: - # no more new line to the left - search_start = 0 - break - else: - search_start = left_newline - # go right to fine 5 new lines - for _ in range(context_size): - right_newline = file_content.find("\n", search_end + 1) - if right_newline == -1: - # no more new line to the right - search_end = len(file_content) - break - else: - search_end = right_newline + # first, find the line number of the matched start position (0-based) + matched_line_no = file_content.count("\n", 0, matched_start_pos) + + window_start_index = max(0, matched_line_no - context_size) + window_end_index = min( + len(file_content_lines), matched_line_no + context_size + 1 + ) - start = max(0, search_start) - end = min(len(file_content), search_end) - context = file_content[start:end] + context = "\n".join(file_content_lines[window_start_index:window_end_index]) occurrences.append((matched_line_no, context)) return occurrences