robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. KeyesMerge #40924 from justinmk/optdicte533ec5160

master
50.4 KiB1791 linesraw
1// textobject.c: functions for text objects
2
3#include <stdbool.h>
4#include <stdint.h>
5#include <stdio.h>
6#include <string.h>
7
8#include "nvim/ascii_defs.h"
9#include "nvim/buffer_defs.h"
10#include "nvim/charset.h"
11#include "nvim/cursor.h"
12#include "nvim/drawscreen.h"
13#include "nvim/eval/funcs.h"
14#include "nvim/fold.h"
15#include "nvim/globals.h"
16#include "nvim/indent.h"
17#include "nvim/insert.h"
18#include "nvim/mark.h"
19#include "nvim/mark_defs.h"
20#include "nvim/mbyte.h"
21#include "nvim/memline.h"
22#include "nvim/memory.h"
23#include "nvim/move.h"
24#include "nvim/normal.h"
25#include "nvim/option_vars.h"
26#include "nvim/pos_defs.h"
27#include "nvim/search.h"
28#include "nvim/strings.h"
29#include "nvim/textobject.h"
30#include "nvim/vim_defs.h"
31
32#include "textobject.c.generated.h"
33
34/// Find the start of the next sentence, searching in the direction specified
35/// by the "dir" argument.  The cursor is positioned on the start of the next
36/// sentence when found.  If the next sentence is found, return OK.  Return FAIL
37/// otherwise.  See ":h sentence" for the precise definition of a "sentence"
38/// text object.
39int findsent(Direction dir, int count)
40{
41  int c;
42  int (*func)(pos_T *);
43  bool noskip = false;              // do not skip blanks
44
45  pos_T pos = curwin->w_cursor;
46  if (dir == FORWARD) {
47    func = incl;
48  } else {
49    func = decl;
50  }
51
52  while (count--) {
53    const pos_T prev_pos = pos;
54
55    // if on an empty line, skip up to a non-empty line
56    if (gchar_pos(&pos) == NUL) {
57      do {
58        if ((*func)(&pos) == -1) {
59          break;
60        }
61      } while (gchar_pos(&pos) == NUL);
62      if (dir == FORWARD) {
63        goto found;
64      }
65      // if on the start of a paragraph or a section and searching forward,
66      // go to the next line
67    } else if (dir == FORWARD && pos.col == 0
68               && startPS(pos.lnum, NUL, false)) {
69      if (pos.lnum == curbuf->b_ml.ml_line_count) {
70        return FAIL;
71      }
72      pos.lnum++;
73      goto found;
74    } else if (dir == BACKWARD) {
75      decl(&pos);
76    }
77
78    // go back to the previous non-white non-punctuation character
79    bool found_dot = false;
80    while (c = gchar_pos(&pos), ascii_iswhite(c)
81           || vim_strchr(".!?)]\"'", c) != NULL) {
82      pos_T tpos = pos;
83      if (decl(&tpos) == -1 || (LINEEMPTY(tpos.lnum) && dir == FORWARD)) {
84        break;
85      }
86      if (found_dot) {
87        break;
88      }
89      if (vim_strchr(".!?", c) != NULL) {
90        found_dot = true;
91      }
92      if (vim_strchr(")]\"'", c) != NULL
93          && vim_strchr(".!?)]\"'", gchar_pos(&tpos)) == NULL) {
94        break;
95      }
96      decl(&pos);
97    }
98
99    // remember the line where the search started
100    const int startlnum = pos.lnum;
101    const bool cpo_J = vim_strchr(p_cpo, kCpoEndofsent) != NULL;
102
103    while (true) {              // find end of sentence
104      c = gchar_pos(&pos);
105      if (c == NUL || (pos.col == 0 && startPS(pos.lnum, NUL, false))) {
106        if (dir == BACKWARD && pos.lnum != startlnum) {
107          pos.lnum++;
108        }
109        break;
110      }
111      if (c == '.' || c == '!' || c == '?') {
112        pos_T tpos = pos;
113        do {
114          if ((c = inc(&tpos)) == -1) {
115            break;
116          }
117        } while (vim_strchr(")]\"'", c = gchar_pos(&tpos))
118                 != NULL);
119        if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL
120            || (cpo_J && (c == ' ' && inc(&tpos) >= 0
121                          && gchar_pos(&tpos) == ' '))) {
122          pos = tpos;
123          if (gchar_pos(&pos) == NUL) {         // skip NUL at EOL
124            inc(&pos);
125          }
126          break;
127        }
128      }
129      if ((*func)(&pos) == -1) {
130        if (count) {
131          return FAIL;
132        }
133        noskip = true;
134        break;
135      }
136    }
137found:
138    // skip white space
139    while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t')) {
140      if (incl(&pos) == -1) {
141        break;
142      }
143    }
144
145    if (equalpos(prev_pos, pos)) {
146      // didn't actually move, advance one character and try again
147      if ((*func)(&pos) == -1) {
148        if (count) {
149          return FAIL;
150        }
151        break;
152      }
153      count++;
154    }
155  }
156
157  setpcmark();
158  curwin->w_cursor = pos;
159  return OK;
160}
161
162/// Find the next paragraph or section in direction 'dir'.
163/// Paragraphs are currently supposed to be separated by empty lines.
164/// If 'what' is NUL we go to the next paragraph.
165/// If 'what' is '{' or '}' we go to the next section.
166/// If 'both' is true also stop at '}'.
167///
168/// @param pincl  Return: true if last char is to be included
169///
170/// @return       true if the next paragraph or section was found.
171bool findpar(bool *pincl, int dir, int count, int what, bool both)
172{
173  bool first;               // true on first line
174  linenr_T fold_first;      // first line of a closed fold
175  linenr_T fold_last;       // last line of a closed fold
176  bool fold_skipped;        // true if a closed fold was skipped this
177                            // iteration
178
179  linenr_T curr = curwin->w_cursor.lnum;
180
181  while (count--) {
182    bool did_skip = false;  // true after separating lines have been skipped
183    for (first = true;; first = false) {
184      if (*ml_get(curr) != NUL) {
185        did_skip = true;
186      }
187
188      // skip folded lines
189      fold_skipped = false;
190      if (first && hasFolding(curwin, curr, &fold_first, &fold_last)) {
191        curr = ((dir > 0) ? fold_last : fold_first) + dir;
192        fold_skipped = true;
193      }
194
195      if (!first && did_skip && startPS(curr, what, both)) {
196        break;
197      }
198
199      if (fold_skipped) {
200        curr -= dir;
201      }
202      if ((curr += dir) < 1 || curr > curbuf->b_ml.ml_line_count) {
203        if (count) {
204          return false;
205        }
206        curr -= dir;
207        break;
208      }
209    }
210  }
211  setpcmark();
212  if (both && *ml_get(curr) == '}') {   // include line with '}'
213    curr++;
214  }
215  curwin->w_cursor.lnum = curr;
216  if (curr == curbuf->b_ml.ml_line_count && what != '}' && dir == FORWARD) {
217    char *line = ml_get(curr);
218
219    // Put the cursor on the last character in the last line and make the
220    // motion inclusive.
221    if ((curwin->w_cursor.col = ml_get_len(curr)) != 0) {
222      curwin->w_cursor.col--;
223      curwin->w_cursor.col -= utf_head_off(line, line + curwin->w_cursor.col);
224      *pincl = true;
225    }
226  } else {
227    curwin->w_cursor.col = 0;
228  }
229  return true;
230}
231
232/// check if the string 's' is a nroff macro that is in option 'opt'
233static bool inmacro(char *opt, const char *s)
234{
235  char *macro;
236
237  for (macro = opt; macro[0]; macro++) {
238    // Accept two characters in the option being equal to two characters
239    // in the line.  A space in the option matches with a space in the
240    // line or the line having ended.
241    if ((macro[0] == s[0]
242         || (macro[0] == ' '
243             && (s[0] == NUL || s[0] == ' ')))
244        && (macro[1] == s[1]
245            || ((macro[1] == NUL || macro[1] == ' ')
246                && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) {
247      break;
248    }
249    macro++;
250    if (macro[0] == NUL) {
251      break;
252    }
253  }
254  return macro[0] != NUL;
255}
256
257/// startPS: return true if line 'lnum' is the start of a section or paragraph.
258/// If 'para' is '{' or '}' only check for sections.
259/// If 'both' is true also stop at '}'
260bool startPS(linenr_T lnum, int para, bool both)
261{
262  char *s = ml_get(lnum);
263  if ((uint8_t)(*s) == para || *s == '\f' || (both && *s == '}')) {
264    return true;
265  }
266  if (*s == '.' && (inmacro(p_sections, s + 1)
267                    || (!para && inmacro(p_para, s + 1)))) {
268    return true;
269  }
270  return false;
271}
272
273// The following routines do the word searches performed by the 'w', 'W',
274// 'b', 'B', 'e', and 'E' commands.
275
276// To perform these searches, characters are placed into one of three
277// classes, and transitions between classes determine word boundaries.
278//
279// The classes are:
280//
281// 0 - white space
282// 1 - punctuation
283// 2 or higher - keyword characters (letters, digits and underscore)
284
285static bool cls_bigword;  ///< true for "W", "B" or "E"
286
287/// cls() - returns the class of character at curwin->w_cursor
288///
289/// If a 'W', 'B', or 'E' motion is being done (cls_bigword == true), chars
290/// from class 2 and higher are reported as class 1 since only white space
291/// boundaries are of interest.
292static int cls(void)
293{
294  int c = gchar_cursor();
295  if (c == ' ' || c == '\t' || c == NUL) {
296    return 0;
297  }
298
299  c = utf_class(c);
300
301  // If cls_bigword is true, report all non-blanks as class 1.
302  if (c != 0 && cls_bigword) {
303    return 1;
304  }
305  return c;
306}
307
308/// fwd_word(count, type, eol) - move forward one word
309///
310/// @return  FAIL if the cursor was already at the end of the file.
311/// If eol is true, last word stops at end of line (for operators).
312///
313/// @param bigword  "W", "E" or "B"
314int fwd_word(int count, bool bigword, bool eol)
315{
316  curwin->w_cursor.coladd = 0;
317  cls_bigword = bigword;
318  while (--count >= 0) {
319    // When inside a range of folded lines, move to the last char of the
320    // last line.
321    if (hasFolding(curwin, curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum)) {
322      coladvance(curwin, MAXCOL);
323    }
324    int sclass = cls();  // starting class
325
326    // We always move at least one character, unless on the last
327    // character in the buffer.
328    int last_line = (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count);
329    int i = inc_cursor();
330    if (i == -1 || (i >= 1 && last_line)) {   // started at last char in file
331      return FAIL;
332    }
333    if (i >= 1 && eol && count == 0) {        // started at last char in line
334      return OK;
335    }
336
337    // Go one char past end of current word (if any)
338    if (sclass != 0) {
339      while (cls() == sclass) {
340        i = inc_cursor();
341        if (i == -1 || (i >= 1 && eol && count == 0)) {
342          return OK;
343        }
344      }
345    }
346
347    // go to next non-white
348    while (cls() == 0) {
349      // We'll stop if we land on a blank line
350      if (curwin->w_cursor.col == 0 && *get_cursor_line_ptr() == NUL) {
351        break;
352      }
353
354      i = inc_cursor();
355      if (i == -1 || (i >= 1 && eol && count == 0)) {
356        return OK;
357      }
358    }
359  }
360  return OK;
361}
362
363/// bck_word() - move backward 'count' words
364///
365/// If stop is true and we are already on the start of a word, move one less.
366///
367/// Returns FAIL if top of the file was reached.
368int bck_word(int count, bool bigword, bool stop)
369{
370  int sclass;               // starting class
371
372  curwin->w_cursor.coladd = 0;
373  cls_bigword = bigword;
374  while (--count >= 0) {
375    // When inside a range of folded lines, move to the first char of the
376    // first line.
377    if (hasFolding(curwin, curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) {
378      curwin->w_cursor.col = 0;
379    }
380    sclass = cls();
381    if (dec_cursor() == -1) {           // started at start of file
382      return FAIL;
383    }
384
385    if (!stop || sclass == cls() || sclass == 0) {
386      // Skip white space before the word.
387      // Stop on an empty line.
388      while (cls() == 0) {
389        if (curwin->w_cursor.col == 0
390            && LINEEMPTY(curwin->w_cursor.lnum)) {
391          goto finished;
392        }
393        if (dec_cursor() == -1) {       // hit start of file, stop here
394          return OK;
395        }
396      }
397
398      // Move backward to start of this word.
399      if (skip_chars(cls(), BACKWARD)) {
400        return OK;
401      }
402    }
403
404    inc_cursor();                       // overshot - forward one
405finished:
406    stop = false;
407  }
408  adjust_skipcol();
409  return OK;
410}
411
412/// end_word() - move to the end of the word
413///
414/// There is an apparent bug in the 'e' motion of the real vi. At least on the
415/// System V Release 3 version for the 80386. Unlike 'b' and 'w', the 'e'
416/// motion crosses blank lines. When the real vi crosses a blank line in an
417/// 'e' motion, the cursor is placed on the FIRST character of the next
418/// non-blank line. The 'E' command, however, works correctly. Since this
419/// appears to be a bug, I have not duplicated it here.
420///
421/// Returns FAIL if end of the file was reached.
422///
423/// If stop is true and we are already on the end of a word, move one less.
424/// If empty is true stop on an empty line.
425int end_word(int count, bool bigword, bool stop, bool empty)
426{
427  int sclass;               // starting class
428
429  curwin->w_cursor.coladd = 0;
430  cls_bigword = bigword;
431
432  // If adjusted cursor position previously, unadjust it.
433  if (*p_sel == 'e' && Visual.active && Visual.mode == 'v'
434      && Visual.select_exclu_adj) {
435    unadjust_for_sel();
436  }
437
438  while (--count >= 0) {
439    // When inside a range of folded lines, move to the last char of the
440    // last line.
441    if (hasFolding(curwin, curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum)) {
442      coladvance(curwin, MAXCOL);
443    }
444    sclass = cls();
445    if (inc_cursor() == -1) {
446      return FAIL;
447    }
448
449    // If we're in the middle of a word, we just have to move to the end
450    // of it.
451    if (cls() == sclass && sclass != 0) {
452      // Move forward to end of the current word
453      if (skip_chars(sclass, FORWARD)) {
454        return FAIL;
455      }
456    } else if (!stop || sclass == 0) {
457      // We were at the end of a word. Go to the end of the next word.
458      // First skip white space, if 'empty' is true, stop at empty line.
459      while (cls() == 0) {
460        if (empty && curwin->w_cursor.col == 0
461            && LINEEMPTY(curwin->w_cursor.lnum)) {
462          goto finished;
463        }
464        if (inc_cursor() == -1) {           // hit end of file, stop here
465          return FAIL;
466        }
467      }
468
469      // Move forward to the end of this word.
470      if (skip_chars(cls(), FORWARD)) {
471        return FAIL;
472      }
473    }
474    dec_cursor();                       // overshot - one char backward
475finished:
476    stop = false;                       // we move only one word less
477  }
478  return OK;
479}
480
481/// Move back to the end of the word.
482///
483/// @param bigword  true for "B"
484/// @param eol      if true, then stop at end of line.
485///
486/// @return         FAIL if start of the file was reached.
487int bckend_word(int count, bool bigword, bool eol)
488{
489  curwin->w_cursor.coladd = 0;
490  cls_bigword = bigword;
491  while (--count >= 0) {
492    int i;
493    int sclass = cls();  // starting class
494    if ((i = dec_cursor()) == -1) {
495      return FAIL;
496    }
497    if (eol && i == 1) {
498      return OK;
499    }
500
501    // Move backward to before the start of this word.
502    if (sclass != 0) {
503      while (cls() == sclass) {
504        if ((i = dec_cursor()) == -1 || (eol && i == 1)) {
505          return OK;
506        }
507      }
508    }
509
510    // Move backward to end of the previous word
511    while (cls() == 0) {
512      if (curwin->w_cursor.col == 0 && LINEEMPTY(curwin->w_cursor.lnum)) {
513        break;
514      }
515      if ((i = dec_cursor()) == -1 || (eol && i == 1)) {
516        return OK;
517      }
518    }
519  }
520  adjust_skipcol();
521  return OK;
522}
523
524/// Skip a row of characters of the same class.
525///
526/// @return  true when end-of-file reached, false otherwise.
527static bool skip_chars(int cclass, int dir)
528{
529  while (cls() == cclass) {
530    if ((dir == FORWARD ? inc_cursor() : dec_cursor()) == -1) {
531      return true;
532    }
533  }
534  return false;
535}
536
537/// Go back to the start of the word or the start of white space
538static void back_in_line(void)
539{
540  int sclass = cls();  // starting class
541  while (true) {
542    if (curwin->w_cursor.col == 0) {        // stop at start of line
543      break;
544    }
545    dec_cursor();
546    if (cls() != sclass) {                  // stop at start of word
547      inc_cursor();
548      break;
549    }
550  }
551}
552
553static void find_first_blank(pos_T *posp)
554{
555  while (decl(posp) != -1) {
556    int c = gchar_pos(posp);
557    if (!ascii_iswhite(c)) {
558      incl(posp);
559      break;
560    }
561  }
562}
563
564/// Skip count/2 sentences and count/2 separating white spaces.
565///
566/// @param at_start_sent  cursor is at start of sentence
567static void findsent_forward(int count, bool at_start_sent)
568{
569  while (count--) {
570    findsent(FORWARD, 1);
571    if (at_start_sent) {
572      find_first_blank(&curwin->w_cursor);
573    }
574    if (count == 0 || at_start_sent) {
575      decl(&curwin->w_cursor);
576    }
577    at_start_sent = !at_start_sent;
578  }
579}
580
581/// Find word under cursor, cursor at end.
582/// Used while an operator is pending, and in Visual mode.
583///
584/// @param include  true: include word and white space
585/// @param bigword  false == word, true == WORD
586int current_word(oparg_T *oap, int count, bool include, bool bigword)
587{
588  pos_T start_pos;
589  bool inclusive = true;
590  bool include_white = false;
591
592  cls_bigword = bigword;
593  clearpos(&start_pos);
594
595  // Correct cursor when 'selection' is exclusive
596  if (Visual.active && *p_sel == 'e' && lt(Visual.start, curwin->w_cursor)) {
597    dec_cursor();
598  }
599
600  // When Visual mode is not active, or when the Visual area is only one
601  // character, select the word and/or white space under the cursor.
602  if (!Visual.active || equalpos(curwin->w_cursor, Visual.start)) {
603    // Go to start of current word or white space.
604    back_in_line();
605    start_pos = curwin->w_cursor;
606
607    // If the start is on white space, and white space should be included
608    // (" word"), or start is not on white space, and white space should
609    // not be included ("word"), find end of word.
610    if ((cls() == 0) == include) {
611      if (end_word(1, bigword, true, true) == FAIL) {
612        return FAIL;
613      }
614    } else {
615      // If the start is not on white space, and white space should be
616      // included ("word   "), or start is on white space and white
617      // space should not be included ("   "), find start of word.
618      // If we end up in the first column of the next line (single char
619      // word) back up to end of the line.
620      fwd_word(1, bigword, true);
621      if (curwin->w_cursor.col == 0) {
622        decl(&curwin->w_cursor);
623      } else {
624        oneleft();
625      }
626
627      if (include) {
628        include_white = true;
629      }
630    }
631
632    if (Visual.active) {
633      // should do something when inclusive == false !
634      Visual.start = start_pos;
635      redraw_curbuf_later(UPD_INVERTED);  // update the inversion
636    } else {
637      oap->start = start_pos;
638      oap->motion_type = kMTCharWise;
639    }
640    count--;
641  }
642
643  // When count is still > 0, extend with more objects.
644  while (count > 0) {
645    inclusive = true;
646    if (Visual.active && lt(curwin->w_cursor, Visual.start)) {
647      // In Visual mode, with cursor at start: move cursor back.
648      if (decl(&curwin->w_cursor) == -1) {
649        return FAIL;
650      }
651      if (include != (cls() != 0)) {
652        if (bck_word(1, bigword, true) == FAIL) {
653          return FAIL;
654        }
655      } else {
656        if (bckend_word(1, bigword, true) == FAIL) {
657          return FAIL;
658        }
659        (void)incl(&curwin->w_cursor);
660      }
661    } else {
662      // Move cursor forward one word and/or white area.
663      if (incl(&curwin->w_cursor) == -1) {
664        return FAIL;
665      }
666      if (include != (cls() == 0)) {
667        if (fwd_word(1, bigword, true) == FAIL && count > 1) {
668          return FAIL;
669        }
670        // If end is just past a new-line, we don't want to include
671        // the first character on the line.
672        // Put cursor on last char of white.
673        if (oneleft() == FAIL) {
674          inclusive = false;
675        }
676      } else {
677        if (end_word(1, bigword, true, true) == FAIL) {
678          return FAIL;
679        }
680      }
681    }
682    count--;
683  }
684
685  if (include_white && (cls() != 0
686                        || (curwin->w_cursor.col == 0 && !inclusive))) {
687    // If we don't include white space at the end, move the start
688    // to include some white space there. This makes "daw" work
689    // better on the last word in a sentence (and "2daw" on last-but-one
690    // word).  Also when "2daw" deletes "word." at the end of the line
691    // (cursor is at start of next line).
692    // But don't delete white space at start of line (indent).
693    pos_T pos = curwin->w_cursor;     // save cursor position
694    curwin->w_cursor = start_pos;
695    if (oneleft() == OK) {
696      back_in_line();
697      if (cls() == 0 && curwin->w_cursor.col > 0) {
698        if (Visual.active) {
699          Visual.start = curwin->w_cursor;
700        } else {
701          oap->start = curwin->w_cursor;
702        }
703      }
704    }
705    curwin->w_cursor = pos;     // put cursor back at end
706  }
707
708  if (Visual.active) {
709    if (*p_sel == 'e' && inclusive && ltoreq(Visual.start, curwin->w_cursor)) {
710      inc_cursor();
711    }
712    if (Visual.mode == 'V') {
713      Visual.mode = 'v';
714      redraw_cmdline = true;                    // show mode later
715    }
716  } else {
717    oap->inclusive = inclusive;
718  }
719
720  return OK;
721}
722
723/// Find the current line ("il") or all lines ("al").
724///
725/// @param include  true: all lines, false: current line without surrounding
726///                 white space
727int current_line(oparg_T *oap, bool include)
728{
729  if (include) {
730    if (Visual.active) {
731      Visual.start.lnum = 1;
732      Visual.start.col = 0;
733      Visual.start.coladd = 0;
734      Visual.mode = 'V';
735      redraw_curbuf_later(UPD_INVERTED);
736      showmode();
737    } else {
738      oap->cursor_start = curwin->w_cursor;
739      oap->restore_cursor = true;
740      oap->start.lnum = 1;
741      oap->start.col = 0;
742      oap->start.coladd = 0;
743      oap->motion_type = kMTLineWise;
744    }
745    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
746    curwin->w_cursor.col = 0;
747    curwin->w_cursor.coladd = 0;
748    return OK;
749  }
750
751  char *line = ml_get(curwin->w_cursor.lnum);
752  char *start = skipwhite(line);
753  char *end = line + strlen(line);
754  while (end > start) {
755    char *prev = mb_prevptr(line, end);
756    if (!ascii_iswhite((uint8_t)(*prev))) {
757      break;
758    }
759    end = prev;
760  }
761  if (start == end) {
762    return FAIL;
763  }
764
765  pos_T start_pos = curwin->w_cursor;
766  start_pos.col = (colnr_T)(start - line);
767  start_pos.coladd = 0;
768
769  pos_T end_pos = curwin->w_cursor;
770  end_pos.col = (colnr_T)(mb_prevptr(line, end) - line);
771  end_pos.coladd = 0;
772
773  if (Visual.active) {
774    Visual.start = start_pos;
775    curwin->w_cursor = end_pos;
776    if (*p_sel == 'e' && ltoreq(Visual.start, curwin->w_cursor)) {
777      inc_cursor();
778    }
779    Visual.mode = 'v';
780    redraw_curbuf_later(UPD_INVERTED);
781    showmode();
782  } else {
783    oap->start = start_pos;
784    oap->motion_type = kMTCharWise;
785    oap->inclusive = true;
786    curwin->w_cursor = end_pos;
787  }
788
789  return OK;
790}
791
792/// Find sentence(s) under the cursor, cursor at end.
793/// When Visual active, extend it by one or more sentences.
794int current_sent(oparg_T *oap, int count, bool include)
795{
796  bool start_blank;
797  int c;
798  bool at_start_sent;
799  int ncount;
800
801  pos_T start_pos = curwin->w_cursor;
802  pos_T pos = start_pos;
803  findsent(FORWARD, 1);        // Find start of next sentence.
804
805  // When the Visual area is bigger than one character: Extend it.
806  if (Visual.active && !equalpos(start_pos, Visual.start)) {
807extend:
808    if (lt(start_pos, Visual.start)) {
809      // Cursor at start of Visual area.
810      // Find out where we are:
811      // - in the white space before a sentence
812      // - in a sentence or just after it
813      // - at the start of a sentence
814      at_start_sent = true;
815      decl(&pos);
816      while (lt(pos, curwin->w_cursor)) {
817        c = gchar_pos(&pos);
818        if (!ascii_iswhite(c)) {
819          at_start_sent = false;
820          break;
821        }
822        incl(&pos);
823      }
824      if (!at_start_sent) {
825        findsent(BACKWARD, 1);
826        if (equalpos(curwin->w_cursor, start_pos)) {
827          at_start_sent = true;            // exactly at start of sentence
828        } else {
829          // inside a sentence, go to its end (start of next)
830          findsent(FORWARD, 1);
831        }
832      }
833      if (include) {            // "as" gets twice as much as "is"
834        count *= 2;
835      }
836      while (count--) {
837        if (at_start_sent) {
838          find_first_blank(&curwin->w_cursor);
839        }
840        c = gchar_cursor();
841        if (!at_start_sent || (!include && !ascii_iswhite(c))) {
842          findsent(BACKWARD, 1);
843        }
844        at_start_sent = !at_start_sent;
845      }
846    } else {
847      // Cursor at end of Visual area.
848      // Find out where we are:
849      // - just before a sentence
850      // - just before or in the white space before a sentence
851      // - in a sentence
852      incl(&pos);
853      at_start_sent = true;
854      if (!equalpos(pos, curwin->w_cursor)) {     // not just before a sentence
855        at_start_sent = false;
856        while (lt(pos, curwin->w_cursor)) {
857          c = gchar_pos(&pos);
858          if (!ascii_iswhite(c)) {
859            at_start_sent = true;
860            break;
861          }
862          incl(&pos);
863        }
864        if (at_start_sent) {            // in the sentence
865          findsent(BACKWARD, 1);
866        } else {  // in/before white before a sentence
867          curwin->w_cursor = start_pos;
868        }
869      }
870
871      if (include) {            // "as" gets twice as much as "is"
872        count *= 2;
873      }
874      findsent_forward(count, at_start_sent);
875      if (*p_sel == 'e') {
876        curwin->w_cursor.col++;
877      }
878    }
879    return OK;
880  }
881
882  // If the cursor started on a blank, check if it is just before the start
883  // of the next sentence.
884  while (c = gchar_pos(&pos), ascii_iswhite(c)) {
885    incl(&pos);
886  }
887  if (equalpos(pos, curwin->w_cursor)) {
888    start_blank = true;
889    find_first_blank(&start_pos);       // go back to first blank
890  } else {
891    start_blank = false;
892    findsent(BACKWARD, 1);
893    start_pos = curwin->w_cursor;
894  }
895  if (include) {
896    ncount = count * 2;
897  } else {
898    ncount = count;
899    if (start_blank) {
900      ncount--;
901    }
902  }
903  if (ncount > 0) {
904    findsent_forward(ncount, true);
905  } else {
906    decl(&curwin->w_cursor);
907  }
908
909  if (include) {
910    // If the blank in front of the sentence is included, exclude the
911    // blanks at the end of the sentence, go back to the first blank.
912    // If there are no trailing blanks, try to include leading blanks.
913    if (start_blank) {
914      find_first_blank(&curwin->w_cursor);
915      c = gchar_pos(&curwin->w_cursor);
916      if (ascii_iswhite(c)) {
917        decl(&curwin->w_cursor);
918      }
919    } else if (c = gchar_cursor(), !ascii_iswhite(c)) {
920      find_first_blank(&start_pos);
921    }
922  }
923
924  if (Visual.active) {
925    // Avoid getting stuck with "is" on a single space before a sentence.
926    if (equalpos(start_pos, curwin->w_cursor)) {
927      goto extend;
928    }
929    if (*p_sel == 'e') {
930      curwin->w_cursor.col++;
931    }
932    Visual.start = start_pos;
933    Visual.mode = 'v';
934    redraw_cmdline = true;    // show mode later
935    redraw_curbuf_later(UPD_INVERTED);  // update the inversion
936  } else {
937    // include a newline after the sentence, if there is one
938    if (incl(&curwin->w_cursor) == -1) {
939      oap->inclusive = true;
940    } else {
941      oap->inclusive = false;
942    }
943    oap->start = start_pos;
944    oap->motion_type = kMTCharWise;
945  }
946  return OK;
947}
948
949/// Find block under the cursor, cursor at end.
950/// "what" and "other" are two matching parenthesis/brace/etc.
951///
952/// @param include  true == include white space
953/// @param what     '(', '{', etc.
954/// @param other    ')', '}', etc.
955int current_block(oparg_T *oap, int count, bool include, int what, int other)
956{
957  pos_T *pos = NULL;
958  pos_T start_pos;
959  pos_T *end_pos;
960  bool sol = false;                      // '{' at start of line
961
962  pos_T old_pos = curwin->w_cursor;
963  pos_T old_end = curwin->w_cursor;           // remember where we started
964  pos_T old_start = old_end;
965
966  // If we start on '(', '{', ')', '}', etc., use the whole block inclusive.
967  if (!Visual.active || equalpos(Visual.start, curwin->w_cursor)) {
968    setpcmark();
969    if (what == '{') {                  // ignore indent
970      while (inindent(1)) {
971        if (inc_cursor() != 0) {
972          break;
973        }
974      }
975    }
976    if (gchar_cursor() == what) {
977      // cursor on '(' or '{', move cursor just after it
978      curwin->w_cursor.col++;
979    }
980  } else if (lt(Visual.start, curwin->w_cursor)) {
981    old_start = Visual.start;
982    curwin->w_cursor = Visual.start;              // cursor at low end of Visual
983  } else {
984    old_end = Visual.start;
985  }
986
987  // Search backwards for unclosed '(', '{', etc..
988  // Put this position in start_pos.
989  // Ignore quotes here.  Keep the "M" flag in 'cpo', as that is what the
990  // user wants.
991  char *save_cpo = p_cpo;
992  p_cpo = vim_strchr(p_cpo, kCpoMatchbsl) != NULL ? "%M" : "%";
993  if ((pos = findmatch(NULL, what)) != NULL) {
994    while (count-- > 0) {
995      if ((pos = findmatch(NULL, what)) == NULL) {
996        break;
997      }
998      curwin->w_cursor = *pos;
999      start_pos = *pos;   // the findmatch for end_pos will overwrite *pos
1000    }
1001  } else {
1002    while (count-- > 0) {
1003      if ((pos = findmatchlimit(NULL, what, FM_FORWARD, 0)) == NULL) {
1004        break;
1005      }
1006      curwin->w_cursor = *pos;
1007      start_pos = *pos;   // the findmatch for end_pos will overwrite *pos
1008    }
1009  }
1010  p_cpo = save_cpo;
1011
1012  // Search for matching ')', '}', etc.
1013  // Put this position in curwin->w_cursor.
1014  if (pos == NULL || (end_pos = findmatch(NULL, other)) == NULL) {
1015    curwin->w_cursor = old_pos;
1016    return FAIL;
1017  }
1018  curwin->w_cursor = *end_pos;
1019
1020  // Try to exclude the '(', '{', ')', '}', etc. when "include" is false.
1021  // If the ending '}', ')' or ']' is only preceded by indent, skip that
1022  // indent. But only if the resulting area is not smaller than what we
1023  // started with.
1024  while (!include) {
1025    incl(&start_pos);
1026    sol = (curwin->w_cursor.col == 0);
1027    decl(&curwin->w_cursor);
1028    while (inindent(1)) {
1029      sol = true;
1030      if (decl(&curwin->w_cursor) != 0) {
1031        break;
1032      }
1033    }
1034
1035    // In Visual mode, when resulting area is empty
1036    // i.e. there is no inner block to select, abort.
1037    if (equalpos(start_pos, *end_pos) && Visual.active) {
1038      curwin->w_cursor = old_pos;
1039      return FAIL;
1040    }
1041
1042    // In Visual mode, when the resulting area is not bigger than what we
1043    // started with, extend it to the next block, and then exclude again.
1044    // Don't try to expand the area if the area is empty.
1045    if (!lt(start_pos, old_start) && !lt(old_end, curwin->w_cursor)
1046        && !equalpos(start_pos, curwin->w_cursor)
1047        && Visual.active) {
1048      curwin->w_cursor = old_start;
1049      decl(&curwin->w_cursor);
1050      if ((pos = findmatch(NULL, what)) == NULL) {
1051        curwin->w_cursor = old_pos;
1052        return FAIL;
1053      }
1054      start_pos = *pos;
1055      curwin->w_cursor = *pos;
1056      if ((end_pos = findmatch(NULL, other)) == NULL) {
1057        curwin->w_cursor = old_pos;
1058        return FAIL;
1059      }
1060      curwin->w_cursor = *end_pos;
1061    } else {
1062      break;
1063    }
1064  }
1065
1066  if (Visual.active) {
1067    if (*p_sel == 'e') {
1068      inc(&curwin->w_cursor);
1069    }
1070    if (sol && gchar_cursor() != NUL) {
1071      inc(&curwin->w_cursor);  // include the line break
1072    }
1073    Visual.start = start_pos;
1074    Visual.mode = 'v';
1075    redraw_curbuf_later(UPD_INVERTED);  // update the inversion
1076    showmode();
1077  } else {
1078    oap->start = start_pos;
1079    oap->motion_type = kMTCharWise;
1080    oap->inclusive = false;
1081    if (sol) {
1082      incl(&curwin->w_cursor);
1083    } else if (ltoreq(start_pos, curwin->w_cursor)) {
1084      // Include the character under the cursor.
1085      oap->inclusive = true;
1086    } else {
1087      // End is before the start (no text in between <>, [], etc.): don't
1088      // operate on any text.
1089      curwin->w_cursor = start_pos;
1090    }
1091  }
1092
1093  return OK;
1094}
1095
1096/// @param end_tag  when true, return true if the cursor is on "</aaa>".
1097///
1098/// @return         true if the cursor is on a "<aaa>" tag.  Ignore "<aaa/>".
1099static bool in_html_tag(bool end_tag)
1100{
1101  char *line = get_cursor_line_ptr();
1102  char *p;
1103  int lc = NUL;
1104  pos_T pos;
1105
1106  for (p = line + curwin->w_cursor.col; p > line;) {
1107    if (*p == '<') {           // find '<' under/before cursor
1108      break;
1109    }
1110    MB_PTR_BACK(line, p);
1111    if (*p == '>') {           // find '>' before cursor
1112      break;
1113    }
1114  }
1115  if (*p != '<') {
1116    return false;
1117  }
1118
1119  pos.lnum = curwin->w_cursor.lnum;
1120  pos.col = (colnr_T)(p - line);
1121
1122  MB_PTR_ADV(p);
1123  if (end_tag) {
1124    // check that there is a '/' after the '<'
1125    return *p == '/';
1126  }
1127
1128  // check that there is no '/' after the '<'
1129  if (*p == '/') {
1130    return false;
1131  }
1132
1133  // check that the matching '>' is not preceded by '/'
1134  while (true) {
1135    if (inc(&pos) < 0) {
1136      return false;
1137    }
1138    int c = (uint8_t)(*ml_get_pos(&pos));
1139    if (c == '>') {
1140      break;
1141    }
1142    lc = c;
1143  }
1144  return lc != '/';
1145}
1146
1147/// Find tag block under the cursor, cursor at end.
1148///
1149/// @param include  true == include white space
1150int current_tagblock(oparg_T *oap, int count_arg, bool include)
1151{
1152  int count = count_arg;
1153  char *cp;
1154  bool do_include = include;
1155  bool save_p_ws = p_ws;
1156  int retval = FAIL;
1157  bool is_inclusive = true;
1158
1159  p_ws = false;
1160
1161  pos_T old_pos = curwin->w_cursor;
1162  pos_T old_end = curwin->w_cursor;               // remember where we started
1163  pos_T old_start = old_end;
1164  if (!Visual.active || *p_sel == 'e') {
1165    decl(&old_end);                         // old_end is inclusive
1166  }
1167
1168  // If we start on "<aaa>" select that block.
1169  if (!Visual.active || equalpos(Visual.start, curwin->w_cursor)) {
1170    setpcmark();
1171
1172    // ignore indent
1173    while (inindent(1)) {
1174      if (inc_cursor() != 0) {
1175        break;
1176      }
1177    }
1178
1179    if (in_html_tag(false)) {
1180      // cursor on start tag, move to its '>'
1181      while (*get_cursor_pos_ptr() != '>') {
1182        if (inc_cursor() < 0) {
1183          break;
1184        }
1185      }
1186    } else if (in_html_tag(true)) {
1187      // cursor on end tag, move to just before it
1188      while (*get_cursor_pos_ptr() != '<') {
1189        if (dec_cursor() < 0) {
1190          break;
1191        }
1192      }
1193      dec_cursor();
1194      old_end = curwin->w_cursor;
1195    }
1196  } else if (lt(Visual.start, curwin->w_cursor)) {
1197    old_start = Visual.start;
1198    curwin->w_cursor = Visual.start;              // cursor at low end of Visual
1199  } else {
1200    old_end = Visual.start;
1201  }
1202
1203again:
1204  // Search backwards for unclosed "<aaa>".
1205  // Put this position in start_pos.
1206  for (int n = 0; n < count; n++) {
1207    if (do_searchpair("<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)",
1208                      "",
1209                      "</[^>]*>", BACKWARD, NULL, 0,
1210                      NULL, 0, 0) <= 0) {
1211      curwin->w_cursor = old_pos;
1212      goto theend;
1213    }
1214  }
1215  pos_T start_pos = curwin->w_cursor;
1216
1217  // Search for matching "</aaa>".  First isolate the "aaa".
1218  inc_cursor();
1219  char *p = get_cursor_pos_ptr();
1220  for (cp = p;
1221       *cp != NUL && *cp != '>' && !ascii_iswhite(*cp);
1222       MB_PTR_ADV(cp)) {}
1223  int len = (int)(cp - p);
1224  if (len == 0) {
1225    curwin->w_cursor = old_pos;
1226    goto theend;
1227  }
1228  const size_t spat_len = (size_t)len + 39;
1229  char *const spat = xmalloc(spat_len);
1230  const size_t epat_len = (size_t)len + 9;
1231  char *const epat = xmalloc(epat_len);
1232  snprintf(spat, spat_len,
1233           "<%.*s\\>\\%%(\\_s\\_[^>]\\{-}\\_[^/]>\\|\\_s\\?>\\)\\c", len, p);
1234  snprintf(epat, epat_len, "</%.*s>\\c", len, p);
1235
1236  const int r = do_searchpair(spat, "", epat, FORWARD, NULL, 0, NULL, 0, 0);
1237
1238  xfree(spat);
1239  xfree(epat);
1240
1241  if (r < 1 || lt(curwin->w_cursor, old_end)) {
1242    // Can't find other end or it's before the previous end.  Could be a
1243    // HTML tag that doesn't have a matching end.  Search backwards for
1244    // another starting tag.
1245    count = 1;
1246    curwin->w_cursor = start_pos;
1247    goto again;
1248  }
1249
1250  if (do_include) {
1251    // Include up to the '>'.
1252    while (*get_cursor_pos_ptr() != '>') {
1253      if (inc_cursor() < 0) {
1254        break;
1255      }
1256    }
1257  } else {
1258    char *c = get_cursor_pos_ptr();
1259    // Exclude the '<' of the end tag.
1260    // If the closing tag is on new line, do not decrement cursor, but make
1261    // operation exclusive, so that the linefeed will be selected
1262    if (*c == '<' && !Visual.active && curwin->w_cursor.col == 0) {
1263      // do not decrement cursor
1264      is_inclusive = false;
1265    } else if (*c == '<') {
1266      dec_cursor();
1267    }
1268  }
1269  pos_T end_pos = curwin->w_cursor;
1270
1271  if (!do_include) {
1272    // Exclude the start tag,
1273    // but skip over '>' if it appears in quotes
1274    bool in_quotes = false;
1275    curwin->w_cursor = start_pos;
1276    while (inc_cursor() >= 0) {
1277      p = get_cursor_pos_ptr();
1278      if (*p == '>' && !in_quotes) {
1279        inc_cursor();
1280        start_pos = curwin->w_cursor;
1281        break;
1282      } else if (*p == '"' || *p == '\'') {
1283        in_quotes = !in_quotes;
1284      }
1285    }
1286    curwin->w_cursor = end_pos;
1287
1288    // If we are in Visual mode and now have the same text as before set
1289    // "do_include" and try again.
1290    if (Visual.active
1291        && equalpos(start_pos, old_start)
1292        && equalpos(end_pos, old_end)) {
1293      do_include = true;
1294      curwin->w_cursor = old_start;
1295      count = count_arg;
1296      goto again;
1297    }
1298  }
1299
1300  if (Visual.active) {
1301    // If the end is before the start there is no text between tags, select
1302    // the char under the cursor.
1303    if (lt(end_pos, start_pos)) {
1304      curwin->w_cursor = start_pos;
1305    } else if (*p_sel == 'e') {
1306      inc_cursor();
1307    }
1308    Visual.start = start_pos;
1309    Visual.mode = 'v';
1310    redraw_curbuf_later(UPD_INVERTED);  // update the inversion
1311    showmode();
1312  } else {
1313    oap->start = start_pos;
1314    oap->motion_type = kMTCharWise;
1315    if (lt(end_pos, start_pos)) {
1316      // End is before the start: there is no text between tags; operate
1317      // on an empty area.
1318      curwin->w_cursor = start_pos;
1319      oap->inclusive = false;
1320    } else {
1321      oap->inclusive = is_inclusive;
1322    }
1323  }
1324  retval = OK;
1325
1326theend:
1327  p_ws = save_p_ws;
1328  return retval;
1329}
1330
1331/// @param include  true == include white space
1332/// @param type     'p' for paragraph, 'S' for section
1333int current_par(oparg_T *oap, int count, bool include, int type)
1334{
1335  int dir;
1336  int retval = OK;
1337  int do_white = false;
1338
1339  if (type == 'S') {        // not implemented yet
1340    return FAIL;
1341  }
1342
1343  linenr_T start_lnum = curwin->w_cursor.lnum;
1344
1345  // When visual area is more than one line: extend it.
1346  if (Visual.active && start_lnum != Visual.start.lnum) {
1347extend:
1348    dir = start_lnum < Visual.start.lnum ? BACKWARD : FORWARD;
1349    for (int i = count; --i >= 0;) {
1350      if (start_lnum ==
1351          (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count)) {
1352        retval = FAIL;
1353        break;
1354      }
1355
1356      int prev_start_is_white = -1;
1357      for (int t = 0; t < 2; t++) {
1358        start_lnum += dir;
1359        int start_is_white = linewhite(start_lnum);
1360        if (prev_start_is_white == start_is_white) {
1361          start_lnum -= dir;
1362          break;
1363        }
1364        while (true) {
1365          if (start_lnum == (dir == BACKWARD
1366                             ? 1 : curbuf->b_ml.ml_line_count)) {
1367            break;
1368          }
1369          if (start_is_white != linewhite(start_lnum + dir)
1370              || (!start_is_white
1371                  && startPS(start_lnum + (dir > 0
1372                                           ? 1 : 0), 0, 0))) {
1373            break;
1374          }
1375          start_lnum += dir;
1376        }
1377        if (!include) {
1378          break;
1379        }
1380        if (start_lnum == (dir == BACKWARD
1381                           ? 1 : curbuf->b_ml.ml_line_count)) {
1382          break;
1383        }
1384        prev_start_is_white = start_is_white;
1385      }
1386    }
1387    curwin->w_cursor.lnum = start_lnum;
1388    curwin->w_cursor.col = 0;
1389    return retval;
1390  }
1391
1392  // First move back to the start_lnum of the paragraph or white lines
1393  bool white_in_front = linewhite(start_lnum);
1394  while (start_lnum > 1) {
1395    if (white_in_front) {           // stop at first white line
1396      if (!linewhite(start_lnum - 1)) {
1397        break;
1398      }
1399    } else {          // stop at first non-white line of start of paragraph
1400      if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0)) {
1401        break;
1402      }
1403    }
1404    start_lnum--;
1405  }
1406
1407  // Move past the end of any white lines.
1408  linenr_T end_lnum = start_lnum;
1409  while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum)) {
1410    end_lnum++;
1411  }
1412
1413  end_lnum--;
1414  int i = count;
1415  if (!include && white_in_front) {
1416    i--;
1417  }
1418  while (i--) {
1419    if (end_lnum == curbuf->b_ml.ml_line_count) {
1420      return FAIL;
1421    }
1422
1423    if (!include) {
1424      do_white = linewhite(end_lnum + 1);
1425    }
1426
1427    if (include || !do_white) {
1428      end_lnum++;
1429      // skip to end of paragraph
1430      while (end_lnum < curbuf->b_ml.ml_line_count
1431             && !linewhite(end_lnum + 1)
1432             && !startPS(end_lnum + 1, 0, 0)) {
1433        end_lnum++;
1434      }
1435    }
1436
1437    if (i == 0 && white_in_front && include) {
1438      break;
1439    }
1440
1441    // skip to end of white lines after paragraph
1442    if (include || do_white) {
1443      while (end_lnum < curbuf->b_ml.ml_line_count
1444             && linewhite(end_lnum + 1)) {
1445        end_lnum++;
1446      }
1447    }
1448  }
1449
1450  // If there are no empty lines at the end, try to find some empty lines at
1451  // the start (unless that has been done already).
1452  if (!white_in_front && !linewhite(end_lnum) && include) {
1453    while (start_lnum > 1 && linewhite(start_lnum - 1)) {
1454      start_lnum--;
1455    }
1456  }
1457
1458  if (Visual.active) {
1459    // Problem: when doing "Vipipip" nothing happens in a single white
1460    // line, we get stuck there.  Trap this here.
1461    if (Visual.mode == 'V' && start_lnum == curwin->w_cursor.lnum) {
1462      goto extend;
1463    }
1464    if (Visual.start.lnum != start_lnum) {
1465      Visual.start.lnum = start_lnum;
1466      Visual.start.col = 0;
1467    }
1468    Visual.mode = 'V';
1469    redraw_curbuf_later(UPD_INVERTED);  // update the inversion
1470    showmode();
1471  } else {
1472    oap->start.lnum = start_lnum;
1473    oap->start.col = 0;
1474    oap->motion_type = kMTLineWise;
1475  }
1476  curwin->w_cursor.lnum = end_lnum;
1477  curwin->w_cursor.col = 0;
1478
1479  return OK;
1480}
1481
1482/// Search quote char from string line[col].
1483/// Quote character escaped by one of the characters in "escape" is not counted
1484/// as a quote.
1485///
1486/// @param escape  escape characters, can be NULL
1487///
1488/// @return        column number of "quotechar" or -1 when not found.
1489static int find_next_quote(char *line, int col, int quotechar, char *escape)
1490{
1491  while (true) {
1492    int c = (uint8_t)line[col];
1493    if (c == NUL) {
1494      return -1;
1495    } else if (escape != NULL && vim_strchr(escape, c)) {
1496      col++;
1497      if (line[col] == NUL) {
1498        return -1;
1499      }
1500    } else if (c == quotechar) {
1501      break;
1502    }
1503    col += utfc_ptr2len(line + col);
1504  }
1505  return col;
1506}
1507
1508/// Search backwards in "line" from column "col_start" to find "quotechar".
1509/// Quote character escaped by one of the characters in "escape" is not counted
1510/// as a quote.
1511///
1512/// @param escape  escape characters, can be NULL
1513///
1514/// @return        the found column or zero.
1515static int find_prev_quote(char *line, int col_start, int quotechar, char *escape)
1516{
1517  while (col_start > 0) {
1518    col_start--;
1519    col_start -= utf_head_off(line, line + col_start);
1520    int n = 0;
1521    if (escape != NULL) {
1522      while (col_start - n > 0 && vim_strchr(escape,
1523                                             (uint8_t)line[col_start - n - 1]) != NULL) {
1524        n++;
1525      }
1526    }
1527    if (n & 1) {
1528      col_start -= n;           // uneven number of escape chars, skip it
1529    } else if ((uint8_t)line[col_start] == quotechar) {
1530      break;
1531    }
1532  }
1533  return col_start;
1534}
1535
1536/// Find quote under the cursor, cursor at end.
1537///
1538/// @param include    true == include quote char
1539/// @param quotechar  Quote character
1540///
1541/// @return           true if found, else false.
1542bool current_quote(oparg_T *oap, int count, bool include, int quotechar)
1543  FUNC_ATTR_NONNULL_ALL
1544{
1545  char *line = get_cursor_line_ptr();
1546  int col_end;
1547  int col_start = curwin->w_cursor.col;
1548  bool inclusive = false;
1549  bool vis_empty = true;                // Visual selection <= 1 char
1550  bool vis_bef_curs = false;            // Visual starts before cursor
1551  bool did_exclusive_adj = false;       // adjusted pos for 'selection'
1552  bool inside_quotes = false;           // Looks like "i'" done before
1553  bool selected_quote = false;          // Has quote inside selection
1554  int i;
1555  bool restore_vis_bef = false;         // restore Visual.start on abort
1556
1557  // When 'selection' is "exclusive" move the cursor to where it would be
1558  // with 'selection' "inclusive", so that the logic is the same for both.
1559  // The cursor then is moved forward after adjusting the area.
1560  if (Visual.active) {
1561    // this only works within one line
1562    if (Visual.start.lnum != curwin->w_cursor.lnum) {
1563      return false;
1564    }
1565
1566    vis_bef_curs = lt(Visual.start, curwin->w_cursor);
1567    vis_empty = equalpos(Visual.start, curwin->w_cursor);
1568    if (*p_sel == 'e') {
1569      if (vis_bef_curs) {
1570        dec_cursor();
1571        did_exclusive_adj = true;
1572      } else if (!vis_empty) {
1573        dec(&Visual.start);
1574        did_exclusive_adj = true;
1575      }
1576      vis_empty = equalpos(Visual.start, curwin->w_cursor);
1577      if (!vis_bef_curs && !vis_empty) {
1578        // Visual.start needs to be start of Visual selection.
1579        pos_T t = curwin->w_cursor;
1580
1581        curwin->w_cursor = Visual.start;
1582        Visual.start = t;
1583        vis_bef_curs = true;
1584        restore_vis_bef = true;
1585      }
1586    }
1587  }
1588
1589  if (!vis_empty) {
1590    // Check if the existing selection exactly spans the text inside
1591    // quotes.
1592    if (vis_bef_curs) {
1593      inside_quotes = Visual.start.col > 0
1594                      && (uint8_t)line[Visual.start.col - 1] == quotechar
1595                      && line[curwin->w_cursor.col] != NUL
1596                      && (uint8_t)line[curwin->w_cursor.col + 1] == quotechar;
1597      i = Visual.start.col;
1598      col_end = curwin->w_cursor.col;
1599    } else {
1600      inside_quotes = curwin->w_cursor.col > 0
1601                      && (uint8_t)line[curwin->w_cursor.col - 1] == quotechar
1602                      && line[Visual.start.col] != NUL
1603                      && (uint8_t)line[Visual.start.col + 1] == quotechar;
1604      i = curwin->w_cursor.col;
1605      col_end = Visual.start.col;
1606    }
1607
1608    // Find out if we have a quote in the selection.
1609    while (i <= col_end) {
1610      // check for going over the end of the line, which can happen if
1611      // the line was changed after the Visual area was selected.
1612      if (line[i] == NUL) {
1613        break;
1614      }
1615      if ((uint8_t)line[i++] == quotechar) {
1616        selected_quote = true;
1617        break;
1618      }
1619    }
1620  }
1621
1622  if (!vis_empty && (uint8_t)line[col_start] == quotechar) {
1623    // Already selecting something and on a quote character.  Find the
1624    // next quoted string.
1625    if (vis_bef_curs) {
1626      // Assume we are on a closing quote: move to after the next
1627      // opening quote.
1628      col_start = find_next_quote(line, col_start + 1, quotechar, NULL);
1629      if (col_start < 0) {
1630        goto abort_search;
1631      }
1632      col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe);
1633      if (col_end < 0) {
1634        // We were on a starting quote perhaps?
1635        col_end = col_start;
1636        col_start = curwin->w_cursor.col;
1637      }
1638    } else {
1639      col_end = find_prev_quote(line, col_start, quotechar, NULL);
1640      if ((uint8_t)line[col_end] != quotechar) {
1641        goto abort_search;
1642      }
1643      col_start = find_prev_quote(line, col_end, quotechar, curbuf->b_p_qe);
1644      if ((uint8_t)line[col_start] != quotechar) {
1645        // We were on an ending quote perhaps?
1646        col_start = col_end;
1647        col_end = curwin->w_cursor.col;
1648      }
1649    }
1650  } else if ((uint8_t)line[col_start] == quotechar || !vis_empty) {
1651    int first_col = col_start;
1652
1653    if (!vis_empty) {
1654      if (vis_bef_curs) {
1655        first_col = find_next_quote(line, col_start, quotechar, NULL);
1656      } else {
1657        first_col = find_prev_quote(line, col_start, quotechar, NULL);
1658      }
1659    }
1660    // The cursor is on a quote, we don't know if it's the opening or
1661    // closing quote.  Search from the start of the line to find out.
1662    // Also do this when there is a Visual area, a' may leave the cursor
1663    // in between two strings.
1664    col_start = 0;
1665    while (true) {
1666      // Find open quote character.
1667      col_start = find_next_quote(line, col_start, quotechar, NULL);
1668      if (col_start < 0 || col_start > first_col) {
1669        goto abort_search;
1670      }
1671      // Find close quote character.
1672      col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe);
1673      if (col_end < 0) {
1674        goto abort_search;
1675      }
1676      // If is cursor between start and end quote character, it is
1677      // target text object.
1678      if (col_start <= first_col && first_col <= col_end) {
1679        break;
1680      }
1681      col_start = col_end + 1;
1682    }
1683  } else {
1684    // Search backward for a starting quote.
1685    col_start = find_prev_quote(line, col_start, quotechar, curbuf->b_p_qe);
1686    if ((uint8_t)line[col_start] != quotechar) {
1687      // No quote before the cursor, look after the cursor.
1688      col_start = find_next_quote(line, col_start, quotechar, NULL);
1689      if (col_start < 0) {
1690        goto abort_search;
1691      }
1692    }
1693
1694    // Find close quote character.
1695    col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe);
1696    if (col_end < 0) {
1697      goto abort_search;
1698    }
1699  }
1700
1701  // When "include" is true, include spaces after closing quote or before
1702  // the starting quote.
1703  if (include) {
1704    if (ascii_iswhite(line[col_end + 1])) {
1705      while (ascii_iswhite(line[col_end + 1])) {
1706        col_end++;
1707      }
1708    } else {
1709      while (col_start > 0 && ascii_iswhite(line[col_start - 1])) {
1710        col_start--;
1711      }
1712    }
1713  }
1714
1715  // Set start position.  After vi" another i" must include the ".
1716  // For v2i" include the quotes.
1717  if (!include && count < 2 && (vis_empty || !inside_quotes)) {
1718    col_start++;
1719  }
1720  curwin->w_cursor.col = col_start;
1721  if (Visual.active) {
1722    // Set the start of the Visual area when the Visual area was empty, we
1723    // were just inside quotes or the Visual area didn't start at a quote
1724    // and didn't include a quote.
1725    if (vis_empty
1726        || (vis_bef_curs
1727            && !selected_quote
1728            && (inside_quotes
1729                || ((uint8_t)line[Visual.start.col] != quotechar
1730                    && (Visual.start.col == 0
1731                        || (uint8_t)line[Visual.start.col - 1] != quotechar))))) {
1732      Visual.start = curwin->w_cursor;
1733      redraw_curbuf_later(UPD_INVERTED);
1734    }
1735  } else {
1736    oap->start = curwin->w_cursor;
1737    oap->motion_type = kMTCharWise;
1738  }
1739
1740  // Set end position.
1741  curwin->w_cursor.col = col_end;
1742  if ((include || count > 1
1743       // After vi" another i" must include the ".
1744       || (!vis_empty && inside_quotes)) && inc_cursor() == 2) {
1745    inclusive = true;
1746  }
1747  if (Visual.active) {
1748    if (vis_empty || vis_bef_curs) {
1749      // decrement cursor when 'selection' is not exclusive
1750      if (*p_sel != 'e') {
1751        dec_cursor();
1752      }
1753    } else {
1754      // Cursor is at start of Visual area.  Set the end of the Visual
1755      // area when it was just inside quotes or it didn't end at a
1756      // quote.
1757      if (inside_quotes
1758          || (!selected_quote
1759              && (uint8_t)line[Visual.start.col] != quotechar
1760              && (line[Visual.start.col] == NUL
1761                  || (uint8_t)line[Visual.start.col + 1] != quotechar))) {
1762        dec_cursor();
1763        Visual.start = curwin->w_cursor;
1764      }
1765      curwin->w_cursor.col = col_start;
1766    }
1767    if (Visual.mode == 'V') {
1768      Visual.mode = 'v';
1769      redraw_cmdline = true;                    // show mode later
1770    }
1771  } else {
1772    // Set inclusive and other oap's flags.
1773    oap->inclusive = inclusive;
1774  }
1775
1776  return true;
1777
1778abort_search:
1779  if (Visual.active && *p_sel == 'e') {
1780    if (did_exclusive_adj) {
1781      inc_cursor();
1782    }
1783    if (restore_vis_bef) {
1784      pos_T t = curwin->w_cursor;
1785
1786      curwin->w_cursor = Visual.start;
1787      Visual.start = t;
1788    }
1789  }
1790  return false;
1791}