document.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. """
  2. The `Document` that implements all the text operations/querying.
  3. """
  4. from __future__ import unicode_literals
  5. import bisect
  6. import re
  7. import six
  8. import string
  9. import weakref
  10. from six.moves import range, map
  11. from .selection import SelectionType, SelectionState, PasteMode
  12. from .clipboard import ClipboardData
  13. __all__ = ('Document',)
  14. # Regex for finding "words" in documents. (We consider a group of alnum
  15. # characters a word, but also a group of special characters a word, as long as
  16. # it doesn't contain a space.)
  17. # (This is a 'word' in Vi.)
  18. _FIND_WORD_RE = re.compile(r'([a-zA-Z0-9_]+|[^a-zA-Z0-9_\s]+)')
  19. _FIND_CURRENT_WORD_RE = re.compile(r'^([a-zA-Z0-9_]+|[^a-zA-Z0-9_\s]+)')
  20. _FIND_CURRENT_WORD_INCLUDE_TRAILING_WHITESPACE_RE = re.compile(r'^(([a-zA-Z0-9_]+|[^a-zA-Z0-9_\s]+)\s*)')
  21. # Regex for finding "WORDS" in documents.
  22. # (This is a 'WORD in Vi.)
  23. _FIND_BIG_WORD_RE = re.compile(r'([^\s]+)')
  24. _FIND_CURRENT_BIG_WORD_RE = re.compile(r'^([^\s]+)')
  25. _FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE = re.compile(r'^([^\s]+\s*)')
  26. # Share the Document._cache between all Document instances.
  27. # (Document instances are considered immutable. That means that if another
  28. # `Document` is constructed with the same text, it should have the same
  29. # `_DocumentCache`.)
  30. _text_to_document_cache = weakref.WeakValueDictionary() # Maps document.text to DocumentCache instance.
  31. class _ImmutableLineList(list):
  32. """
  33. Some protection for our 'lines' list, which is assumed to be immutable in the cache.
  34. (Useful for detecting obvious bugs.)
  35. """
  36. def _error(self, *a, **kw):
  37. raise NotImplementedError('Attempt to modifiy an immutable list.')
  38. __setitem__ = _error
  39. append = _error
  40. clear = _error
  41. extend = _error
  42. insert = _error
  43. pop = _error
  44. remove = _error
  45. reverse = _error
  46. sort = _error
  47. class _DocumentCache(object):
  48. def __init__(self):
  49. #: List of lines for the Document text.
  50. self.lines = None
  51. #: List of index positions, pointing to the start of all the lines.
  52. self.line_indexes = None
  53. class Document(object):
  54. """
  55. This is a immutable class around the text and cursor position, and contains
  56. methods for querying this data, e.g. to give the text before the cursor.
  57. This class is usually instantiated by a :class:`~prompt_toolkit.buffer.Buffer`
  58. object, and accessed as the `document` property of that class.
  59. :param text: string
  60. :param cursor_position: int
  61. :param selection: :class:`.SelectionState`
  62. """
  63. __slots__ = ('_text', '_cursor_position', '_selection', '_cache')
  64. def __init__(self, text='', cursor_position=None, selection=None):
  65. assert isinstance(text, six.text_type), 'Got %r' % text
  66. assert selection is None or isinstance(selection, SelectionState)
  67. # Check cursor position. It can also be right after the end. (Where we
  68. # insert text.)
  69. assert cursor_position is None or cursor_position <= len(text), AssertionError(
  70. 'cursor_position=%r, len_text=%r' % (cursor_position, len(text)))
  71. # By default, if no cursor position was given, make sure to put the
  72. # cursor position is at the end of the document. This is what makes
  73. # sense in most places.
  74. if cursor_position is None:
  75. cursor_position = len(text)
  76. # Keep these attributes private. A `Document` really has to be
  77. # considered to be immutable, because otherwise the caching will break
  78. # things. Because of that, we wrap these into read-only properties.
  79. self._text = text
  80. self._cursor_position = cursor_position
  81. self._selection = selection
  82. # Cache for lines/indexes. (Shared with other Document instances that
  83. # contain the same text.
  84. try:
  85. self._cache = _text_to_document_cache[self.text]
  86. except KeyError:
  87. self._cache = _DocumentCache()
  88. _text_to_document_cache[self.text] = self._cache
  89. # XX: For some reason, above, we can't use 'WeakValueDictionary.setdefault'.
  90. # This fails in Pypy3. `self._cache` becomes None, because that's what
  91. # 'setdefault' returns.
  92. # self._cache = _text_to_document_cache.setdefault(self.text, _DocumentCache())
  93. # assert self._cache
  94. def __repr__(self):
  95. return '%s(%r, %r)' % (self.__class__.__name__, self.text, self.cursor_position)
  96. @property
  97. def text(self):
  98. " The document text. "
  99. return self._text
  100. @property
  101. def cursor_position(self):
  102. " The document cursor position. "
  103. return self._cursor_position
  104. @property
  105. def selection(self):
  106. " :class:`.SelectionState` object. "
  107. return self._selection
  108. @property
  109. def current_char(self):
  110. """ Return character under cursor or an empty string. """
  111. return self._get_char_relative_to_cursor(0) or ''
  112. @property
  113. def char_before_cursor(self):
  114. """ Return character before the cursor or an empty string. """
  115. return self._get_char_relative_to_cursor(-1) or ''
  116. @property
  117. def text_before_cursor(self):
  118. return self.text[:self.cursor_position:]
  119. @property
  120. def text_after_cursor(self):
  121. return self.text[self.cursor_position:]
  122. @property
  123. def current_line_before_cursor(self):
  124. """ Text from the start of the line until the cursor. """
  125. _, _, text = self.text_before_cursor.rpartition('\n')
  126. return text
  127. @property
  128. def current_line_after_cursor(self):
  129. """ Text from the cursor until the end of the line. """
  130. text, _, _ = self.text_after_cursor.partition('\n')
  131. return text
  132. @property
  133. def lines(self):
  134. """
  135. Array of all the lines.
  136. """
  137. # Cache, because this one is reused very often.
  138. if self._cache.lines is None:
  139. self._cache.lines = _ImmutableLineList(self.text.split('\n'))
  140. return self._cache.lines
  141. @property
  142. def _line_start_indexes(self):
  143. """
  144. Array pointing to the start indexes of all the lines.
  145. """
  146. # Cache, because this is often reused. (If it is used, it's often used
  147. # many times. And this has to be fast for editing big documents!)
  148. if self._cache.line_indexes is None:
  149. # Create list of line lengths.
  150. line_lengths = map(len, self.lines)
  151. # Calculate cumulative sums.
  152. indexes = [0]
  153. append = indexes.append
  154. pos = 0
  155. for line_length in line_lengths:
  156. pos += line_length + 1
  157. append(pos)
  158. # Remove the last item. (This is not a new line.)
  159. if len(indexes) > 1:
  160. indexes.pop()
  161. self._cache.line_indexes = indexes
  162. return self._cache.line_indexes
  163. @property
  164. def lines_from_current(self):
  165. """
  166. Array of the lines starting from the current line, until the last line.
  167. """
  168. return self.lines[self.cursor_position_row:]
  169. @property
  170. def line_count(self):
  171. r""" Return the number of lines in this document. If the document ends
  172. with a trailing \n, that counts as the beginning of a new line. """
  173. return len(self.lines)
  174. @property
  175. def current_line(self):
  176. """ Return the text on the line where the cursor is. (when the input
  177. consists of just one line, it equals `text`. """
  178. return self.current_line_before_cursor + self.current_line_after_cursor
  179. @property
  180. def leading_whitespace_in_current_line(self):
  181. """ The leading whitespace in the left margin of the current line. """
  182. current_line = self.current_line
  183. length = len(current_line) - len(current_line.lstrip())
  184. return current_line[:length]
  185. def _get_char_relative_to_cursor(self, offset=0):
  186. """
  187. Return character relative to cursor position, or empty string
  188. """
  189. try:
  190. return self.text[self.cursor_position + offset]
  191. except IndexError:
  192. return ''
  193. @property
  194. def on_first_line(self):
  195. """
  196. True when we are at the first line.
  197. """
  198. return self.cursor_position_row == 0
  199. @property
  200. def on_last_line(self):
  201. """
  202. True when we are at the last line.
  203. """
  204. return self.cursor_position_row == self.line_count - 1
  205. @property
  206. def cursor_position_row(self):
  207. """
  208. Current row. (0-based.)
  209. """
  210. row, _ = self._find_line_start_index(self.cursor_position)
  211. return row
  212. @property
  213. def cursor_position_col(self):
  214. """
  215. Current column. (0-based.)
  216. """
  217. # (Don't use self.text_before_cursor to calculate this. Creating
  218. # substrings and doing rsplit is too expensive for getting the cursor
  219. # position.)
  220. _, line_start_index = self._find_line_start_index(self.cursor_position)
  221. return self.cursor_position - line_start_index
  222. def _find_line_start_index(self, index):
  223. """
  224. For the index of a character at a certain line, calculate the index of
  225. the first character on that line.
  226. Return (row, index) tuple.
  227. """
  228. indexes = self._line_start_indexes
  229. pos = bisect.bisect_right(indexes, index) - 1
  230. return pos, indexes[pos]
  231. def translate_index_to_position(self, index):
  232. """
  233. Given an index for the text, return the corresponding (row, col) tuple.
  234. (0-based. Returns (0, 0) for index=0.)
  235. """
  236. # Find start of this line.
  237. row, row_index = self._find_line_start_index(index)
  238. col = index - row_index
  239. return row, col
  240. def translate_row_col_to_index(self, row, col):
  241. """
  242. Given a (row, col) tuple, return the corresponding index.
  243. (Row and col params are 0-based.)
  244. Negative row/col values are turned into zero.
  245. """
  246. try:
  247. result = self._line_start_indexes[row]
  248. line = self.lines[row]
  249. except IndexError:
  250. if row < 0:
  251. result = self._line_start_indexes[0]
  252. line = self.lines[0]
  253. else:
  254. result = self._line_start_indexes[-1]
  255. line = self.lines[-1]
  256. result += max(0, min(col, len(line)))
  257. # Keep in range. (len(self.text) is included, because the cursor can be
  258. # right after the end of the text as well.)
  259. result = max(0, min(result, len(self.text)))
  260. return result
  261. @property
  262. def is_cursor_at_the_end(self):
  263. """ True when the cursor is at the end of the text. """
  264. return self.cursor_position == len(self.text)
  265. @property
  266. def is_cursor_at_the_end_of_line(self):
  267. """ True when the cursor is at the end of this line. """
  268. return self.current_char in ('\n', '')
  269. def has_match_at_current_position(self, sub):
  270. """
  271. `True` when this substring is found at the cursor position.
  272. """
  273. return self.text.find(sub, self.cursor_position) == self.cursor_position
  274. def find(self, sub, in_current_line=False, include_current_position=False,
  275. ignore_case=False, count=1):
  276. """
  277. Find `text` after the cursor, return position relative to the cursor
  278. position. Return `None` if nothing was found.
  279. :param count: Find the n-th occurance.
  280. """
  281. assert isinstance(ignore_case, bool)
  282. if in_current_line:
  283. text = self.current_line_after_cursor
  284. else:
  285. text = self.text_after_cursor
  286. if not include_current_position:
  287. if len(text) == 0:
  288. return # (Otherwise, we always get a match for the empty string.)
  289. else:
  290. text = text[1:]
  291. flags = re.IGNORECASE if ignore_case else 0
  292. iterator = re.finditer(re.escape(sub), text, flags)
  293. try:
  294. for i, match in enumerate(iterator):
  295. if i + 1 == count:
  296. if include_current_position:
  297. return match.start(0)
  298. else:
  299. return match.start(0) + 1
  300. except StopIteration:
  301. pass
  302. def find_all(self, sub, ignore_case=False):
  303. """
  304. Find all occurances of the substring. Return a list of absolute
  305. positions in the document.
  306. """
  307. flags = re.IGNORECASE if ignore_case else 0
  308. return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)]
  309. def find_backwards(self, sub, in_current_line=False, ignore_case=False, count=1):
  310. """
  311. Find `text` before the cursor, return position relative to the cursor
  312. position. Return `None` if nothing was found.
  313. :param count: Find the n-th occurance.
  314. """
  315. if in_current_line:
  316. before_cursor = self.current_line_before_cursor[::-1]
  317. else:
  318. before_cursor = self.text_before_cursor[::-1]
  319. flags = re.IGNORECASE if ignore_case else 0
  320. iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
  321. try:
  322. for i, match in enumerate(iterator):
  323. if i + 1 == count:
  324. return - match.start(0) - len(sub)
  325. except StopIteration:
  326. pass
  327. def get_word_before_cursor(self, WORD=False):
  328. """
  329. Give the word before the cursor.
  330. If we have whitespace before the cursor this returns an empty string.
  331. """
  332. if self.text_before_cursor[-1:].isspace():
  333. return ''
  334. else:
  335. return self.text_before_cursor[self.find_start_of_previous_word(WORD=WORD):]
  336. def find_start_of_previous_word(self, count=1, WORD=False):
  337. """
  338. Return an index relative to the cursor position pointing to the start
  339. of the previous word. Return `None` if nothing was found.
  340. """
  341. # Reverse the text before the cursor, in order to do an efficient
  342. # backwards search.
  343. text_before_cursor = self.text_before_cursor[::-1]
  344. regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
  345. iterator = regex.finditer(text_before_cursor)
  346. try:
  347. for i, match in enumerate(iterator):
  348. if i + 1 == count:
  349. return - match.end(1)
  350. except StopIteration:
  351. pass
  352. def find_boundaries_of_current_word(self, WORD=False, include_leading_whitespace=False,
  353. include_trailing_whitespace=False):
  354. """
  355. Return the relative boundaries (startpos, endpos) of the current word under the
  356. cursor. (This is at the current line, because line boundaries obviously
  357. don't belong to any word.)
  358. If not on a word, this returns (0,0)
  359. """
  360. text_before_cursor = self.current_line_before_cursor[::-1]
  361. text_after_cursor = self.current_line_after_cursor
  362. def get_regex(include_whitespace):
  363. return {
  364. (False, False): _FIND_CURRENT_WORD_RE,
  365. (False, True): _FIND_CURRENT_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
  366. (True, False): _FIND_CURRENT_BIG_WORD_RE,
  367. (True, True): _FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
  368. }[(WORD, include_whitespace)]
  369. match_before = get_regex(include_leading_whitespace).search(text_before_cursor)
  370. match_after = get_regex(include_trailing_whitespace).search(text_after_cursor)
  371. # When there is a match before and after, and we're not looking for
  372. # WORDs, make sure that both the part before and after the cursor are
  373. # either in the [a-zA-Z_] alphabet or not. Otherwise, drop the part
  374. # before the cursor.
  375. if not WORD and match_before and match_after:
  376. c1 = self.text[self.cursor_position - 1]
  377. c2 = self.text[self.cursor_position]
  378. alphabet = string.ascii_letters + '0123456789_'
  379. if (c1 in alphabet) != (c2 in alphabet):
  380. match_before = None
  381. return (
  382. - match_before.end(1) if match_before else 0,
  383. match_after.end(1) if match_after else 0
  384. )
  385. def get_word_under_cursor(self, WORD=False):
  386. """
  387. Return the word, currently below the cursor.
  388. This returns an empty string when the cursor is on a whitespace region.
  389. """
  390. start, end = self.find_boundaries_of_current_word(WORD=WORD)
  391. return self.text[self.cursor_position + start: self.cursor_position + end]
  392. def find_next_word_beginning(self, count=1, WORD=False):
  393. """
  394. Return an index relative to the cursor position pointing to the start
  395. of the next word. Return `None` if nothing was found.
  396. """
  397. if count < 0:
  398. return self.find_previous_word_beginning(count=-count, WORD=WORD)
  399. regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
  400. iterator = regex.finditer(self.text_after_cursor)
  401. try:
  402. for i, match in enumerate(iterator):
  403. # Take first match, unless it's the word on which we're right now.
  404. if i == 0 and match.start(1) == 0:
  405. count += 1
  406. if i + 1 == count:
  407. return match.start(1)
  408. except StopIteration:
  409. pass
  410. def find_next_word_ending(self, include_current_position=False, count=1, WORD=False):
  411. """
  412. Return an index relative to the cursor position pointing to the end
  413. of the next word. Return `None` if nothing was found.
  414. """
  415. if count < 0:
  416. return self.find_previous_word_ending(count=-count, WORD=WORD)
  417. if include_current_position:
  418. text = self.text_after_cursor
  419. else:
  420. text = self.text_after_cursor[1:]
  421. regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
  422. iterable = regex.finditer(text)
  423. try:
  424. for i, match in enumerate(iterable):
  425. if i + 1 == count:
  426. value = match.end(1)
  427. if include_current_position:
  428. return value
  429. else:
  430. return value + 1
  431. except StopIteration:
  432. pass
  433. def find_previous_word_beginning(self, count=1, WORD=False):
  434. """
  435. Return an index relative to the cursor position pointing to the start
  436. of the previous word. Return `None` if nothing was found.
  437. """
  438. if count < 0:
  439. return self.find_next_word_beginning(count=-count, WORD=WORD)
  440. regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
  441. iterator = regex.finditer(self.text_before_cursor[::-1])
  442. try:
  443. for i, match in enumerate(iterator):
  444. if i + 1 == count:
  445. return - match.end(1)
  446. except StopIteration:
  447. pass
  448. def find_previous_word_ending(self, count=1, WORD=False):
  449. """
  450. Return an index relative to the cursor position pointing to the end
  451. of the previous word. Return `None` if nothing was found.
  452. """
  453. if count < 0:
  454. return self.find_next_word_ending(count=-count, WORD=WORD)
  455. text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
  456. regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
  457. iterator = regex.finditer(text_before_cursor)
  458. try:
  459. for i, match in enumerate(iterator):
  460. # Take first match, unless it's the word on which we're right now.
  461. if i == 0 and match.start(1) == 0:
  462. count += 1
  463. if i + 1 == count:
  464. return -match.start(1) + 1
  465. except StopIteration:
  466. pass
  467. def find_next_matching_line(self, match_func, count=1):
  468. """
  469. Look downwards for empty lines.
  470. Return the line index, relative to the current line.
  471. """
  472. result = None
  473. for index, line in enumerate(self.lines[self.cursor_position_row + 1:]):
  474. if match_func(line):
  475. result = 1 + index
  476. count -= 1
  477. if count == 0:
  478. break
  479. return result
  480. def find_previous_matching_line(self, match_func, count=1):
  481. """
  482. Look upwards for empty lines.
  483. Return the line index, relative to the current line.
  484. """
  485. result = None
  486. for index, line in enumerate(self.lines[:self.cursor_position_row][::-1]):
  487. if match_func(line):
  488. result = -1 - index
  489. count -= 1
  490. if count == 0:
  491. break
  492. return result
  493. def get_cursor_left_position(self, count=1):
  494. """
  495. Relative position for cursor left.
  496. """
  497. if count < 0:
  498. return self.get_cursor_right_position(-count)
  499. return - min(self.cursor_position_col, count)
  500. def get_cursor_right_position(self, count=1):
  501. """
  502. Relative position for cursor_right.
  503. """
  504. if count < 0:
  505. return self.get_cursor_left_position(-count)
  506. return min(count, len(self.current_line_after_cursor))
  507. def get_cursor_up_position(self, count=1, preferred_column=None):
  508. """
  509. Return the relative cursor position (character index) where we would be if the
  510. user pressed the arrow-up button.
  511. :param preferred_column: When given, go to this column instead of
  512. staying at the current column.
  513. """
  514. assert count >= 1
  515. column = self.cursor_position_col if preferred_column is None else preferred_column
  516. return self.translate_row_col_to_index(
  517. max(0, self.cursor_position_row - count), column) - self.cursor_position
  518. def get_cursor_down_position(self, count=1, preferred_column=None):
  519. """
  520. Return the relative cursor position (character index) where we would be if the
  521. user pressed the arrow-down button.
  522. :param preferred_column: When given, go to this column instead of
  523. staying at the current column.
  524. """
  525. assert count >= 1
  526. column = self.cursor_position_col if preferred_column is None else preferred_column
  527. return self.translate_row_col_to_index(
  528. self.cursor_position_row + count, column) - self.cursor_position
  529. def find_enclosing_bracket_right(self, left_ch, right_ch, end_pos=None):
  530. """
  531. Find the right bracket enclosing current position. Return the relative
  532. position to the cursor position.
  533. When `end_pos` is given, don't look past the position.
  534. """
  535. if self.current_char == right_ch:
  536. return 0
  537. if end_pos is None:
  538. end_pos = len(self.text)
  539. else:
  540. end_pos = min(len(self.text), end_pos)
  541. stack = 1
  542. # Look forward.
  543. for i in range(self.cursor_position + 1, end_pos):
  544. c = self.text[i]
  545. if c == left_ch:
  546. stack += 1
  547. elif c == right_ch:
  548. stack -= 1
  549. if stack == 0:
  550. return i - self.cursor_position
  551. def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None):
  552. """
  553. Find the left bracket enclosing current position. Return the relative
  554. position to the cursor position.
  555. When `start_pos` is given, don't look past the position.
  556. """
  557. if self.current_char == left_ch:
  558. return 0
  559. if start_pos is None:
  560. start_pos = 0
  561. else:
  562. start_pos = max(0, start_pos)
  563. stack = 1
  564. # Look backward.
  565. for i in range(self.cursor_position - 1, start_pos - 1, -1):
  566. c = self.text[i]
  567. if c == right_ch:
  568. stack += 1
  569. elif c == left_ch:
  570. stack -= 1
  571. if stack == 0:
  572. return i - self.cursor_position
  573. def find_matching_bracket_position(self, start_pos=None, end_pos=None):
  574. """
  575. Return relative cursor position of matching [, (, { or < bracket.
  576. When `start_pos` or `end_pos` are given. Don't look past the positions.
  577. """
  578. # Look for a match.
  579. for A, B in '()', '[]', '{}', '<>':
  580. if self.current_char == A:
  581. return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
  582. elif self.current_char == B:
  583. return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
  584. return 0
  585. def get_start_of_document_position(self):
  586. """ Relative position for the start of the document. """
  587. return - self.cursor_position
  588. def get_end_of_document_position(self):
  589. """ Relative position for the end of the document. """
  590. return len(self.text) - self.cursor_position
  591. def get_start_of_line_position(self, after_whitespace=False):
  592. """ Relative position for the start of this line. """
  593. if after_whitespace:
  594. current_line = self.current_line
  595. return len(current_line) - len(current_line.lstrip()) - self.cursor_position_col
  596. else:
  597. return - len(self.current_line_before_cursor)
  598. def get_end_of_line_position(self):
  599. """ Relative position for the end of this line. """
  600. return len(self.current_line_after_cursor)
  601. def last_non_blank_of_current_line_position(self):
  602. """
  603. Relative position for the last non blank character of this line.
  604. """
  605. return len(self.current_line.rstrip()) - self.cursor_position_col - 1
  606. def get_column_cursor_position(self, column):
  607. """
  608. Return the relative cursor position for this column at the current
  609. line. (It will stay between the boundaries of the line in case of a
  610. larger number.)
  611. """
  612. line_length = len(self.current_line)
  613. current_column = self.cursor_position_col
  614. column = max(0, min(line_length, column))
  615. return column - current_column
  616. def selection_range(self): # XXX: shouldn't this return `None` if there is no selection???
  617. """
  618. Return (from, to) tuple of the selection.
  619. start and end position are included.
  620. This doesn't take the selection type into account. Use
  621. `selection_ranges` instead.
  622. """
  623. if self.selection:
  624. from_, to = sorted([self.cursor_position, self.selection.original_cursor_position])
  625. else:
  626. from_, to = self.cursor_position, self.cursor_position
  627. return from_, to
  628. def selection_ranges(self):
  629. """
  630. Return a list of (from, to) tuples for the selection or none if nothing
  631. was selected. start and end position are always included in the
  632. selection.
  633. This will yield several (from, to) tuples in case of a BLOCK selection.
  634. """
  635. if self.selection:
  636. from_, to = sorted([self.cursor_position, self.selection.original_cursor_position])
  637. if self.selection.type == SelectionType.BLOCK:
  638. from_line, from_column = self.translate_index_to_position(from_)
  639. to_line, to_column = self.translate_index_to_position(to)
  640. from_column, to_column = sorted([from_column, to_column])
  641. lines = self.lines
  642. for l in range(from_line, to_line + 1):
  643. line_length = len(lines[l])
  644. if from_column < line_length:
  645. yield (self.translate_row_col_to_index(l, from_column),
  646. self.translate_row_col_to_index(l, min(line_length - 1, to_column)))
  647. else:
  648. # In case of a LINES selection, go to the start/end of the lines.
  649. if self.selection.type == SelectionType.LINES:
  650. from_ = max(0, self.text.rfind('\n', 0, from_) + 1)
  651. if self.text.find('\n', to) >= 0:
  652. to = self.text.find('\n', to)
  653. else:
  654. to = len(self.text) - 1
  655. yield from_, to
  656. def selection_range_at_line(self, row):
  657. """
  658. If the selection spans a portion of the given line, return a (from, to) tuple.
  659. Otherwise, return None.
  660. """
  661. if self.selection:
  662. row_start = self.translate_row_col_to_index(row, 0)
  663. row_end = self.translate_row_col_to_index(row, max(0, len(self.lines[row]) - 1))
  664. from_, to = sorted([self.cursor_position, self.selection.original_cursor_position])
  665. # Take the intersection of the current line and the selection.
  666. intersection_start = max(row_start, from_)
  667. intersection_end = min(row_end, to)
  668. if intersection_start <= intersection_end:
  669. if self.selection.type == SelectionType.LINES:
  670. intersection_start = row_start
  671. intersection_end = row_end
  672. elif self.selection.type == SelectionType.BLOCK:
  673. _, col1 = self.translate_index_to_position(from_)
  674. _, col2 = self.translate_index_to_position(to)
  675. col1, col2 = sorted([col1, col2])
  676. intersection_start = self.translate_row_col_to_index(row, col1)
  677. intersection_end = self.translate_row_col_to_index(row, col2)
  678. _, from_column = self.translate_index_to_position(intersection_start)
  679. _, to_column = self.translate_index_to_position(intersection_end)
  680. return from_column, to_column
  681. def cut_selection(self):
  682. """
  683. Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the
  684. document represents the new document when the selection is cut, and the
  685. clipboard data, represents whatever has to be put on the clipboard.
  686. """
  687. if self.selection:
  688. cut_parts = []
  689. remaining_parts = []
  690. new_cursor_position = self.cursor_position
  691. last_to = 0
  692. for from_, to in self.selection_ranges():
  693. if last_to == 0:
  694. new_cursor_position = from_
  695. remaining_parts.append(self.text[last_to:from_])
  696. cut_parts.append(self.text[from_:to + 1])
  697. last_to = to + 1
  698. remaining_parts.append(self.text[last_to:])
  699. cut_text = '\n'.join(cut_parts)
  700. remaining_text = ''.join(remaining_parts)
  701. # In case of a LINES selection, don't include the trailing newline.
  702. if self.selection.type == SelectionType.LINES and cut_text.endswith('\n'):
  703. cut_text = cut_text[:-1]
  704. return (Document(text=remaining_text, cursor_position=new_cursor_position),
  705. ClipboardData(cut_text, self.selection.type))
  706. else:
  707. return self, ClipboardData('')
  708. def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1):
  709. """
  710. Return a new :class:`.Document` instance which contains the result if
  711. we would paste this data at the current cursor position.
  712. :param paste_mode: Where to paste. (Before/after/emacs.)
  713. :param count: When >1, Paste multiple times.
  714. """
  715. assert isinstance(data, ClipboardData)
  716. assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
  717. before = (paste_mode == PasteMode.VI_BEFORE)
  718. after = (paste_mode == PasteMode.VI_AFTER)
  719. if data.type == SelectionType.CHARACTERS:
  720. if after:
  721. new_text = (self.text[:self.cursor_position + 1] + data.text * count +
  722. self.text[self.cursor_position + 1:])
  723. else:
  724. new_text = self.text_before_cursor + data.text * count + self.text_after_cursor
  725. new_cursor_position = self.cursor_position + len(data.text) * count
  726. if before:
  727. new_cursor_position -= 1
  728. elif data.type == SelectionType.LINES:
  729. l = self.cursor_position_row
  730. if before:
  731. lines = self.lines[:l] + [data.text] * count + self.lines[l:]
  732. new_text = '\n'.join(lines)
  733. new_cursor_position = len(''.join(self.lines[:l])) + l
  734. else:
  735. lines = self.lines[:l + 1] + [data.text] * count + self.lines[l + 1:]
  736. new_cursor_position = len(''.join(self.lines[:l + 1])) + l + 1
  737. new_text = '\n'.join(lines)
  738. elif data.type == SelectionType.BLOCK:
  739. lines = self.lines[:]
  740. start_line = self.cursor_position_row
  741. start_column = self.cursor_position_col + (0 if before else 1)
  742. for i, line in enumerate(data.text.split('\n')):
  743. index = i + start_line
  744. if index >= len(lines):
  745. lines.append('')
  746. lines[index] = lines[index].ljust(start_column)
  747. lines[index] = lines[index][:start_column] + line * count + lines[index][start_column:]
  748. new_text = '\n'.join(lines)
  749. new_cursor_position = self.cursor_position + (0 if before else 1)
  750. return Document(text=new_text, cursor_position=new_cursor_position)
  751. def empty_line_count_at_the_end(self):
  752. """
  753. Return number of empty lines at the end of the document.
  754. """
  755. count = 0
  756. for line in self.lines[::-1]:
  757. if not line or line.isspace():
  758. count += 1
  759. else:
  760. break
  761. return count
  762. def start_of_paragraph(self, count=1, before=False):
  763. """
  764. Return the start of the current paragraph. (Relative cursor position.)
  765. """
  766. def match_func(text):
  767. return not text or text.isspace()
  768. line_index = self.find_previous_matching_line(match_func=match_func, count=count)
  769. if line_index:
  770. add = 0 if before else 1
  771. return min(0, self.get_cursor_up_position(count=-line_index) + add)
  772. else:
  773. return -self.cursor_position
  774. def end_of_paragraph(self, count=1, after=False):
  775. """
  776. Return the end of the current paragraph. (Relative cursor position.)
  777. """
  778. def match_func(text):
  779. return not text or text.isspace()
  780. line_index = self.find_next_matching_line(match_func=match_func, count=count)
  781. if line_index:
  782. add = 0 if after else 1
  783. return max(0, self.get_cursor_down_position(count=line_index) - add)
  784. else:
  785. return len(self.text_after_cursor)
  786. # Modifiers.
  787. def insert_after(self, text):
  788. """
  789. Create a new document, with this text inserted after the buffer.
  790. It keeps selection ranges and cursor position in sync.
  791. """
  792. return Document(
  793. text=self.text + text,
  794. cursor_position=self.cursor_position,
  795. selection=self.selection)
  796. def insert_before(self, text):
  797. """
  798. Create a new document, with this text inserted before the buffer.
  799. It keeps selection ranges and cursor position in sync.
  800. """
  801. selection_state = self.selection
  802. if selection_state:
  803. selection_state = SelectionState(
  804. original_cursor_position=selection_state.original_cursor_position + len(text),
  805. type=selection_state.type)
  806. return Document(
  807. text=text + self.text,
  808. cursor_position=self.cursor_position + len(text),
  809. selection=selection_state)