Format a source code snippet with a column/span marker. Renders every source line spanned by the diagnostic (``lineno`` through ``end_lineno``, inclusive) with a per-line gutter, followed by a caret underline covering the offending span. For a single-line span (``end_lineno == linen
(
source_lines: list,
lineno: int,
col_offset: int,
end_lineno: int,
end_col_offset: int,
)
| 186 | |
| 187 | |
| 188 | def _format_source_snippet( |
| 189 | source_lines: list, |
| 190 | lineno: int, |
| 191 | col_offset: int, |
| 192 | end_lineno: int, |
| 193 | end_col_offset: int, |
| 194 | ) -> str: |
| 195 | """Format a source code snippet with a column/span marker. |
| 196 | |
| 197 | Renders every source line spanned by the diagnostic (``lineno`` through |
| 198 | ``end_lineno``, inclusive) with a per-line gutter, followed by a caret |
| 199 | underline covering the offending span. For a single-line span |
| 200 | (``end_lineno == lineno``) only the columns ``col_offset`` (inclusive) |
| 201 | through ``end_col_offset`` (exclusive) are underlined; for a multi-line |
| 202 | span the underline covers the start column to end-of-line on the first |
| 203 | line, the full text of interior lines, and the start of the final line up |
| 204 | to ``end_col_offset``. |
| 205 | |
| 206 | Parameters |
| 207 | ---------- |
| 208 | source_lines : list of str |
| 209 | Lines of the source code. |
| 210 | |
| 211 | lineno : int |
| 212 | 1-based starting line number in the source. |
| 213 | |
| 214 | col_offset : int |
| 215 | 1-based starting column (inclusive) on ``lineno``. |
| 216 | |
| 217 | end_lineno : int |
| 218 | 1-based ending line number in the source (>= ``lineno``). |
| 219 | |
| 220 | end_col_offset : int |
| 221 | 1-based ending column (exclusive) on ``end_lineno``. |
| 222 | |
| 223 | Returns |
| 224 | ------- |
| 225 | snippet : str |
| 226 | Formatted source snippet with caret-marker line(s). |
| 227 | """ |
| 228 | if end_lineno < lineno: |
| 229 | end_lineno = lineno |
| 230 | |
| 231 | # Determine the gutter width so that all line numbers line up. |
| 232 | header_width = len(f" {end_lineno} ") |
| 233 | no_line_header = " " * header_width |
| 234 | |
| 235 | parts = [f"{no_line_header}| "] |
| 236 | for cur_lineno in range(lineno, end_lineno + 1): |
| 237 | idx = cur_lineno - 1 |
| 238 | if not 0 <= idx < len(source_lines): |
| 239 | continue |
| 240 | line_text = source_lines[idx].rstrip("\n") |
| 241 | line_header = f" {cur_lineno} ".rjust(header_width) |
| 242 | |
| 243 | # Compute the underline span [start_col, stop_col) for this line. |
| 244 | start_col = col_offset if cur_lineno == lineno else 1 |
| 245 | stop_col = end_col_offset if cur_lineno == end_lineno else len(line_text) + 1 |
searching dependent graphs…