line_numbers.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright 2016 Grist Labs, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import bisect
  15. import re
  16. from typing import Dict, List, Tuple
  17. _line_start_re = re.compile(r'^', re.M)
  18. class LineNumbers(object):
  19. """
  20. Class to convert between character offsets in a text string, and pairs (line, column) of 1-based
  21. line and 0-based column numbers, as used by tokens and AST nodes.
  22. This class expects unicode for input and stores positions in unicode. But it supports
  23. translating to and from utf8 offsets, which are used by ast parsing.
  24. """
  25. def __init__(self, text):
  26. # type: (str) -> None
  27. # A list of character offsets of each line's first character.
  28. self._line_offsets = [m.start(0) for m in _line_start_re.finditer(text)]
  29. self._text = text
  30. self._text_len = len(text)
  31. self._utf8_offset_cache = {} # type: Dict[int, List[int]] # maps line num to list of char offset for each byte in line
  32. def from_utf8_col(self, line, utf8_column):
  33. # type: (int, int) -> int
  34. """
  35. Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column.
  36. """
  37. offsets = self._utf8_offset_cache.get(line)
  38. if offsets is None:
  39. end_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len
  40. line_text = self._text[self._line_offsets[line - 1] : end_offset]
  41. offsets = [i for i,c in enumerate(line_text) for byte in c.encode('utf8')]
  42. offsets.append(len(line_text))
  43. self._utf8_offset_cache[line] = offsets
  44. return offsets[max(0, min(len(offsets)-1, utf8_column))]
  45. def line_to_offset(self, line, column):
  46. # type: (int, int) -> int
  47. """
  48. Converts 1-based line number and 0-based column to 0-based character offset into text.
  49. """
  50. line -= 1
  51. if line >= len(self._line_offsets):
  52. return self._text_len
  53. elif line < 0:
  54. return 0
  55. else:
  56. return min(self._line_offsets[line] + max(0, column), self._text_len)
  57. def offset_to_line(self, offset):
  58. # type: (int) -> Tuple[int, int]
  59. """
  60. Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
  61. numbers.
  62. """
  63. offset = max(0, min(self._text_len, offset))
  64. line_index = bisect.bisect_right(self._line_offsets, offset) - 1
  65. return (line_index + 1, offset - self._line_offsets[line_index])