-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrap_fixer.py
1586 lines (1395 loc) · 69.3 KB
/
wrap_fixer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import sys
from sublime import Region
import sublime
import sublime_plugin
if sys.version_info[0] >= 3:
from .settings_parser import SettingsParser
from .util import Util
else:
from settings_parser import SettingsParser
from util import Util
class WrapFixer(sublime_plugin.TextCommand):
"""Provides the ability to perform word wrapping fixup.
"Word wrapping fixup" consists of attempting to fix word wrapping in
the vicinity of the selection cursor. WrapFixer is the meat /
brains of the WrapAsYouType plugin. Each WrapFixer instance manages
a particular View. A WrapFixer instance assumes that the
on_modified(), on_post_modification(), and on_selection_modified()
methods are called as appropriate.
"""
# The main body of wrap fixup is the _gen_edits() method. It is a
# coroutine - a generator method that yields a sequence of edits to perform
# to fix word wrap, and requires each edit to be executed before control is
# returned to the generator. Each edit is represented as a pair consisting
# of a Region and a string, and indicates that any text that is in the
# Region should be replaced with the given string.
#
# A number of variable names recur in the implementation of WrapFixer. The
# "indent" of a line is the whitespace on that line that precedes the line
# start under consideration. The "i_line_start" (indent + line start) of a
# line is the result of appending the line start to the indent. The
# "i_line_start_i" (indent + line start + indent) of a line is the
# i_line_start, followed by all of the subsequent whitespace on that line,
# up to the first non-whitespace character or the end of the line.
#
# Private attributes:
#
# Generator<tuple<Region, str>> _edits_gen - A coroutine that yields the
# edits to execute in order to perform word wrapping fixup: an
# execution of the _gen_edits() method. This will normally be at least
# partially executed: if has_edit() has been called, then the first
# edit is retrieved as _first_edit, and if perform_edits() has been
# called, then all of the edits have been retrieved. This is None if
# the view was altered since the beginning of the most recent call to
# has_edit() or perform_edits().
# tuple<Region, str> _first_edit - The first edit that _edits_gen yielded.
# This is None if it did not yield any edits or if _edits_gen is None.
# bool _passively_split - Whether the line after the selection cursor was
# added as a result of our splitting a line (as in _try_split_edit),
# provided that the split took place since the last time the user set
# "wrap_as_you_type_passive" to true or "wrap_as_you_type_disabled" to
# false, and since the last time he manually moved the selection
# cursor.
# int _prev_selection_point - The most recent value of _selection_point().
# We do not update _prev_selection_point if the
# "wrap_as_you_type_disabled" setting is true.
# list<bool> _section_matches - Whether the selection cursor matches each
# of the sections, as in _point_matches_selector. This is parallel to
# _settings_parser.sections. All of the elements of _section_matches
# are True if there isn't a single, empty selection cursor. In the
# event of a modification, _section_matches is not updated until
# on_post_modification() is called. The value of _section_matches is
# unspecified if _settings_parser.is_disabled is True.
# View _view - The View that this WrapFixer manages.
# A regular expression for stripping whitespace from the beginning and end
# of a string. The result of the stripping is given by re.Match.group(1).
_STRIP_REGEX = re.compile(r'^\s*(\S.*\S|\S?)\s*$', re.DOTALL)
# A regular expression matching all of the whitespace at the end of the
# source string. It matches the empty string if there is no such
# whitespace.
_TRAILING_WHITESPACE_REGEX = re.compile(r'\s*$')
# Equivalent value is contractual
_WHITESPACE_REGEX = re.compile(r'\s*')
# A map to each WrapFixer instance from _view.id()
_instances = {}
def __init__(self, view):
"""Private constructor."""
self._view = view
self._edits_gen = None
self._first_edit = None
self._prev_selection_point = None
self._passively_split = False
self._section_matches = []
self._settings_parser = SettingsParser(view)
self._settings_parser.add_on_change(
'wrap_as_you_type_sections', self._update_section_matches)
self._settings_parser.add_on_change(
'wrap_as_you_type_passive', self._on_change_passive)
self._settings_parser.add_on_change(
'wrap_as_you_type_disabled', self._on_change_disabled)
def _selection_point(self):
"""Return the point of the selection cursor.
Return None if there is not a single, empty selection cursor.
return int - The point.
"""
selection = self._view.sel()
if len(selection) == 1 and selection[0].empty():
return selection[0].begin()
else:
return None
def _update_section_matches(self):
"""Update the value of _section_matches."""
if (not self._settings_parser.sections or
self._settings_parser.is_disabled):
return
view = self._view
point = self._selection_point()
if point is None:
self._section_matches = (
[True] * len(self._settings_parser.sections))
return
line_region = view.line(point)
prev_char_scope = self._prev_char_scope(point, line_region)
next_char_scope = view.scope_name(point)
self._section_matches = []
for section in self._settings_parser.sections:
self._section_matches.append(
self._matches_selector(
section, prev_char_scope, next_char_scope))
def _add_width(self, width, char, tab_size):
"""Return the resulting width after adding the specified character.
Return the width (number of columns) that results from appending
the specified character to a line of the specified width.
Assume that char is not a newline character.
Note that this method is conceptually faulty. See the comments
for _width for details.
int width - The width of the line prior to adding "char".
str char - The character.
int tab_size - The number of columns per tab.
return int - The width after adding "char".
"""
if char != '\t':
return width + 1
else:
return (width // tab_size) * tab_size + tab_size
def _width(self, line):
"""Return the width of the specified line of text.
Return the width (number of columns) of the specified line of
text. Assume that "line" does not contain any newline
characters.
Note that this method is conceptually faulty. It assumes that
there is one character per Unicode code point, but this is not
always true, e.g. for Thai characters. However, at the time of
writing, Sublime Text renders each Unicode code point as one
character, so the behavior of this method conforms to that of
Sublime. See
https://github.com/SublimeTextIssues/Core/issues/663 .
"""
tab_size = self._view.settings().get('tab_size')
width = 0
for char in line:
width = self._add_width(width, char, tab_size)
return width
def _advance_by_width(self, line, width):
"""Return the character at column "width" of "line".
Return the index of the first character in the specified line of
text that is at or beyond the specified width (number of
columns). For example, _advance_by_width('foo bar', 4) returns
4. Assume that "line" does not contain any newline characters.
Note that this method is conceptually faulty. See the comments
for _width for details.
"""
tab_size = self._view.settings().get('tab_size')
width_traveled = 0
for i, char in enumerate(line):
if width_traveled >= width:
return i
width_traveled = self._add_width(width_traveled, char, tab_size)
return len(line)
def _wrap_width(self, section):
"""Return the wrap width of the specified section.
If section['wrap_width'] is None, this method uses the
appropriate fallback.
dict<str, object> section - The section, formatted like the
elements of _settings_parser.sections.
return int - The wrap width.
"""
if section['wrap_width'] is not None:
return section['wrap_width']
settings = self._view.settings()
wrap_width = settings.get('wrap_width')
if wrap_width:
return wrap_width
rulers = settings.get('rulers')
if rulers:
return rulers[0]
else:
return 80
def _prev_line_region(self, point):
"""Return the Region containing the previous line.
Return the Region containing the line before the line that
contains "point", excluding newline characters, if any.
int point - The point.
return Region - The previous line region.
"""
view = self._view
row = view.rowcol(point)[0]
if row > 0:
return view.line(view.text_point(row - 1, 0))
else:
return None
def _next_line_region(self, point):
"""Return the Region containing the next line.
Return the Region containing the line after the line that
contains "point", excluding newline characters, if any.
int point - The point.
return Region - The next line region.
"""
view = self._view
line_region = view.full_line(point)
if line_region.end() < view.size():
return view.line(line_region.end())
else:
return None
def _leading_whitespace(self, str_, start=0):
"""Return the whitespace at the beginning of the specified string.
Return all of the whitespace at the beginning of str_[start:].
Return '' if there is no such whitespace.
str str_ - The string.
int start - The starting index.
return str - The leading whitespace.
"""
return WrapFixer._WHITESPACE_REGEX.match(str_, start).group()
def _end_point_excluding_whitespace(self, str_, region):
"""Return the latest point in "region" that is a whitespace character.
Return the point of (or rather, immediately before) the latest
character in "region" that is a whitespace character. Return
region.end() if the last character is not a whitespace
character. Return region.begin() if all of the characters are
whitespace characters.
str str_ - The value of _view.substr(region).
Region region - The region.
return int - The point.
"""
match = WrapFixer._TRAILING_WHITESPACE_REGEX.search(str_)
return region.end() - match.end() + match.start()
def _section_indent(self, line, line_start):
"""Return the whitespace at the beginning of "line" before line_start.
For example, _section_indent(' * Foo', ' * ') returns ' ',
because there are two spaces prior to the space-asterisk-space.
Assume that "line" does not contain any newline characters.
Return None if "line" does not start with whitespace followed by
line_start. If line_start consists exclusively of whitespace,
so that there are multiple possible matches, return the shortest
possible match.
str line - The line of text to match.
str line_start - The line start.
return str - The whitespace before line_start.
"""
line_indent = self._leading_whitespace(line)
if Util.is_all_whitespace(line_start):
index = line_indent.find(line_start)
if index >= 0:
return line_indent[:index]
else:
return None
else:
line_start_indent = self._leading_whitespace(line_start)
section_indent_length = len(line_indent) - len(line_start_indent)
if (line_indent.endswith(line_start_indent) and
line[
len(line_indent):
section_indent_length + len(line_start)] ==
line_start[len(line_start_indent):]):
return line_indent[:section_indent_length]
else:
return None
def _i_line_start_i(self, line, line_start):
"""Return the i_line_start_i of the specified line.
str line - The line of text.
str line_start - The line start.
return str - The i_line_start_i.
"""
indent = self._section_indent(line, line_start)
if indent is None:
return None
post_indent = self._leading_whitespace(
line, len(indent) + len(line_start))
return line[:len(indent) + len(line_start) + len(post_indent)]
def _fix_word_spans(self, raw_spans, str_):
"""Fix errors in the results of applying "wrap_as_you_type_word_regex".
Return a list of word spans that is like raw_spans, but after
applying adjustments needed to make the results permissible for
"wrap_as_you_type_word_regex". Per README.md,
"wrap_as_you_type_word_regex" may not produce non-empty words,
and it must produce words that cover all non-whitespace
characters. If raw_spans does not meet these conditions,
_fix_word_spans attempts to produce similar results that do.
_fix_word_spans may warn the user of the error.
list<tuple<int, int>> raw_spans - The word spans produced by
"wrap_as_you_type_word_regex", formatted like the return
value of _word_spans.
str str_ - The string from which the words are taken.
return list<tuple<int, int>> - The adjusted word spans,
formatted like the return value of _word_spans.
"""
# Remove zero-character words
non_empty_spans = [span for span in raw_spans if span[0] != span[1]]
warn = len(non_empty_spans) < len(raw_spans)
# Check each gap between adjacent words (and at the beginning and end
# of the string) for non-whitespace characters
spans = []
for i in range(0, len(non_empty_spans) + 1):
# Identify the gap
if i > 0:
gap_start_index = non_empty_spans[i - 1][1]
else:
gap_start_index = 0
if i < len(non_empty_spans):
gap_end_index = non_empty_spans[i][0]
else:
gap_end_index = len(str_)
gap = str_[gap_start_index:gap_end_index]
# Check for non-whitespace characters
match = WrapFixer._STRIP_REGEX.search(gap)
if match.start(1) < match.end(1):
# The gap has a non-whitespace character. Add a word that
# covers the non-whitespace characters.
warn = True
spans.append((
gap_start_index + match.start(1),
gap_start_index + match.end(1)))
if i < len(non_empty_spans):
spans.append(non_empty_spans[i])
if warn:
raw_words = [str_[span[0]:span[1]] for span in raw_spans]
print(
u'WrapAsYouType error: The "wrap_as_you_type_word_regex" '
'setting is faulty, because on the string {0:s}, it yielded '
'either an empty word, or a gap between words that had '
'non-whitespace characters. It produced the following words: '
'{1:s}. WrapAsYouType has corrected for this, but you should '
'fix the setting.'.format(repr(str_.strip()), str(raw_words)))
Util.status_message(
self._view.window(),
'WrapAsYouType settings error; see console')
return spans
def _word_spans(self, str_):
"""Return the locations of the words in str_.
Return the locations of the words in str_, based on the value of
_settings_parser.word_regex (and after applying any corrections
suggested by _fix_word_spans).
str str_ - The string to search.
return list<tuple<int, int>> - The positions of the words. Each
element is a pair indicating the start and end indices of
the span (the index of the first character, and the index of
the position right after the last character). The elements
are in order.
"""
# Trim whitespace
match = WrapFixer._STRIP_REGEX.search(str_)
trimmed_str = match.group(1)
if not trimmed_str:
return []
trimmed_str_start_index = match.start(1)
# Compute the words
spans = []
for match in self._settings_parser.word_regex.finditer(trimmed_str):
spans.append((
trimmed_str_start_index + match.start(),
trimmed_str_start_index + match.end()))
# Fix any problems with the words
if (self._settings_parser.word_regex !=
SettingsParser.DEFAULT_WORD_REGEX):
return self._fix_word_spans(spans, str_)
else:
# Optimization: DEFAULT_WORD_REGEX is trustworthy, so don't bother
# calling _fix_word_spans
return spans
def _space_between(self, first_word, second_word):
"""Return the space to use between the specified words.
Return the space to use between the specified words, as
suggested by _settings_parser.space_between_words. The space is
a string consisting of whitespace characters. It may be the
empty string ''.
str first_word - The word before the space.
str second_word - The word after the space.
return str - The space.
"""
for item in self._settings_parser.space_between_words:
if ((item['first_word_regex'] is None or
item['first_word_regex'].search(
first_word) is not None) and
(item['second_word_regex'] is None or
item['second_word_regex'].search(
second_word) is not None)):
return item['space']
return ' '
def _combine_extent(self, section, first_point, second_point):
"""Return the furthest that we can combine a section.
Return the furthest point that we can combine first_point with
in the specified section, based on section['combining_selector']
and section['selector'], as we move from first_point to
second_point. So if second_point > first_point, this is the
latest point that is no later than second_point that we can
combine with first_point, and vice versa if second_point <
first_point. _combine_extent does not check whether first_point
matches the section (as in _point_matches_selector).
dict<str, object> section - The section, formatted like the
elements of _settings_parser.sections.
int first_point - The starting point.
int second_point - The ending point.
return int - The furthest point we can combine.
"""
# Determine the range of points on which to check score_selector
view = self._view
if first_point >= second_point:
points = range(first_point - 1, second_point - 1, -1)
elif view.rowcol(second_point)[1] > 0:
points = range(first_point, second_point)
else:
# Special-case the first character of a line; see the comment below
points = range(first_point, second_point + 1)
prev_scope = None
for point in points:
scope = view.scope_name(point)
if scope == prev_scope:
# Optimization: Avoid relatively expensive calls to
# score_selector
continue
if (sublime.score_selector(scope, section['selector']) == 0 and
(section['combining_selector'] is None or
sublime.score_selector(
scope, section['combining_selector']) == 0)):
if first_point >= second_point:
return point + 1
elif view.rowcol(point)[1] > 0:
return point
else:
# Special-case the first character of a line. In a typical
# Sublime syntax file, a line-based scope (e.g. a
# comment.line) includes the newline character at the end
# of the line. This does not seem quite proper to me, but
# in any event it necessitates this special case.
return point - 1
prev_scope = scope
return second_point
def _are_combined(self, section, first_point, second_point):
"""Return whether we can combine the specified points.
Return whether we can combine second_point with first_point in
the specified section, based on section['combining_selector']
and section['selector'], by moving from first_point to
second_point. _are_combined does not check whether first_point
matches the section (as in _point_matches_selector).
dict<str, object> section - The section, formatted like the
elements of _settings_parser.sections.
int first_point - The starting point.
int second_point - The ending point.
return bool - Whether we can combine second_point with
first_point.
"""
return (
self._combine_extent(section, first_point, second_point) ==
second_point)
def _prev_char_scope(self, point, line_region):
"""Return the scope associated with the character before "point".
Return the scope associated with the character before "point",
as in _view.scope_name, but if that is a line break character,
return None instead.
In a typical Sublime syntax file, a line-based scope (e.g. a
comment.line) includes the newline character at the end of the
line. This does not seem quite proper to me, but in any event
it requires special behavior in _matches_selector and
_point_matches_selector concerning the beginning of the line.
This is why _prev_char_scope returns None at the beginning of a
line.
int point - The point.
Region line_region - The value of _view.line(point).
return str - The scope.
"""
if point > line_region.begin():
return self._view.scope_name(point - 1)
else:
return None
def _matches_selector(self, section, prev_char_scope, next_char_scope):
"""Return whether a position with the given scopes matches "section".
Return whether a position with the specified preceding and
succeeding scopes matches "section", based on
section['selector'].
We should conceive of a match as being performed not on a
character, but on the point between two characters. See the
comments for _point_matches_selector for more information.
dict<str, object> section - The section, formatted like the
elements of _settings_parser.sections.
str prev_char_scope - The result of calling _prev_char_scope on
the position.
str next_char_scope - The scope of the succeeding character, as
returned by _view.scope_name.
return bool - Whether the position matches.
"""
return (
(prev_char_scope is not None and
sublime.score_selector(
prev_char_scope, section['selector']) > 0) or
sublime.score_selector(next_char_scope, section['selector']) > 0)
def _point_matches_selector(self, section, point, line_region):
"""Return whether the specified point matches "section".
Return whether the specified point matches "section", based on
section['selector'].
We should conceive of a match as being performed not on a
character, but on the point between two characters. For
example, in C++ block comments, a selection cursor that is
immediately before the /* is in the block comment, even though
the preceding character is not. Likewise, a selection cursor
that is immediately after the */ is in the block comment, even
though the succeeding character is not.
dict<str, object> section - The section, formatted like the
elements of _settings_parser.sections.
int point - The position.
Region line_region - The value of _view.line(point).
return bool - Whether the position matches.
"""
return self._matches_selector(
section, self._prev_char_scope(point, line_region),
self._view.scope_name(point))
def _first_line_paragraph(self, line_text):
"""Return the _settings_parser.paragraphs element matching line_text.
Return the first element in _settings_parser.paragraphs whose
"first_line_regex" entry matches the specified line, if any.
str line_text - The line's text - the contents of the line after
removing the line start and any leading and trailing
whitespace.
return dict<str, object> - The paragraph element.
"""
for paragraph in self._settings_parser.paragraphs:
if paragraph['first_line_regex'].search(line_text) is not None:
return paragraph
return None
def _paragraph_indent(self, line_text):
"""Return the relative indentation of the line after "line".
Return the indentation of the line after the specified line,
relative to the indentation of the specified line, if the
subsequent line is in the same paragraph. Return None instead
if the line is part of a single-line paragraph, as in the
"single_line" entry of elements of the
"wrap_as_you_type_paragraphs" setting.
str line_text - The line's text - the contents of the line after
removing the line start and any leading and trailing
whitespace.
return str - The indentation. This consists exclusively of
whitespace characters.
"""
for paragraph in self._settings_parser.paragraphs:
match = paragraph['first_line_regex'].search(line_text)
if match is not None:
if paragraph['single_line']:
return None
indent_group = paragraph['indent_group']
if indent_group is not None:
group = match.group(indent_group)
if group is not None:
components = []
for char in group:
components.append(' ' if char != '\t' else '\t')
return ''.join(components)
if paragraph['indent'] is not None:
return paragraph['indent']
elif paragraph['indent_levels'] is not None:
tab_size = self._view.settings().get('tab_size')
return ' ' * (tab_size * paragraph['indent_levels'])
else:
return ''
return ''
def _same_paragraph_line(
self, section, point, first_line, second_line,
first_line_region, second_line_region, line_start):
"""Determine whether the specified lines are in the same paragraph.
Determine whether the specified consecutive lines are in the
same paragraph. If so, return the text in the second line - the
result of taking that line, removing any characters that are not
in the same section as "point", removing the line start, and
then removing any leading or trailing whitespace. If not,
return None.
Note that first_line and second_line need not currently be
individual lines; they may be portions of the document that we
are considering as if they were consecutive lines.
dict<str, object> section - The current section, formatted like
the elements of _settings_parser.sections.
int point - The current position. This must be in
first_line_region or second_line_region.
str first_line - The text of the first line.
str second_line - The text of the second line.
Region first_line_region - The region containing first_line.
Region second_line_region - The region containing second_line.
str line_start - The line start.
return str - The second line's text, if it is in the same
paragraph.
"""
# Compute the lines' indents
indent = self._section_indent(first_line, line_start)
if indent is None:
return None
second_indent = self._section_indent(second_line, line_start)
if second_indent != indent:
return None
# Compute the lines' text, before applying _combine_extent
i_line_start_len = len(indent) + len(line_start)
first_line_text = first_line[i_line_start_len:].strip()
second_line_text = second_line[i_line_start_len:].strip()
if not first_line_text or not second_line_text:
return None
# Compute the lines' post-line-start indents
first_paragraph_indent = self._leading_whitespace(
first_line[i_line_start_len:])
second_paragraph_indent = self._leading_whitespace(
second_line[i_line_start_len:])
if not second_paragraph_indent.startswith(first_paragraph_indent):
return None
# Check whether the indentation of the second line is correct for a
# same-paragraph match
paragraph_indent = self._paragraph_indent(first_line_text)
if (paragraph_indent is None or
second_paragraph_indent[len(first_paragraph_indent):] !=
paragraph_indent):
return None
# If the line break between the two paragraphs was inserted by the user
# pressing the enter key, then we preserve it, by treating the second
# line as the start of a new paragraph
regions = self._view.get_regions(
'wrap_as_you_type_explicit_line_break')
for region in regions:
if (region.begin() == first_line_region.end() and
region.end() == second_line_region.begin()):
return None
# Restrict second_line_text by _combine_extent
combine_extent = self._combine_extent(
section, point,
second_line_region.begin() + i_line_start_len +
len(second_paragraph_indent) + len(second_line_text))
if (combine_extent <
second_line_region.begin() + i_line_start_len +
len(second_paragraph_indent) + 1):
# "point" does not combine with any text on the second line
return None
second_line_extent_text = second_line_text[
:combine_extent - second_line_region.begin() - i_line_start_len -
len(second_paragraph_indent)].strip()
if not second_line_extent_text:
return None
if (self._first_line_paragraph(second_line_extent_text) is not None or
not self._are_combined(
section, point, first_line_region.begin())):
return None
return second_line_extent_text
def _should_erase_preceding_line_break(
self, section, point, line_start, line, line_region, prev_line,
prev_line_region, prev_end_point_excluding_whitespace,
prev_char_scope, next_char_scope):
"""Return whether we should erase the preceding line break.
Return whether we should erase all of the text from the most
recent line break up to the selection cursor, if we are using
the specified section and line start. We also erase any
trailing whitespace on the line before the line break. Assume
that there is a single, non-empty selection cursor.
We perform such an erasure when it appears that the user is
backspacing content from before the earliest text on the current
line. To the user, the effect is like deleting the space
between the last word on the preceding line and the first word
on the current line. The purpose of the erasure is to make it
feel more like editing non-wrapped text content to the user (or
rather, like editing soft-wrapped content that doesn't have any
indentation or line start).
dict<str, object> section - The section we are attempting to
use, formatted like the elements of
_settings_parser.sections.
int point - The position of the selection cursor.
str line_start - The line start we are attempting to use.
str line - The value of _view.substr(line_region).
Region line_region - The value of _view.line(point).
str prev_line - The value of _view.substr(prev_line_region).
This is None if prev_line_region is None.
Region prev_line_region - The value of _prev_line_region(point).
int prev_end_point_excluding_whitespace - The value of
_end_point_excluding_whitespace(prev_line,
prev_line_region). This is None if prev_line is None.
str prev_char_scope - The value of
_prev_char_scope(prev_line_region.end(), prev_line_reigon).
This is None if prev_line_region is None.
str next_char_scope - The value of
_view.scope_name(prev_line_region.end()). This is None if
prev_line_region is None.
return bool - Whether we should erase the preceding line break.
"""
if (prev_line_region is None or Util.is_all_whitespace(line) or
# If line_start consists exclusively of whitespace, then the
# setting is too generic to be confident that the user
# backspaced past the beginning of a line
Util.is_all_whitespace(line_start)):
return False
# Check whether the user appears to have backspaced part of the
# indentation
indent = self._section_indent(prev_line, line_start)
if (indent is None or line.startswith(indent) or
line[:point - line_region.begin()] !=
indent[:point - line_region.begin()]):
return False
# Check whether prev_line has at least one word
if Util.is_all_whitespace(prev_line[len(indent) + len(line_start):]):
return False
# Check whether the first thing after "point" is line_start, in which
# case the user only appears to be editing the indentation
if (self._section_indent(
line[point - line_region.begin():], line_start) is not None):
return False
# Check whether prev_line.begin() and "point" are in a single section
if (not self._matches_selector(
section, prev_char_scope, next_char_scope) or
not self._are_combined(
section, prev_line_region.begin(), point)):
return False
# If the preceding line break was inserted by the user pressing the
# enter key, then preserve it
regions = self._view.get_regions(
'wrap_as_you_type_explicit_line_break')
for region in regions:
if region.begin() == prev_line_region.end():
return False
return True
def _erase_preceding_line_break_edit(self, point):
"""Return a pair with an edit for erasing the preceding line break.
Return a pair whose first element is an edit for erasing all of
the text from the most recent line break character up to the
selection cursor. This also erases any trailing whitespace on
the line before the line break. The second element of the
return value is the recommended new point - the position to
which "point" is moved after the erasure. Clients ought to
check that _should_erase_preceding_line_break returns True
before calling this method. See the comments for
_should_erase_preceding_line_break for more information
concerning the motivation of such an edit.
int point - The position.
return tuple<tuple<Region, str>, int> - A pair consisting of the
edit and the new position, respectively.
"""
# Compute the region to erase
view = self._view
line_region = view.line(point)
line = view.substr(line_region)
prev_line_region = self._prev_line_region(point)
prev_line = view.substr(prev_line_region)
erase_start_point = self._end_point_excluding_whitespace(
prev_line, prev_line_region)
erase_end_point = (
line_region.begin() + len(self._leading_whitespace(line)))
erase_region = Region(erase_start_point, erase_end_point)
# Return the edit and the new position
edit = (erase_region, '')
if point <= erase_region.begin():
return (edit, point)
elif point <= erase_region.end():
return (edit, erase_region.begin())
else:
return (edit, point - erase_region.size())
def _try_remove_indent_of_next_line_edit(self, section, point, line_start):
r"""Return an edit for removing subsequent indentation, if appropriate.
Return an edit for removing the text from "point" up to what
appears to be the end of the former i_line_start_i of the next
line, or None if we should not remove such text.
The goal here is to help the user when he presses the "delete"
key at the end of a line. For example, if the line start is
" * ", the current line of text reads, " * Foo bar * baz",
and the selection cursor is immediately after the word "bar",
then it looks as though the document used to read,
" * Foo bar\n * baz", and the user just deleted the newline
character. In this case, we erase text so that the line reads,
" * Foo barbaz" instead. The purpose of the erasure is to
make it feel more like editing non-wrapped text content to the
user (or rather, like editing soft-wrapped content that doesn't
have any indentation or line start).
dict<str, object> section - The current section, formatted like
the elements of _settings_parser.sections.
int point - The position.
str line_start - The line start.
return tuple<Region, str> - The edit, if any.
"""
line_region = self._view.line(point)
line = self._view.substr(line_region)
first_line = line[:point - line_region.begin()]
second_line = line[point - line_region.begin():]
i_line_start_i = self._i_line_start_i(second_line, line_start)
if (i_line_start_i is None or
self._leading_whitespace(i_line_start_i) in ('', ' ', ' ')):
# i_line_start_i is too generic for us to confidently guess that
# the user deleted a newline character
return None
# Check _point_matches_selector
if not self._point_matches_selector(section, point, line_region):
return None
# Check whether the "lines" are in the same paragraph
if (self._same_paragraph_line(
section, point, first_line, second_line,
Region(line_region.begin(), point),
Region(point, line_region.end()), line_start) is None):
return None
# Return the edit
erase_region = Region(point, point + len(i_line_start_i))
return (erase_region, '')
def _try_split_edit(self, section, point, line_start):
"""Return a pair containing the edit for splitting the line, if any.
Return a pair whose first element is the edit for splitting the
line containing "point", if we should do so. If the line is
longer than the wrap width, and it contains at least two words,
then we split the line after the latest word that is no later
than the wrap width (or the first word if there is no such
word), assuming the split is contained in a single section.
Note that it may take multiple split operations to reduce the
line down to lines that are all no longer than the wrap width.
The second element of the return value is the recommended new
point - the later of the position to which "point" is moved
after the split, and the position after the i_line_start_i of
the added line. This method returns (None, None) if we should
not perform a split operation. It assumes that there is a
single, empty selection cursor.
dict<str, object> section - The current section, formatted like
the elements of _settings_parser.sections.
int point - The current position.
str line_start - The line start.
return tuple<tuple<Region, str>, int> - A pair consisting of the
edit and the new position, respectively.
"""
# Compute the words on the current line
view = self._view
line_region = view.line(point)
line = view.substr(line_region)
i_line_start_i = self._i_line_start_i(line, line_start)
if i_line_start_i is None:
return (None, None)
word_spans = self._word_spans(line[len(i_line_start_i):])
if len(word_spans) <= 1:
return (None, None)
# Check whether the line is longer than the wrap width
wrap_width = self._wrap_width(section)
wrap_index = self._advance_by_width(line, wrap_width)
if wrap_index >= len(i_line_start_i) + word_spans[-1][1]:
return (None, None)
# Check whether this is a single-line paragraph
line_text = line[len(i_line_start_i):].rstrip()
paragraph = self._first_line_paragraph(line_text)
if paragraph is not None and paragraph['single_line']:
return (None, None)
# Compute the last word on this line and the first word on the next
# line, post-split
last_word_span = None
first_word_span = None
if len(i_line_start_i) + word_spans[0][1] > wrap_index:
# The first word does not fit on one line
last_word_span = word_spans[0]
first_word_span = word_spans[1]
else:
for span in word_spans:
if len(i_line_start_i) + span[1] <= wrap_index:
last_word_span = span
else:
first_word_span = span
break
last_word_region = Region(
line_region.begin() + len(i_line_start_i) + last_word_span[0],
line_region.begin() + len(i_line_start_i) + last_word_span[1])
first_word_region = Region(
line_region.begin() + len(i_line_start_i) + first_word_span[0],
line_region.begin() + len(i_line_start_i) + first_word_span[1])
# Check whether "point" is in the same section as
# first_word_region.end() and line_region.begin()
if (not self._point_matches_selector(section, point, line_region) or
not self._are_combined(
section, point, first_word_region.end()) or
not self._are_combined(section, point, line_region.begin())):
return (None, None)
# Compute the edit
selection_point = self._selection_point()