vim72-20100325-kaoriya-w64j.zip
[MacVim/KaoriYa.git] / src / search.c
blob406f57ba8b3ba29294421a64155867d72767c312
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9 /*
10 * search.c: code for normal mode searching commands
13 #include "vim.h"
15 static void save_re_pat __ARGS((int idx, char_u *pat, int magic));
16 #ifdef FEAT_EVAL
17 static void set_vv_searchforward __ARGS((void));
18 static int first_submatch __ARGS((regmmatch_T *rp));
19 #endif
20 static int check_prevcol __ARGS((char_u *linep, int col, int ch, int *prevcol));
21 static int inmacro __ARGS((char_u *, char_u *));
22 static int check_linecomment __ARGS((char_u *line));
23 static int cls __ARGS((void));
24 static int skip_chars __ARGS((int, int));
25 #ifdef FEAT_TEXTOBJ
26 static void back_in_line __ARGS((void));
27 static void find_first_blank __ARGS((pos_T *));
28 static void findsent_forward __ARGS((long count, int at_start_sent));
29 #endif
30 #ifdef FEAT_FIND_ID
31 static void show_pat_in_path __ARGS((char_u *, int,
32 int, int, FILE *, linenr_T *, long));
33 #endif
34 #ifdef FEAT_VIMINFO
35 static void wvsp_one __ARGS((FILE *fp, int idx, char *s, int sc));
36 #endif
39 * This file contains various searching-related routines. These fall into
40 * three groups:
41 * 1. string searches (for /, ?, n, and N)
42 * 2. character searches within a single line (for f, F, t, T, etc)
43 * 3. "other" kinds of searches like the '%' command, and 'word' searches.
47 * String searches
49 * The string search functions are divided into two levels:
50 * lowest: searchit(); uses an pos_T for starting position and found match.
51 * Highest: do_search(); uses curwin->w_cursor; calls searchit().
53 * The last search pattern is remembered for repeating the same search.
54 * This pattern is shared between the :g, :s, ? and / commands.
55 * This is in search_regcomp().
57 * The actual string matching is done using a heavily modified version of
58 * Henry Spencer's regular expression library. See regexp.c.
61 /* The offset for a search command is store in a soff struct */
62 /* Note: only spats[0].off is really used */
63 struct soffset
65 int dir; /* search direction, '/' or '?' */
66 int line; /* search has line offset */
67 int end; /* search set cursor at end */
68 long off; /* line or char offset */
71 /* A search pattern and its attributes are stored in a spat struct */
72 struct spat
74 char_u *pat; /* the pattern (in allocated memory) or NULL */
75 int magic; /* magicness of the pattern */
76 int no_scs; /* no smarcase for this pattern */
77 struct soffset off;
81 * Two search patterns are remembered: One for the :substitute command and
82 * one for other searches. last_idx points to the one that was used the last
83 * time.
85 static struct spat spats[2] =
87 {NULL, TRUE, FALSE, {'/', 0, 0, 0L}}, /* last used search pat */
88 {NULL, TRUE, FALSE, {'/', 0, 0, 0L}} /* last used substitute pat */
91 static int last_idx = 0; /* index in spats[] for RE_LAST */
93 #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO)
94 /* copy of spats[], for keeping the search patterns while executing autocmds */
95 static struct spat saved_spats[2];
96 static int saved_last_idx = 0;
97 # ifdef FEAT_SEARCH_EXTRA
98 static int saved_no_hlsearch = 0;
99 # endif
100 #endif
102 static char_u *mr_pattern = NULL; /* pattern used by search_regcomp() */
103 #ifdef FEAT_RIGHTLEFT
104 static int mr_pattern_alloced = FALSE; /* mr_pattern was allocated */
105 #endif
107 #ifdef FEAT_FIND_ID
109 * Type used by find_pattern_in_path() to remember which included files have
110 * been searched already.
112 typedef struct SearchedFile
114 FILE *fp; /* File pointer */
115 char_u *name; /* Full name of file */
116 linenr_T lnum; /* Line we were up to in file */
117 int matched; /* Found a match in this file */
118 } SearchedFile;
119 #endif
122 * translate search pattern for vim_regcomp()
124 * pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd)
125 * pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command)
126 * pat_save == RE_BOTH: save pat in both patterns (:global command)
127 * pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL
128 * pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL
129 * pat_use == RE_LAST: use last used pattern if "pat" is NULL
130 * options & SEARCH_HIS: put search string in history
131 * options & SEARCH_KEEP: keep previous search pattern
133 * returns FAIL if failed, OK otherwise.
136 search_regcomp(pat, pat_save, pat_use, options, regmatch)
137 char_u *pat;
138 int pat_save;
139 int pat_use;
140 int options;
141 regmmatch_T *regmatch; /* return: pattern and ignore-case flag */
143 int magic;
144 int i;
146 rc_did_emsg = FALSE;
147 magic = p_magic;
150 * If no pattern given, use a previously defined pattern.
152 if (pat == NULL || *pat == NUL)
154 if (pat_use == RE_LAST)
155 i = last_idx;
156 else
157 i = pat_use;
158 if (spats[i].pat == NULL) /* pattern was never defined */
160 if (pat_use == RE_SUBST)
161 EMSG(_(e_nopresub));
162 else
163 EMSG(_(e_noprevre));
164 rc_did_emsg = TRUE;
165 return FAIL;
167 pat = spats[i].pat;
168 magic = spats[i].magic;
169 no_smartcase = spats[i].no_scs;
171 #ifdef FEAT_CMDHIST
172 else if (options & SEARCH_HIS) /* put new pattern in history */
173 add_to_history(HIST_SEARCH, pat, TRUE, NUL);
174 #endif
176 #ifdef FEAT_RIGHTLEFT
177 if (mr_pattern_alloced)
179 vim_free(mr_pattern);
180 mr_pattern_alloced = FALSE;
183 if (curwin->w_p_rl && *curwin->w_p_rlc == 's')
185 char_u *rev_pattern;
187 rev_pattern = reverse_text(pat);
188 if (rev_pattern == NULL)
189 mr_pattern = pat; /* out of memory, keep normal pattern. */
190 else
192 mr_pattern = rev_pattern;
193 mr_pattern_alloced = TRUE;
196 else
197 #endif
198 mr_pattern = pat;
201 * Save the currently used pattern in the appropriate place,
202 * unless the pattern should not be remembered.
204 if (!(options & SEARCH_KEEP))
206 /* search or global command */
207 if (pat_save == RE_SEARCH || pat_save == RE_BOTH)
208 save_re_pat(RE_SEARCH, pat, magic);
209 /* substitute or global command */
210 if (pat_save == RE_SUBST || pat_save == RE_BOTH)
211 save_re_pat(RE_SUBST, pat, magic);
214 regmatch->rmm_ic = ignorecase(pat);
215 regmatch->rmm_maxcol = 0;
216 regmatch->regprog = vim_regcomp(pat, magic ? RE_MAGIC : 0);
217 if (regmatch->regprog == NULL)
218 return FAIL;
219 return OK;
223 * Get search pattern used by search_regcomp().
225 char_u *
226 get_search_pat()
228 return mr_pattern;
231 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
233 * Reverse text into allocated memory.
234 * Returns the allocated string, NULL when out of memory.
236 char_u *
237 reverse_text(s)
238 char_u *s;
240 unsigned len;
241 unsigned s_i, rev_i;
242 char_u *rev;
245 * Reverse the pattern.
247 len = (unsigned)STRLEN(s);
248 rev = alloc(len + 1);
249 if (rev != NULL)
251 rev_i = len;
252 for (s_i = 0; s_i < len; ++s_i)
254 # ifdef FEAT_MBYTE
255 if (has_mbyte)
257 int mb_len;
259 mb_len = (*mb_ptr2len)(s + s_i);
260 rev_i -= mb_len;
261 mch_memmove(rev + rev_i, s + s_i, mb_len);
262 s_i += mb_len - 1;
264 else
265 # endif
266 rev[--rev_i] = s[s_i];
269 rev[len] = NUL;
271 return rev;
273 #endif
275 static void
276 save_re_pat(idx, pat, magic)
277 int idx;
278 char_u *pat;
279 int magic;
281 if (spats[idx].pat != pat)
283 vim_free(spats[idx].pat);
284 spats[idx].pat = vim_strsave(pat);
285 spats[idx].magic = magic;
286 spats[idx].no_scs = no_smartcase;
287 last_idx = idx;
288 #ifdef FEAT_SEARCH_EXTRA
289 /* If 'hlsearch' set and search pat changed: need redraw. */
290 if (p_hls)
291 redraw_all_later(SOME_VALID);
292 no_hlsearch = FALSE;
293 #endif
297 #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO)
299 * Save the search patterns, so they can be restored later.
300 * Used before/after executing autocommands and user functions.
302 static int save_level = 0;
304 void
305 save_search_patterns()
307 if (save_level++ == 0)
309 saved_spats[0] = spats[0];
310 if (spats[0].pat != NULL)
311 saved_spats[0].pat = vim_strsave(spats[0].pat);
312 saved_spats[1] = spats[1];
313 if (spats[1].pat != NULL)
314 saved_spats[1].pat = vim_strsave(spats[1].pat);
315 saved_last_idx = last_idx;
316 # ifdef FEAT_SEARCH_EXTRA
317 saved_no_hlsearch = no_hlsearch;
318 # endif
322 void
323 restore_search_patterns()
325 if (--save_level == 0)
327 vim_free(spats[0].pat);
328 spats[0] = saved_spats[0];
329 #if defined(FEAT_EVAL)
330 set_vv_searchforward();
331 #endif
332 vim_free(spats[1].pat);
333 spats[1] = saved_spats[1];
334 last_idx = saved_last_idx;
335 # ifdef FEAT_SEARCH_EXTRA
336 no_hlsearch = saved_no_hlsearch;
337 # endif
340 #endif
342 #if defined(EXITFREE) || defined(PROTO)
343 void
344 free_search_patterns()
346 vim_free(spats[0].pat);
347 vim_free(spats[1].pat);
349 # ifdef FEAT_RIGHTLEFT
350 if (mr_pattern_alloced)
352 vim_free(mr_pattern);
353 mr_pattern_alloced = FALSE;
354 mr_pattern = NULL;
356 # endif
358 #endif
361 * Return TRUE when case should be ignored for search pattern "pat".
362 * Uses the 'ignorecase' and 'smartcase' options.
365 ignorecase(pat)
366 char_u *pat;
368 char_u *p;
369 int ic;
371 ic = p_ic;
372 if (ic && !no_smartcase && p_scs
373 #ifdef FEAT_INS_EXPAND
374 && !(ctrl_x_mode && curbuf->b_p_inf)
375 #endif
378 /* don't ignore case if pattern has uppercase */
379 for (p = pat; *p; )
381 #ifdef FEAT_MBYTE
382 int l;
384 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
386 if (enc_utf8 && utf_isupper(utf_ptr2char(p)))
388 ic = FALSE;
389 break;
391 p += l;
393 else
394 #endif
395 if (*p == '\\')
397 if (p[1] == '_' && p[2] != NUL) /* skip "\_X" */
398 p += 3;
399 else if (p[1] == '%' && p[2] != NUL) /* skip "\%X" */
400 p += 3;
401 else if (p[1] != NUL) /* skip "\X" */
402 p += 2;
403 else
404 p += 1;
406 else if (MB_ISUPPER(*p))
408 ic = FALSE;
409 break;
411 else
412 ++p;
415 no_smartcase = FALSE;
417 return ic;
420 char_u *
421 last_search_pat()
423 return spats[last_idx].pat;
427 * Reset search direction to forward. For "gd" and "gD" commands.
429 void
430 reset_search_dir()
432 spats[0].off.dir = '/';
433 #if defined(FEAT_EVAL)
434 set_vv_searchforward();
435 #endif
438 #if defined(FEAT_EVAL) || defined(FEAT_VIMINFO)
440 * Set the last search pattern. For ":let @/ =" and viminfo.
441 * Also set the saved search pattern, so that this works in an autocommand.
443 void
444 set_last_search_pat(s, idx, magic, setlast)
445 char_u *s;
446 int idx;
447 int magic;
448 int setlast;
450 vim_free(spats[idx].pat);
451 /* An empty string means that nothing should be matched. */
452 if (*s == NUL)
453 spats[idx].pat = NULL;
454 else
455 spats[idx].pat = vim_strsave(s);
456 spats[idx].magic = magic;
457 spats[idx].no_scs = FALSE;
458 spats[idx].off.dir = '/';
459 #if defined(FEAT_EVAL)
460 set_vv_searchforward();
461 #endif
462 spats[idx].off.line = FALSE;
463 spats[idx].off.end = FALSE;
464 spats[idx].off.off = 0;
465 if (setlast)
466 last_idx = idx;
467 if (save_level)
469 vim_free(saved_spats[idx].pat);
470 saved_spats[idx] = spats[0];
471 if (spats[idx].pat == NULL)
472 saved_spats[idx].pat = NULL;
473 else
474 saved_spats[idx].pat = vim_strsave(spats[idx].pat);
475 saved_last_idx = last_idx;
477 # ifdef FEAT_SEARCH_EXTRA
478 /* If 'hlsearch' set and search pat changed: need redraw. */
479 if (p_hls && idx == last_idx && !no_hlsearch)
480 redraw_all_later(SOME_VALID);
481 # endif
483 #endif
485 #ifdef FEAT_SEARCH_EXTRA
487 * Get a regexp program for the last used search pattern.
488 * This is used for highlighting all matches in a window.
489 * Values returned in regmatch->regprog and regmatch->rmm_ic.
491 void
492 last_pat_prog(regmatch)
493 regmmatch_T *regmatch;
495 if (spats[last_idx].pat == NULL)
497 regmatch->regprog = NULL;
498 return;
500 ++emsg_off; /* So it doesn't beep if bad expr */
501 (void)search_regcomp((char_u *)"", 0, last_idx, SEARCH_KEEP, regmatch);
502 --emsg_off;
504 #endif
507 * lowest level search function.
508 * Search for 'count'th occurrence of pattern 'pat' in direction 'dir'.
509 * Start at position 'pos' and return the found position in 'pos'.
511 * if (options & SEARCH_MSG) == 0 don't give any messages
512 * if (options & SEARCH_MSG) == SEARCH_NFMSG don't give 'notfound' messages
513 * if (options & SEARCH_MSG) == SEARCH_MSG give all messages
514 * if (options & SEARCH_HIS) put search pattern in history
515 * if (options & SEARCH_END) return position at end of match
516 * if (options & SEARCH_START) accept match at pos itself
517 * if (options & SEARCH_KEEP) keep previous search pattern
518 * if (options & SEARCH_FOLD) match only once in a closed fold
519 * if (options & SEARCH_PEEK) check for typed char, cancel search
521 * Return FAIL (zero) for failure, non-zero for success.
522 * When FEAT_EVAL is defined, returns the index of the first matching
523 * subpattern plus one; one if there was none.
526 searchit(win, buf, pos, dir, pat, count, options, pat_use, stop_lnum, tm)
527 win_T *win; /* window to search in; can be NULL for a
528 buffer without a window! */
529 buf_T *buf;
530 pos_T *pos;
531 int dir;
532 char_u *pat;
533 long count;
534 int options;
535 int pat_use; /* which pattern to use when "pat" is empty */
536 linenr_T stop_lnum; /* stop after this line number when != 0 */
537 proftime_T *tm UNUSED; /* timeout limit or NULL */
539 int found;
540 linenr_T lnum; /* no init to shut up Apollo cc */
541 regmmatch_T regmatch;
542 char_u *ptr;
543 colnr_T matchcol;
544 lpos_T endpos;
545 lpos_T matchpos;
546 int loop;
547 pos_T start_pos;
548 int at_first_line;
549 int extra_col;
550 int match_ok;
551 long nmatched;
552 int submatch = 0;
553 int save_called_emsg = called_emsg;
554 #ifdef FEAT_SEARCH_EXTRA
555 int break_loop = FALSE;
556 #endif
558 if (search_regcomp(pat, RE_SEARCH, pat_use,
559 (options & (SEARCH_HIS + SEARCH_KEEP)), &regmatch) == FAIL)
561 if ((options & SEARCH_MSG) && !rc_did_emsg)
562 EMSG2(_("E383: Invalid search string: %s"), mr_pattern);
563 return FAIL;
566 /* When not accepting a match at the start position set "extra_col" to a
567 * non-zero value. Don't do that when starting at MAXCOL, since MAXCOL +
568 * 1 is zero. */
569 if ((options & SEARCH_START) || pos->col == MAXCOL)
570 extra_col = 0;
571 #ifdef FEAT_MBYTE
572 /* Watch out for the "col" being MAXCOL - 2, used in a closed fold. */
573 else if (has_mbyte && pos->lnum >= 1 && pos->lnum <= buf->b_ml.ml_line_count
574 && pos->col < MAXCOL - 2)
576 ptr = ml_get_buf(buf, pos->lnum, FALSE) + pos->col;
577 if (*ptr == NUL)
578 extra_col = 1;
579 else
580 extra_col = (*mb_ptr2len)(ptr);
582 #endif
583 else
584 extra_col = 1;
587 * find the string
589 called_emsg = FALSE;
590 do /* loop for count */
592 start_pos = *pos; /* remember start pos for detecting no match */
593 found = 0; /* default: not found */
594 at_first_line = TRUE; /* default: start in first line */
595 if (pos->lnum == 0) /* correct lnum for when starting in line 0 */
597 pos->lnum = 1;
598 pos->col = 0;
599 at_first_line = FALSE; /* not in first line now */
603 * Start searching in current line, unless searching backwards and
604 * we're in column 0.
605 * If we are searching backwards, in column 0, and not including the
606 * current position, gain some efficiency by skipping back a line.
607 * Otherwise begin the search in the current line.
609 if (dir == BACKWARD && start_pos.col == 0
610 && (options & SEARCH_START) == 0)
612 lnum = pos->lnum - 1;
613 at_first_line = FALSE;
615 else
616 lnum = pos->lnum;
618 for (loop = 0; loop <= 1; ++loop) /* loop twice if 'wrapscan' set */
620 for ( ; lnum > 0 && lnum <= buf->b_ml.ml_line_count;
621 lnum += dir, at_first_line = FALSE)
623 /* Stop after checking "stop_lnum", if it's set. */
624 if (stop_lnum != 0 && (dir == FORWARD
625 ? lnum > stop_lnum : lnum < stop_lnum))
626 break;
627 #ifdef FEAT_RELTIME
628 /* Stop after passing the "tm" time limit. */
629 if (tm != NULL && profile_passed_limit(tm))
630 break;
631 #endif
634 * Look for a match somewhere in line "lnum".
636 nmatched = vim_regexec_multi(&regmatch, win, buf,
637 lnum, (colnr_T)0,
638 #ifdef FEAT_RELTIME
640 #else
641 NULL
642 #endif
644 /* Abort searching on an error (e.g., out of stack). */
645 if (called_emsg)
646 break;
647 if (nmatched > 0)
649 /* match may actually be in another line when using \zs */
650 matchpos = regmatch.startpos[0];
651 endpos = regmatch.endpos[0];
652 #ifdef FEAT_EVAL
653 submatch = first_submatch(&regmatch);
654 #endif
655 /* "lnum" may be past end of buffer for "\n\zs". */
656 if (lnum + matchpos.lnum > buf->b_ml.ml_line_count)
657 ptr = (char_u *)"";
658 else
659 ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE);
662 * Forward search in the first line: match should be after
663 * the start position. If not, continue at the end of the
664 * match (this is vi compatible) or on the next char.
666 if (dir == FORWARD && at_first_line)
668 match_ok = TRUE;
670 * When the match starts in a next line it's certainly
671 * past the start position.
672 * When match lands on a NUL the cursor will be put
673 * one back afterwards, compare with that position,
674 * otherwise "/$" will get stuck on end of line.
676 while (matchpos.lnum == 0
677 && ((options & SEARCH_END)
678 ? (nmatched == 1
679 && (int)endpos.col - 1
680 < (int)start_pos.col + extra_col)
681 : ((int)matchpos.col
682 - (ptr[matchpos.col] == NUL)
683 < (int)start_pos.col + extra_col)))
686 * If vi-compatible searching, continue at the end
687 * of the match, otherwise continue one position
688 * forward.
690 if (vim_strchr(p_cpo, CPO_SEARCH) != NULL)
692 if (nmatched > 1)
694 /* end is in next line, thus no match in
695 * this line */
696 match_ok = FALSE;
697 break;
699 matchcol = endpos.col;
700 /* for empty match: advance one char */
701 if (matchcol == matchpos.col
702 && ptr[matchcol] != NUL)
704 #ifdef FEAT_MBYTE
705 if (has_mbyte)
706 matchcol +=
707 (*mb_ptr2len)(ptr + matchcol);
708 else
709 #endif
710 ++matchcol;
713 else
715 matchcol = matchpos.col;
716 if (ptr[matchcol] != NUL)
718 #ifdef FEAT_MBYTE
719 if (has_mbyte)
720 matchcol += (*mb_ptr2len)(ptr
721 + matchcol);
722 else
723 #endif
724 ++matchcol;
727 if (ptr[matchcol] == NUL
728 || (nmatched = vim_regexec_multi(&regmatch,
729 win, buf, lnum + matchpos.lnum,
730 matchcol,
731 #ifdef FEAT_RELTIME
733 #else
734 NULL
735 #endif
736 )) == 0)
738 match_ok = FALSE;
739 break;
741 matchpos = regmatch.startpos[0];
742 endpos = regmatch.endpos[0];
743 # ifdef FEAT_EVAL
744 submatch = first_submatch(&regmatch);
745 # endif
747 /* Need to get the line pointer again, a
748 * multi-line search may have made it invalid. */
749 ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE);
751 if (!match_ok)
752 continue;
754 if (dir == BACKWARD)
757 * Now, if there are multiple matches on this line,
758 * we have to get the last one. Or the last one before
759 * the cursor, if we're on that line.
760 * When putting the new cursor at the end, compare
761 * relative to the end of the match.
763 match_ok = FALSE;
764 for (;;)
766 /* Remember a position that is before the start
767 * position, we use it if it's the last match in
768 * the line. Always accept a position after
769 * wrapping around. */
770 if (loop
771 || ((options & SEARCH_END)
772 ? (lnum + regmatch.endpos[0].lnum
773 < start_pos.lnum
774 || (lnum + regmatch.endpos[0].lnum
775 == start_pos.lnum
776 && (int)regmatch.endpos[0].col - 1
777 + extra_col
778 <= (int)start_pos.col))
779 : (lnum + regmatch.startpos[0].lnum
780 < start_pos.lnum
781 || (lnum + regmatch.startpos[0].lnum
782 == start_pos.lnum
783 && (int)regmatch.startpos[0].col
784 + extra_col
785 <= (int)start_pos.col))))
787 match_ok = TRUE;
788 matchpos = regmatch.startpos[0];
789 endpos = regmatch.endpos[0];
790 # ifdef FEAT_EVAL
791 submatch = first_submatch(&regmatch);
792 # endif
794 else
795 break;
798 * We found a valid match, now check if there is
799 * another one after it.
800 * If vi-compatible searching, continue at the end
801 * of the match, otherwise continue one position
802 * forward.
804 if (vim_strchr(p_cpo, CPO_SEARCH) != NULL)
806 if (nmatched > 1)
807 break;
808 matchcol = endpos.col;
809 /* for empty match: advance one char */
810 if (matchcol == matchpos.col
811 && ptr[matchcol] != NUL)
813 #ifdef FEAT_MBYTE
814 if (has_mbyte)
815 matchcol +=
816 (*mb_ptr2len)(ptr + matchcol);
817 else
818 #endif
819 ++matchcol;
822 else
824 /* Stop when the match is in a next line. */
825 if (matchpos.lnum > 0)
826 break;
827 matchcol = matchpos.col;
828 if (ptr[matchcol] != NUL)
830 #ifdef FEAT_MBYTE
831 if (has_mbyte)
832 matchcol +=
833 (*mb_ptr2len)(ptr + matchcol);
834 else
835 #endif
836 ++matchcol;
839 if (ptr[matchcol] == NUL
840 || (nmatched = vim_regexec_multi(&regmatch,
841 win, buf, lnum + matchpos.lnum,
842 matchcol,
843 #ifdef FEAT_RELTIME
845 #else
846 NULL
847 #endif
848 )) == 0)
849 break;
851 /* Need to get the line pointer again, a
852 * multi-line search may have made it invalid. */
853 ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE);
857 * If there is only a match after the cursor, skip
858 * this match.
860 if (!match_ok)
861 continue;
864 /* With the SEARCH_END option move to the last character
865 * of the match. Don't do it for an empty match, end
866 * should be same as start then. */
867 if (options & SEARCH_END && !(options & SEARCH_NOOF)
868 && !(matchpos.lnum == endpos.lnum
869 && matchpos.col == endpos.col))
871 /* For a match in the first column, set the position
872 * on the NUL in the previous line. */
873 pos->lnum = lnum + endpos.lnum;
874 pos->col = endpos.col;
875 if (endpos.col == 0)
877 if (pos->lnum > 1) /* just in case */
879 --pos->lnum;
880 pos->col = (colnr_T)STRLEN(ml_get_buf(buf,
881 pos->lnum, FALSE));
884 else
886 --pos->col;
887 #ifdef FEAT_MBYTE
888 if (has_mbyte
889 && pos->lnum <= buf->b_ml.ml_line_count)
891 ptr = ml_get_buf(buf, pos->lnum, FALSE);
892 pos->col -= (*mb_head_off)(ptr, ptr + pos->col);
894 #endif
897 else
899 pos->lnum = lnum + matchpos.lnum;
900 pos->col = matchpos.col;
902 #ifdef FEAT_VIRTUALEDIT
903 pos->coladd = 0;
904 #endif
905 found = 1;
907 /* Set variables used for 'incsearch' highlighting. */
908 search_match_lines = endpos.lnum - matchpos.lnum;
909 search_match_endcol = endpos.col;
910 break;
912 line_breakcheck(); /* stop if ctrl-C typed */
913 if (got_int)
914 break;
916 #ifdef FEAT_SEARCH_EXTRA
917 /* Cancel searching if a character was typed. Used for
918 * 'incsearch'. Don't check too often, that would slowdown
919 * searching too much. */
920 if ((options & SEARCH_PEEK)
921 && ((lnum - pos->lnum) & 0x3f) == 0
922 && char_avail())
924 break_loop = TRUE;
925 break;
927 #endif
929 if (loop && lnum == start_pos.lnum)
930 break; /* if second loop, stop where started */
932 at_first_line = FALSE;
935 * Stop the search if wrapscan isn't set, "stop_lnum" is
936 * specified, after an interrupt, after a match and after looping
937 * twice.
939 if (!p_ws || stop_lnum != 0 || got_int || called_emsg
940 #ifdef FEAT_SEARCH_EXTRA
941 || break_loop
942 #endif
943 || found || loop)
944 break;
947 * If 'wrapscan' is set we continue at the other end of the file.
948 * If 'shortmess' does not contain 's', we give a message.
949 * This message is also remembered in keep_msg for when the screen
950 * is redrawn. The keep_msg is cleared whenever another message is
951 * written.
953 if (dir == BACKWARD) /* start second loop at the other end */
954 lnum = buf->b_ml.ml_line_count;
955 else
956 lnum = 1;
957 if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
958 give_warning((char_u *)_(dir == BACKWARD
959 ? top_bot_msg : bot_top_msg), TRUE);
961 if (got_int || called_emsg
962 #ifdef FEAT_SEARCH_EXTRA
963 || break_loop
964 #endif
966 break;
968 while (--count > 0 && found); /* stop after count matches or no match */
970 vim_free(regmatch.regprog);
972 called_emsg |= save_called_emsg;
974 if (!found) /* did not find it */
976 if (got_int)
977 EMSG(_(e_interr));
978 else if ((options & SEARCH_MSG) == SEARCH_MSG)
980 if (p_ws)
981 EMSG2(_(e_patnotf2), mr_pattern);
982 else if (lnum == 0)
983 EMSG2(_("E384: search hit TOP without match for: %s"),
984 mr_pattern);
985 else
986 EMSG2(_("E385: search hit BOTTOM without match for: %s"),
987 mr_pattern);
989 return FAIL;
992 /* A pattern like "\n\zs" may go past the last line. */
993 if (pos->lnum > buf->b_ml.ml_line_count)
995 pos->lnum = buf->b_ml.ml_line_count;
996 pos->col = (int)STRLEN(ml_get_buf(buf, pos->lnum, FALSE));
997 if (pos->col > 0)
998 --pos->col;
1001 return submatch + 1;
1004 #ifdef FEAT_EVAL
1005 void
1006 set_search_direction(cdir)
1007 int cdir;
1009 spats[0].off.dir = cdir;
1012 static void
1013 set_vv_searchforward()
1015 set_vim_var_nr(VV_SEARCHFORWARD, (long)(spats[0].off.dir == '/'));
1019 * Return the number of the first subpat that matched.
1021 static int
1022 first_submatch(rp)
1023 regmmatch_T *rp;
1025 int submatch;
1027 for (submatch = 1; ; ++submatch)
1029 if (rp->startpos[submatch].lnum >= 0)
1030 break;
1031 if (submatch == 9)
1033 submatch = 0;
1034 break;
1037 return submatch;
1039 #endif
1041 #ifdef USE_MIGEMO
1042 # define MIGEMO_QUERY_MAXSIZE 40960
1043 /* Load migemo header */
1044 # ifndef DYNAMIC_MIGEMO
1045 # include <migemo.h>
1046 # else /* DYNAMIC_MIGEMO */
1048 # define MIGEMO_PROC FARPROC
1049 # ifndef DYNAMIC_MIGEMO_DLL
1050 # define DYNAMIC_MIGEMO_DLL "migemo.dll"
1051 # endif
1053 # define MIGEMO_OPINDEX_OR 0
1054 # define MIGEMO_OPINDEX_NEST_IN 1
1055 # define MIGEMO_OPINDEX_NEST_OUT 2
1056 # define MIGEMO_OPINDEX_SELECT_IN 3
1057 # define MIGEMO_OPINDEX_SELECT_OUT 4
1058 # define MIGEMO_OPINDEX_NEWLINE 5
1060 typedef struct _migemo migemo;
1061 typedef int (*MIGEMO_PROC_CHAR2INT)(unsigned char*, unsigned int*);
1062 typedef int (*MIGEMO_PROC_INT2CHAR)(unsigned int, unsigned char*);
1063 static HANDLE hDllMigemo = NULL;
1064 migemo* (*dll_migemo_open)(char*);
1065 void (*dll_migemo_close)(migemo*);
1066 unsigned char* (*dll_migemo_query)(migemo*, unsigned char*);
1067 void (*dll_migemo_release)(migemo*, unsigned char*);
1068 int (*dll_migemo_set_operator)(migemo*, int index, unsigned char* op);
1069 const unsigned char* (*dll_migemo_get_operator)(migemo*, int index);
1070 void (*dll_migemo_setproc_char2int)(migemo*, MIGEMO_PROC_CHAR2INT);
1071 void (*dll_migemo_setproc_int2char)(migemo*, MIGEMO_PROC_INT2CHAR);
1073 # define migemo_open dll_migemo_open
1074 # define migemo_close dll_migemo_close
1075 # define migemo_query dll_migemo_query
1076 # define migemo_release dll_migemo_release
1077 # define migemo_set_operator dll_migemo_set_operator
1078 # define migemo_get_operator dll_migemo_get_operator
1079 # define migemo_setproc_char2int dll_migemo_setproc_char2int
1080 # define migemo_setproc_int2char dll_migemo_setproc_int2char
1082 static void
1083 dyn_migemo_end()
1085 if (hDllMigemo)
1087 FreeLibrary(hDllMigemo);
1088 hDllMigemo = NULL;
1092 static int
1093 dyn_migemo_init()
1095 static struct { char* name; MIGEMO_PROC* ptr; } migemo_func_table[] = {
1096 {"migemo_open", (MIGEMO_PROC*)&dll_migemo_open},
1097 {"migemo_close", (MIGEMO_PROC*)&dll_migemo_close},
1098 {"migemo_query", (MIGEMO_PROC*)&dll_migemo_query},
1099 {"migemo_release", (MIGEMO_PROC*)&dll_migemo_release},
1100 {"migemo_set_operator", (MIGEMO_PROC*)&dll_migemo_set_operator},
1101 {"migemo_get_operator", (MIGEMO_PROC*)&dll_migemo_get_operator},
1102 {"migemo_setproc_char2int", (MIGEMO_PROC*)&dll_migemo_setproc_char2int},
1103 {"migemo_setproc_int2char", (MIGEMO_PROC*)&dll_migemo_setproc_int2char},
1104 {NULL, NULL},
1106 int i;
1108 if (hDllMigemo)
1109 return 1;
1110 if (!(hDllMigemo = LoadLibraryEx(DYNAMIC_MIGEMO_DLL, NULL, 0)))
1111 return 0;
1112 for (i = 0; migemo_func_table[i].ptr; ++i)
1114 if (!(*migemo_func_table[i].ptr = GetProcAddress(hDllMigemo,
1115 migemo_func_table[i].name)))
1117 dyn_migemo_end();
1118 return 0;
1121 return 1;
1123 # endif /* DYNAMIC_MIGEMO */
1125 static int
1126 vimigemo_char2int(unsigned char* p, unsigned int* code)
1128 unsigned int ch = *p;
1129 int len = 1;
1131 #ifdef FEAT_MBYTE
1132 if (has_mbyte)
1134 ch = (*mb_ptr2char)(p);
1135 len = (*mb_ptr2len)(p);
1137 #endif
1138 if (code)
1139 *code = ch;
1140 return len;
1143 static int
1144 vimigemo_int2char(unsigned int code, unsigned char* buf)
1146 int len;
1148 #ifdef FEAT_MBYTE
1149 if (has_mbyte && (len = (*mb_char2len)(code)) != 1)
1151 if (buf)
1152 (*mb_char2bytes)(code, buf);
1154 else
1155 #endif
1157 len = 0;
1158 switch (code)
1160 case '\\':
1161 case '.': case '*': case '^': case '$': case '/':
1162 case '[': case ']': case '~':
1163 if (buf)
1164 buf[len] = '\\';
1165 ++len;
1166 default:
1167 if (buf)
1168 buf[len] = (unsigned char)(code & 0xFF);
1169 ++len;
1170 break;
1174 return len;
1178 migemo_enabled()
1180 return
1181 #ifdef DYNAMIC_MIGEMO
1182 dyn_migemo_init()
1183 #else
1185 #endif
1189 static migemo* migemo_object = NULL;
1190 static int migemo_tryload = 0;
1192 static void
1193 init_migemo()
1195 # ifdef DYNAMIC_MIGEMO
1196 if (!dyn_migemo_init())
1197 return;
1198 # endif
1199 if (migemo_tryload || migemo_object)
1200 return;
1202 migemo_tryload = 1;
1203 migemo_object = migemo_open(p_migdict);
1205 if (!migemo_object)
1206 return;
1208 migemo_set_operator(migemo_object, MIGEMO_OPINDEX_OR, "\\|");
1209 migemo_set_operator(migemo_object, MIGEMO_OPINDEX_NEST_IN, "\\%(");
1210 migemo_set_operator(migemo_object, MIGEMO_OPINDEX_NEST_OUT, "\\)");
1211 migemo_set_operator(migemo_object, MIGEMO_OPINDEX_NEST_OUT, "\\)");
1212 migemo_set_operator(migemo_object, MIGEMO_OPINDEX_NEWLINE, "\\_s*");
1213 migemo_setproc_int2char(migemo_object, vimigemo_int2char);
1214 migemo_setproc_char2int(migemo_object, vimigemo_char2int);
1217 void
1218 reset_migemo(int lastcall)
1220 if (migemo_object)
1221 migemo_close(migemo_object);
1222 migemo_object = NULL;
1223 migemo_tryload = 0;
1224 # ifdef DYNAMIC_MIGEMO
1225 if (lastcall)
1226 dyn_migemo_end();
1227 # endif
1230 char_u*
1231 query_migemo(char_u* str)
1233 char_u *retval = NULL;
1235 if (str)
1237 init_migemo();
1238 if (migemo_object)
1240 char *query = migemo_query(migemo_object, str);
1242 if (query != NULL)
1244 retval = vim_strsave(query);
1245 migemo_release(migemo_object, query);
1249 return retval ? retval : str;
1253 check_migemo_able_string(char_u* str)
1255 int len;
1257 len = STRLEN(str);
1258 /* Disabled because of adding query size limitation. */
1259 #if 0
1260 if (len == 1 && vim_strchr("kstnKSTN", str[0]))
1261 return 0;
1262 #endif
1263 /* TODO: Incomplete method. To be improved. */
1264 if (len >= 1 && (vim_strchr(str, '^')))
1265 return 0;
1266 if (len >= 2 && !STRNCMP(str, "\\<", 2))
1267 return 0;
1268 /* Search for multibyte char */
1269 #ifdef FEAT_MBYTE
1270 if (has_mbyte)
1271 while (*str)
1273 if ((*mb_ptr2len)(str) > 1)
1274 return 0;
1275 ++str;
1277 #endif
1278 return 1;
1281 static int
1282 searchit_migemo(win, buf, pos, dir, str, count, options, pat_use, stop_lnum,
1283 tm, did)
1284 win_T *win;
1285 buf_T *buf;
1286 pos_T *pos;
1287 int dir;
1288 char_u *str;
1289 long count;
1290 int options;
1291 int pat_use;
1292 linenr_T stop_lnum; /* stop after this line number when != 0 */
1293 proftime_T* tm;
1294 int *did;
1296 int retval = 0;
1297 int didval = 0;
1299 if (str && buf && STRLEN(p_migdict) > 0 && check_migemo_able_string(str))
1301 init_migemo();
1302 if (migemo_object)
1304 char *query;
1305 char_u *newstr = NULL;
1307 /* Remove backslash in str */
1308 if (vim_strchr(str, '\\') && (newstr = vim_strsave(str)))
1310 char_u *p, *end = newstr + STRLEN(newstr);
1312 for (p = newstr; p[0] != NUL; ++p)
1314 if ((p = vim_strchr(p, '\\')) == NULL)
1315 break;
1316 mch_memmove(p, p + 1, end - p);
1318 str = newstr;
1320 query = migemo_query(migemo_object, str);
1321 if (query && STRLEN(query) < MIGEMO_QUERY_MAXSIZE)
1323 retval = searchit(win, buf, pos, dir, query, count, options,
1324 pat_use, stop_lnum, tm);
1325 didval = 1;
1327 if (query)
1328 migemo_release(migemo_object, query);
1329 if (newstr)
1330 vim_free(newstr);
1334 if (did)
1335 *did = didval;
1336 return retval;
1338 #endif /* USE_MIGEMO */
1341 * Highest level string search function.
1342 * Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc'
1343 * If 'dirc' is 0: use previous dir.
1344 * If 'pat' is NULL or empty : use previous string.
1345 * If 'options & SEARCH_REV' : go in reverse of previous dir.
1346 * If 'options & SEARCH_ECHO': echo the search command and handle options
1347 * If 'options & SEARCH_MSG' : may give error message
1348 * If 'options & SEARCH_OPT' : interpret optional flags
1349 * If 'options & SEARCH_HIS' : put search pattern in history
1350 * If 'options & SEARCH_NOOF': don't add offset to position
1351 * If 'options & SEARCH_MARK': set previous context mark
1352 * If 'options & SEARCH_KEEP': keep previous search pattern
1353 * If 'options & SEARCH_START': accept match at curpos itself
1354 * If 'options & SEARCH_PEEK': check for typed char, cancel search
1356 * Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this
1357 * makes the movement linewise without moving the match position.
1359 * return 0 for failure, 1 for found, 2 for found and line offset added
1362 do_search(oap, dirc, pat, count, options, tm)
1363 oparg_T *oap; /* can be NULL */
1364 int dirc; /* '/' or '?' */
1365 char_u *pat;
1366 long count;
1367 int options;
1368 proftime_T *tm; /* timeout limit or NULL */
1370 pos_T pos; /* position of the last match */
1371 char_u *searchstr;
1372 struct soffset old_off;
1373 int retval; /* Return value */
1374 char_u *p;
1375 long c;
1376 char_u *dircp;
1377 char_u *strcopy = NULL;
1378 char_u *ps;
1381 * A line offset is not remembered, this is vi compatible.
1383 if (spats[0].off.line && vim_strchr(p_cpo, CPO_LINEOFF) != NULL)
1385 spats[0].off.line = FALSE;
1386 spats[0].off.off = 0;
1390 * Save the values for when (options & SEARCH_KEEP) is used.
1391 * (there is no "if ()" around this because gcc wants them initialized)
1393 old_off = spats[0].off;
1395 pos = curwin->w_cursor; /* start searching at the cursor position */
1398 * Find out the direction of the search.
1400 if (dirc == 0)
1401 dirc = spats[0].off.dir;
1402 else
1404 spats[0].off.dir = dirc;
1405 #if defined(FEAT_EVAL)
1406 set_vv_searchforward();
1407 #endif
1409 if (options & SEARCH_REV)
1411 #ifdef WIN32
1412 /* There is a bug in the Visual C++ 2.2 compiler which means that
1413 * dirc always ends up being '/' */
1414 dirc = (dirc == '/') ? '?' : '/';
1415 #else
1416 if (dirc == '/')
1417 dirc = '?';
1418 else
1419 dirc = '/';
1420 #endif
1423 #ifdef FEAT_FOLDING
1424 /* If the cursor is in a closed fold, don't find another match in the same
1425 * fold. */
1426 if (dirc == '/')
1428 if (hasFolding(pos.lnum, NULL, &pos.lnum))
1429 pos.col = MAXCOL - 2; /* avoid overflow when adding 1 */
1431 else
1433 if (hasFolding(pos.lnum, &pos.lnum, NULL))
1434 pos.col = 0;
1436 #endif
1438 #ifdef FEAT_SEARCH_EXTRA
1440 * Turn 'hlsearch' highlighting back on.
1442 if (no_hlsearch && !(options & SEARCH_KEEP))
1444 redraw_all_later(SOME_VALID);
1445 no_hlsearch = FALSE;
1447 #endif
1450 * Repeat the search when pattern followed by ';', e.g. "/foo/;?bar".
1452 for (;;)
1454 searchstr = pat;
1455 dircp = NULL;
1456 /* use previous pattern */
1457 if (pat == NULL || *pat == NUL || *pat == dirc)
1459 if (spats[RE_SEARCH].pat == NULL) /* no previous pattern */
1461 EMSG(_(e_noprevre));
1462 retval = 0;
1463 goto end_do_search;
1465 /* make search_regcomp() use spats[RE_SEARCH].pat */
1466 searchstr = (char_u *)"";
1469 if (pat != NULL && *pat != NUL) /* look for (new) offset */
1472 * Find end of regular expression.
1473 * If there is a matching '/' or '?', toss it.
1475 ps = strcopy;
1476 p = skip_regexp(pat, dirc, (int)p_magic, &strcopy);
1477 if (strcopy != ps)
1479 /* made a copy of "pat" to change "\?" to "?" */
1480 searchcmdlen += (int)(STRLEN(pat) - STRLEN(strcopy));
1481 pat = strcopy;
1482 searchstr = strcopy;
1484 if (*p == dirc)
1486 dircp = p; /* remember where we put the NUL */
1487 *p++ = NUL;
1489 spats[0].off.line = FALSE;
1490 spats[0].off.end = FALSE;
1491 spats[0].off.off = 0;
1493 * Check for a line offset or a character offset.
1494 * For get_address (echo off) we don't check for a character
1495 * offset, because it is meaningless and the 's' could be a
1496 * substitute command.
1498 if (*p == '+' || *p == '-' || VIM_ISDIGIT(*p))
1499 spats[0].off.line = TRUE;
1500 else if ((options & SEARCH_OPT) &&
1501 (*p == 'e' || *p == 's' || *p == 'b'))
1503 if (*p == 'e') /* end */
1504 spats[0].off.end = SEARCH_END;
1505 ++p;
1507 if (VIM_ISDIGIT(*p) || *p == '+' || *p == '-') /* got an offset */
1509 /* 'nr' or '+nr' or '-nr' */
1510 if (VIM_ISDIGIT(*p) || VIM_ISDIGIT(*(p + 1)))
1511 spats[0].off.off = atol((char *)p);
1512 else if (*p == '-') /* single '-' */
1513 spats[0].off.off = -1;
1514 else /* single '+' */
1515 spats[0].off.off = 1;
1516 ++p;
1517 while (VIM_ISDIGIT(*p)) /* skip number */
1518 ++p;
1521 /* compute length of search command for get_address() */
1522 searchcmdlen += (int)(p - pat);
1524 pat = p; /* put pat after search command */
1527 if ((options & SEARCH_ECHO) && messaging()
1528 && !cmd_silent && msg_silent == 0)
1530 char_u *msgbuf;
1531 char_u *trunc;
1533 if (*searchstr == NUL)
1534 p = spats[last_idx].pat;
1535 else
1536 p = searchstr;
1537 msgbuf = alloc((unsigned)(STRLEN(p) + 40));
1538 if (msgbuf != NULL)
1540 msgbuf[0] = dirc;
1541 #ifdef FEAT_MBYTE
1542 if (enc_utf8 && utf_iscomposing(utf_ptr2char(p)))
1544 /* Use a space to draw the composing char on. */
1545 msgbuf[1] = ' ';
1546 STRCPY(msgbuf + 2, p);
1548 else
1549 #endif
1550 STRCPY(msgbuf + 1, p);
1551 if (spats[0].off.line || spats[0].off.end || spats[0].off.off)
1553 p = msgbuf + STRLEN(msgbuf);
1554 *p++ = dirc;
1555 if (spats[0].off.end)
1556 *p++ = 'e';
1557 else if (!spats[0].off.line)
1558 *p++ = 's';
1559 if (spats[0].off.off > 0 || spats[0].off.line)
1560 *p++ = '+';
1561 if (spats[0].off.off != 0 || spats[0].off.line)
1562 sprintf((char *)p, "%ld", spats[0].off.off);
1563 else
1564 *p = NUL;
1567 msg_start();
1568 trunc = msg_strtrunc(msgbuf, FALSE);
1570 #ifdef FEAT_RIGHTLEFT
1571 /* The search pattern could be shown on the right in rightleft
1572 * mode, but the 'ruler' and 'showcmd' area use it too, thus
1573 * it would be blanked out again very soon. Show it on the
1574 * left, but do reverse the text. */
1575 if (curwin->w_p_rl && *curwin->w_p_rlc == 's')
1577 char_u *r;
1579 r = reverse_text(trunc != NULL ? trunc : msgbuf);
1580 if (r != NULL)
1582 vim_free(trunc);
1583 trunc = r;
1586 #endif
1587 if (trunc != NULL)
1589 msg_outtrans(trunc);
1590 vim_free(trunc);
1592 else
1593 msg_outtrans(msgbuf);
1594 msg_clr_eos();
1595 msg_check();
1596 vim_free(msgbuf);
1598 gotocmdline(FALSE);
1599 out_flush();
1600 msg_nowait = TRUE; /* don't wait for this message */
1605 * If there is a character offset, subtract it from the current
1606 * position, so we don't get stuck at "?pat?e+2" or "/pat/s-2".
1607 * Skip this if pos.col is near MAXCOL (closed fold).
1608 * This is not done for a line offset, because then we would not be vi
1609 * compatible.
1611 if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2)
1613 if (spats[0].off.off > 0)
1615 for (c = spats[0].off.off; c; --c)
1616 if (decl(&pos) == -1)
1617 break;
1618 if (c) /* at start of buffer */
1620 pos.lnum = 0; /* allow lnum == 0 here */
1621 pos.col = MAXCOL;
1624 else
1626 for (c = spats[0].off.off; c; ++c)
1627 if (incl(&pos) == -1)
1628 break;
1629 if (c) /* at end of buffer */
1631 pos.lnum = curbuf->b_ml.ml_line_count + 1;
1632 pos.col = 0;
1637 #ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */
1638 if (p_altkeymap && curwin->w_p_rl)
1639 lrFswap(searchstr,0);
1640 #endif
1642 #ifdef USE_MIGEMO
1644 int did_migemo = 0;
1645 if (options & SEARCH_MIGEMO)
1646 c = searchit_migemo(
1647 curwin, curbuf, &pos,
1648 dirc == '/' ? FORWARD : BACKWARD,
1649 searchstr, count, spats[0].off.end + (options &
1650 (SEARCH_KEEP + SEARCH_PEEK + SEARCH_HIS
1651 + SEARCH_MSG + SEARCH_START
1652 + ((pat != NULL && *pat == ';') ?
1653 0 : SEARCH_NOOF))),
1654 RE_LAST, (linenr_T)0, tm, &did_migemo);
1655 if (!did_migemo)
1656 #endif /* USE_MIGEMO */
1657 c = searchit(curwin, curbuf, &pos, dirc == '/' ? FORWARD : BACKWARD,
1658 searchstr, count, spats[0].off.end + (options &
1659 (SEARCH_KEEP + SEARCH_PEEK + SEARCH_HIS
1660 + SEARCH_MSG + SEARCH_START
1661 + ((pat != NULL && *pat == ';') ? 0 : SEARCH_NOOF))),
1662 RE_LAST, (linenr_T)0, tm);
1663 #ifdef USE_MIGEMO
1665 #endif /* USE_MIGEMO */
1667 if (dircp != NULL)
1668 *dircp = dirc; /* restore second '/' or '?' for normal_cmd() */
1669 if (c == FAIL)
1671 retval = 0;
1672 goto end_do_search;
1674 if (spats[0].off.end && oap != NULL)
1675 oap->inclusive = TRUE; /* 'e' includes last character */
1677 retval = 1; /* pattern found */
1680 * Add character and/or line offset
1682 if (!(options & SEARCH_NOOF) || (pat != NULL && *pat == ';'))
1684 if (spats[0].off.line) /* Add the offset to the line number. */
1686 c = pos.lnum + spats[0].off.off;
1687 if (c < 1)
1688 pos.lnum = 1;
1689 else if (c > curbuf->b_ml.ml_line_count)
1690 pos.lnum = curbuf->b_ml.ml_line_count;
1691 else
1692 pos.lnum = c;
1693 pos.col = 0;
1695 retval = 2; /* pattern found, line offset added */
1697 else if (pos.col < MAXCOL - 2) /* just in case */
1699 /* to the right, check for end of file */
1700 c = spats[0].off.off;
1701 if (c > 0)
1703 while (c-- > 0)
1704 if (incl(&pos) == -1)
1705 break;
1707 /* to the left, check for start of file */
1708 else
1710 while (c++ < 0)
1711 if (decl(&pos) == -1)
1712 break;
1718 * The search command can be followed by a ';' to do another search.
1719 * For example: "/pat/;/foo/+3;?bar"
1720 * This is like doing another search command, except:
1721 * - The remembered direction '/' or '?' is from the first search.
1722 * - When an error happens the cursor isn't moved at all.
1723 * Don't do this when called by get_address() (it handles ';' itself).
1725 if (!(options & SEARCH_OPT) || pat == NULL || *pat != ';')
1726 break;
1728 dirc = *++pat;
1729 if (dirc != '?' && dirc != '/')
1731 retval = 0;
1732 EMSG(_("E386: Expected '?' or '/' after ';'"));
1733 goto end_do_search;
1735 ++pat;
1738 if (options & SEARCH_MARK)
1739 setpcmark();
1740 curwin->w_cursor = pos;
1741 curwin->w_set_curswant = TRUE;
1743 end_do_search:
1744 if (options & SEARCH_KEEP)
1745 spats[0].off = old_off;
1746 vim_free(strcopy);
1748 return retval;
1751 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1753 * search_for_exact_line(buf, pos, dir, pat)
1755 * Search for a line starting with the given pattern (ignoring leading
1756 * white-space), starting from pos and going in direction dir. pos will
1757 * contain the position of the match found. Blank lines match only if
1758 * ADDING is set. if p_ic is set then the pattern must be in lowercase.
1759 * Return OK for success, or FAIL if no line found.
1762 search_for_exact_line(buf, pos, dir, pat)
1763 buf_T *buf;
1764 pos_T *pos;
1765 int dir;
1766 char_u *pat;
1768 linenr_T start = 0;
1769 char_u *ptr;
1770 char_u *p;
1772 if (buf->b_ml.ml_line_count == 0)
1773 return FAIL;
1774 for (;;)
1776 pos->lnum += dir;
1777 if (pos->lnum < 1)
1779 if (p_ws)
1781 pos->lnum = buf->b_ml.ml_line_count;
1782 if (!shortmess(SHM_SEARCH))
1783 give_warning((char_u *)_(top_bot_msg), TRUE);
1785 else
1787 pos->lnum = 1;
1788 break;
1791 else if (pos->lnum > buf->b_ml.ml_line_count)
1793 if (p_ws)
1795 pos->lnum = 1;
1796 if (!shortmess(SHM_SEARCH))
1797 give_warning((char_u *)_(bot_top_msg), TRUE);
1799 else
1801 pos->lnum = 1;
1802 break;
1805 if (pos->lnum == start)
1806 break;
1807 if (start == 0)
1808 start = pos->lnum;
1809 ptr = ml_get_buf(buf, pos->lnum, FALSE);
1810 p = skipwhite(ptr);
1811 pos->col = (colnr_T) (p - ptr);
1813 /* when adding lines the matching line may be empty but it is not
1814 * ignored because we are interested in the next line -- Acevedo */
1815 if ((compl_cont_status & CONT_ADDING)
1816 && !(compl_cont_status & CONT_SOL))
1818 if ((p_ic ? MB_STRICMP(p, pat) : STRCMP(p, pat)) == 0)
1819 return OK;
1821 else if (*p != NUL) /* ignore empty lines */
1822 { /* expanding lines or words */
1823 if ((p_ic ? MB_STRNICMP(p, pat, compl_length)
1824 : STRNCMP(p, pat, compl_length)) == 0)
1825 return OK;
1828 return FAIL;
1830 #endif /* FEAT_INS_EXPAND */
1833 * Character Searches
1837 * Search for a character in a line. If "t_cmd" is FALSE, move to the
1838 * position of the character, otherwise move to just before the char.
1839 * Do this "cap->count1" times.
1840 * Return FAIL or OK.
1843 searchc(cap, t_cmd)
1844 cmdarg_T *cap;
1845 int t_cmd;
1847 int c = cap->nchar; /* char to search for */
1848 int dir = cap->arg; /* TRUE for searching forward */
1849 long count = cap->count1; /* repeat count */
1850 static int lastc = NUL; /* last character searched for */
1851 static int lastcdir; /* last direction of character search */
1852 static int last_t_cmd; /* last search t_cmd */
1853 int col;
1854 char_u *p;
1855 int len;
1856 #ifdef FEAT_MBYTE
1857 static char_u bytes[MB_MAXBYTES];
1858 static int bytelen = 1; /* >1 for multi-byte char */
1859 #endif
1861 if (c != NUL) /* normal search: remember args for repeat */
1863 if (!KeyStuffed) /* don't remember when redoing */
1865 lastc = c;
1866 lastcdir = dir;
1867 last_t_cmd = t_cmd;
1868 #ifdef FEAT_MBYTE
1869 bytelen = (*mb_char2bytes)(c, bytes);
1870 if (cap->ncharC1 != 0)
1872 bytelen += (*mb_char2bytes)(cap->ncharC1, bytes + bytelen);
1873 if (cap->ncharC2 != 0)
1874 bytelen += (*mb_char2bytes)(cap->ncharC2, bytes + bytelen);
1876 #endif
1879 else /* repeat previous search */
1881 if (lastc == NUL)
1882 return FAIL;
1883 if (dir) /* repeat in opposite direction */
1884 dir = -lastcdir;
1885 else
1886 dir = lastcdir;
1887 t_cmd = last_t_cmd;
1888 c = lastc;
1889 /* For multi-byte re-use last bytes[] and bytelen. */
1892 if (dir == BACKWARD)
1893 cap->oap->inclusive = FALSE;
1894 else
1895 cap->oap->inclusive = TRUE;
1897 p = ml_get_curline();
1898 col = curwin->w_cursor.col;
1899 len = (int)STRLEN(p);
1901 while (count--)
1903 #ifdef FEAT_MBYTE
1904 if (has_mbyte)
1906 for (;;)
1908 if (dir > 0)
1910 col += (*mb_ptr2len)(p + col);
1911 if (col >= len)
1912 return FAIL;
1914 else
1916 if (col == 0)
1917 return FAIL;
1918 col -= (*mb_head_off)(p, p + col - 1) + 1;
1920 if (bytelen == 1)
1922 if (p[col] == c)
1923 break;
1925 else
1927 if (vim_memcmp(p + col, bytes, bytelen) == 0)
1928 break;
1932 else
1933 #endif
1935 for (;;)
1937 if ((col += dir) < 0 || col >= len)
1938 return FAIL;
1939 if (p[col] == c)
1940 break;
1945 if (t_cmd)
1947 /* backup to before the character (possibly double-byte) */
1948 col -= dir;
1949 #ifdef FEAT_MBYTE
1950 if (has_mbyte)
1952 if (dir < 0)
1953 /* Landed on the search char which is bytelen long */
1954 col += bytelen - 1;
1955 else
1956 /* To previous char, which may be multi-byte. */
1957 col -= (*mb_head_off)(p, p + col);
1959 #endif
1961 curwin->w_cursor.col = col;
1963 return OK;
1967 * "Other" Searches
1971 * findmatch - find the matching paren or brace
1973 * Improvement over vi: Braces inside quotes are ignored.
1975 pos_T *
1976 findmatch(oap, initc)
1977 oparg_T *oap;
1978 int initc;
1980 return findmatchlimit(oap, initc, 0, 0);
1984 * Return TRUE if the character before "linep[col]" equals "ch".
1985 * Return FALSE if "col" is zero.
1986 * Update "*prevcol" to the column of the previous character, unless "prevcol"
1987 * is NULL.
1988 * Handles multibyte string correctly.
1990 static int
1991 check_prevcol(linep, col, ch, prevcol)
1992 char_u *linep;
1993 int col;
1994 int ch;
1995 int *prevcol;
1997 --col;
1998 #ifdef FEAT_MBYTE
1999 if (col > 0 && has_mbyte)
2000 col -= (*mb_head_off)(linep, linep + col);
2001 #endif
2002 if (prevcol)
2003 *prevcol = col;
2004 return (col >= 0 && linep[col] == ch) ? TRUE : FALSE;
2008 * findmatchlimit -- find the matching paren or brace, if it exists within
2009 * maxtravel lines of here. A maxtravel of 0 means search until falling off
2010 * the edge of the file.
2012 * "initc" is the character to find a match for. NUL means to find the
2013 * character at or after the cursor.
2015 * flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#')
2016 * FM_FORWARD search forwards (when initc is '/', '*' or '#')
2017 * FM_BLOCKSTOP stop at start/end of block ({ or } in column 0)
2018 * FM_SKIPCOMM skip comments (not implemented yet!)
2020 * "oap" is only used to set oap->motion_type for a linewise motion, it be
2021 * NULL
2024 pos_T *
2025 findmatchlimit(oap, initc, flags, maxtravel)
2026 oparg_T *oap;
2027 int initc;
2028 int flags;
2029 int maxtravel;
2031 static pos_T pos; /* current search position */
2032 int findc = 0; /* matching brace */
2033 int c;
2034 int count = 0; /* cumulative number of braces */
2035 int backwards = FALSE; /* init for gcc */
2036 int inquote = FALSE; /* TRUE when inside quotes */
2037 char_u *linep; /* pointer to current line */
2038 char_u *ptr;
2039 int do_quotes; /* check for quotes in current line */
2040 int at_start; /* do_quotes value at start position */
2041 int hash_dir = 0; /* Direction searched for # things */
2042 int comment_dir = 0; /* Direction searched for comments */
2043 pos_T match_pos; /* Where last slash-star was found */
2044 int start_in_quotes; /* start position is in quotes */
2045 int traveled = 0; /* how far we've searched so far */
2046 int ignore_cend = FALSE; /* ignore comment end */
2047 int cpo_match; /* vi compatible matching */
2048 int cpo_bsl; /* don't recognize backslashes */
2049 int match_escaped = 0; /* search for escaped match */
2050 int dir; /* Direction to search */
2051 int comment_col = MAXCOL; /* start of / / comment */
2052 #ifdef FEAT_LISP
2053 int lispcomm = FALSE; /* inside of Lisp-style comment */
2054 int lisp = curbuf->b_p_lisp; /* engage Lisp-specific hacks ;) */
2055 #endif
2057 pos = curwin->w_cursor;
2058 linep = ml_get(pos.lnum);
2060 cpo_match = (vim_strchr(p_cpo, CPO_MATCH) != NULL);
2061 cpo_bsl = (vim_strchr(p_cpo, CPO_MATCHBSL) != NULL);
2063 /* Direction to search when initc is '/', '*' or '#' */
2064 if (flags & FM_BACKWARD)
2065 dir = BACKWARD;
2066 else if (flags & FM_FORWARD)
2067 dir = FORWARD;
2068 else
2069 dir = 0;
2072 * if initc given, look in the table for the matching character
2073 * '/' and '*' are special cases: look for start or end of comment.
2074 * When '/' is used, we ignore running backwards into an star-slash, for
2075 * "[*" command, we just want to find any comment.
2077 if (initc == '/' || initc == '*')
2079 comment_dir = dir;
2080 if (initc == '/')
2081 ignore_cend = TRUE;
2082 backwards = (dir == FORWARD) ? FALSE : TRUE;
2083 initc = NUL;
2085 else if (initc != '#' && initc != NUL)
2087 /* 'matchpairs' is "x:y,x:y" */
2088 for (ptr = curbuf->b_p_mps; *ptr; ptr += 2)
2090 if (*ptr == initc)
2092 findc = initc;
2093 initc = ptr[2];
2094 backwards = TRUE;
2095 break;
2097 ptr += 2;
2098 if (*ptr == initc)
2100 findc = initc;
2101 initc = ptr[-2];
2102 backwards = FALSE;
2103 break;
2105 if (ptr[1] != ',')
2106 break;
2108 if (!findc) /* invalid initc! */
2109 return NULL;
2112 * Either initc is '#', or no initc was given and we need to look under the
2113 * cursor.
2115 else
2117 if (initc == '#')
2119 hash_dir = dir;
2121 else
2124 * initc was not given, must look for something to match under
2125 * or near the cursor.
2126 * Only check for special things when 'cpo' doesn't have '%'.
2128 if (!cpo_match)
2130 /* Are we before or at #if, #else etc.? */
2131 ptr = skipwhite(linep);
2132 if (*ptr == '#' && pos.col <= (colnr_T)(ptr - linep))
2134 ptr = skipwhite(ptr + 1);
2135 if ( STRNCMP(ptr, "if", 2) == 0
2136 || STRNCMP(ptr, "endif", 5) == 0
2137 || STRNCMP(ptr, "el", 2) == 0)
2138 hash_dir = 1;
2141 /* Are we on a comment? */
2142 else if (linep[pos.col] == '/')
2144 if (linep[pos.col + 1] == '*')
2146 comment_dir = FORWARD;
2147 backwards = FALSE;
2148 pos.col++;
2150 else if (pos.col > 0 && linep[pos.col - 1] == '*')
2152 comment_dir = BACKWARD;
2153 backwards = TRUE;
2154 pos.col--;
2157 else if (linep[pos.col] == '*')
2159 if (linep[pos.col + 1] == '/')
2161 comment_dir = BACKWARD;
2162 backwards = TRUE;
2164 else if (pos.col > 0 && linep[pos.col - 1] == '/')
2166 comment_dir = FORWARD;
2167 backwards = FALSE;
2173 * If we are not on a comment or the # at the start of a line, then
2174 * look for brace anywhere on this line after the cursor.
2176 if (!hash_dir && !comment_dir)
2179 * Find the brace under or after the cursor.
2180 * If beyond the end of the line, use the last character in
2181 * the line.
2183 if (linep[pos.col] == NUL && pos.col)
2184 --pos.col;
2185 for (;;)
2187 initc = linep[pos.col];
2188 if (initc == NUL)
2189 break;
2191 for (ptr = curbuf->b_p_mps; *ptr; ++ptr)
2193 if (*ptr == initc)
2195 findc = ptr[2];
2196 backwards = FALSE;
2197 break;
2199 ptr += 2;
2200 if (*ptr == initc)
2202 findc = ptr[-2];
2203 backwards = TRUE;
2204 break;
2206 if (!*++ptr)
2207 break;
2209 if (findc)
2210 break;
2211 #ifdef FEAT_MBYTE
2212 if (has_mbyte)
2213 pos.col += (*mb_ptr2len)(linep + pos.col);
2214 else
2215 #endif
2216 ++pos.col;
2218 if (!findc)
2220 /* no brace in the line, maybe use " #if" then */
2221 if (!cpo_match && *skipwhite(linep) == '#')
2222 hash_dir = 1;
2223 else
2224 return NULL;
2226 else if (!cpo_bsl)
2228 int col, bslcnt = 0;
2230 /* Set "match_escaped" if there are an odd number of
2231 * backslashes. */
2232 for (col = pos.col; check_prevcol(linep, col, '\\', &col);)
2233 bslcnt++;
2234 match_escaped = (bslcnt & 1);
2238 if (hash_dir)
2241 * Look for matching #if, #else, #elif, or #endif
2243 if (oap != NULL)
2244 oap->motion_type = MLINE; /* Linewise for this case only */
2245 if (initc != '#')
2247 ptr = skipwhite(skipwhite(linep) + 1);
2248 if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0)
2249 hash_dir = 1;
2250 else if (STRNCMP(ptr, "endif", 5) == 0)
2251 hash_dir = -1;
2252 else
2253 return NULL;
2255 pos.col = 0;
2256 while (!got_int)
2258 if (hash_dir > 0)
2260 if (pos.lnum == curbuf->b_ml.ml_line_count)
2261 break;
2263 else if (pos.lnum == 1)
2264 break;
2265 pos.lnum += hash_dir;
2266 linep = ml_get(pos.lnum);
2267 line_breakcheck(); /* check for CTRL-C typed */
2268 ptr = skipwhite(linep);
2269 if (*ptr != '#')
2270 continue;
2271 pos.col = (colnr_T) (ptr - linep);
2272 ptr = skipwhite(ptr + 1);
2273 if (hash_dir > 0)
2275 if (STRNCMP(ptr, "if", 2) == 0)
2276 count++;
2277 else if (STRNCMP(ptr, "el", 2) == 0)
2279 if (count == 0)
2280 return &pos;
2282 else if (STRNCMP(ptr, "endif", 5) == 0)
2284 if (count == 0)
2285 return &pos;
2286 count--;
2289 else
2291 if (STRNCMP(ptr, "if", 2) == 0)
2293 if (count == 0)
2294 return &pos;
2295 count--;
2297 else if (initc == '#' && STRNCMP(ptr, "el", 2) == 0)
2299 if (count == 0)
2300 return &pos;
2302 else if (STRNCMP(ptr, "endif", 5) == 0)
2303 count++;
2306 return NULL;
2310 #ifdef FEAT_RIGHTLEFT
2311 /* This is just guessing: when 'rightleft' is set, search for a matching
2312 * paren/brace in the other direction. */
2313 if (curwin->w_p_rl && vim_strchr((char_u *)"()[]{}<>", initc) != NULL)
2314 backwards = !backwards;
2315 #endif
2317 do_quotes = -1;
2318 start_in_quotes = MAYBE;
2319 clearpos(&match_pos);
2321 /* backward search: Check if this line contains a single-line comment */
2322 if ((backwards && comment_dir)
2323 #ifdef FEAT_LISP
2324 || lisp
2325 #endif
2327 comment_col = check_linecomment(linep);
2328 #ifdef FEAT_LISP
2329 if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col)
2330 lispcomm = TRUE; /* find match inside this comment */
2331 #endif
2332 while (!got_int)
2335 * Go to the next position, forward or backward. We could use
2336 * inc() and dec() here, but that is much slower
2338 if (backwards)
2340 #ifdef FEAT_LISP
2341 /* char to match is inside of comment, don't search outside */
2342 if (lispcomm && pos.col < (colnr_T)comment_col)
2343 break;
2344 #endif
2345 if (pos.col == 0) /* at start of line, go to prev. one */
2347 if (pos.lnum == 1) /* start of file */
2348 break;
2349 --pos.lnum;
2351 if (maxtravel > 0 && ++traveled > maxtravel)
2352 break;
2354 linep = ml_get(pos.lnum);
2355 pos.col = (colnr_T)STRLEN(linep); /* pos.col on trailing NUL */
2356 do_quotes = -1;
2357 line_breakcheck();
2359 /* Check if this line contains a single-line comment */
2360 if (comment_dir
2361 #ifdef FEAT_LISP
2362 || lisp
2363 #endif
2365 comment_col = check_linecomment(linep);
2366 #ifdef FEAT_LISP
2367 /* skip comment */
2368 if (lisp && comment_col != MAXCOL)
2369 pos.col = comment_col;
2370 #endif
2372 else
2374 --pos.col;
2375 #ifdef FEAT_MBYTE
2376 if (has_mbyte)
2377 pos.col -= (*mb_head_off)(linep, linep + pos.col);
2378 #endif
2381 else /* forward search */
2383 if (linep[pos.col] == NUL
2384 /* at end of line, go to next one */
2385 #ifdef FEAT_LISP
2386 /* don't search for match in comment */
2387 || (lisp && comment_col != MAXCOL
2388 && pos.col == (colnr_T)comment_col)
2389 #endif
2392 if (pos.lnum == curbuf->b_ml.ml_line_count /* end of file */
2393 #ifdef FEAT_LISP
2394 /* line is exhausted and comment with it,
2395 * don't search for match in code */
2396 || lispcomm
2397 #endif
2399 break;
2400 ++pos.lnum;
2402 if (maxtravel && traveled++ > maxtravel)
2403 break;
2405 linep = ml_get(pos.lnum);
2406 pos.col = 0;
2407 do_quotes = -1;
2408 line_breakcheck();
2409 #ifdef FEAT_LISP
2410 if (lisp) /* find comment pos in new line */
2411 comment_col = check_linecomment(linep);
2412 #endif
2414 else
2416 #ifdef FEAT_MBYTE
2417 if (has_mbyte)
2418 pos.col += (*mb_ptr2len)(linep + pos.col);
2419 else
2420 #endif
2421 ++pos.col;
2426 * If FM_BLOCKSTOP given, stop at a '{' or '}' in column 0.
2428 if (pos.col == 0 && (flags & FM_BLOCKSTOP) &&
2429 (linep[0] == '{' || linep[0] == '}'))
2431 if (linep[0] == findc && count == 0) /* match! */
2432 return &pos;
2433 break; /* out of scope */
2436 if (comment_dir)
2438 /* Note: comments do not nest, and we ignore quotes in them */
2439 /* TODO: ignore comment brackets inside strings */
2440 if (comment_dir == FORWARD)
2442 if (linep[pos.col] == '*' && linep[pos.col + 1] == '/')
2444 pos.col++;
2445 return &pos;
2448 else /* Searching backwards */
2451 * A comment may contain / * or / /, it may also start or end
2452 * with / * /. Ignore a / * after / /.
2454 if (pos.col == 0)
2455 continue;
2456 else if ( linep[pos.col - 1] == '/'
2457 && linep[pos.col] == '*'
2458 && (int)pos.col < comment_col)
2460 count++;
2461 match_pos = pos;
2462 match_pos.col--;
2464 else if (linep[pos.col - 1] == '*' && linep[pos.col] == '/')
2466 if (count > 0)
2467 pos = match_pos;
2468 else if (pos.col > 1 && linep[pos.col - 2] == '/'
2469 && (int)pos.col <= comment_col)
2470 pos.col -= 2;
2471 else if (ignore_cend)
2472 continue;
2473 else
2474 return NULL;
2475 return &pos;
2478 continue;
2482 * If smart matching ('cpoptions' does not contain '%'), braces inside
2483 * of quotes are ignored, but only if there is an even number of
2484 * quotes in the line.
2486 if (cpo_match)
2487 do_quotes = 0;
2488 else if (do_quotes == -1)
2491 * Count the number of quotes in the line, skipping \" and '"'.
2492 * Watch out for "\\".
2494 at_start = do_quotes;
2495 for (ptr = linep; *ptr; ++ptr)
2497 if (ptr == linep + pos.col + backwards)
2498 at_start = (do_quotes & 1);
2499 if (*ptr == '"'
2500 && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\''))
2501 ++do_quotes;
2502 if (*ptr == '\\' && ptr[1] != NUL)
2503 ++ptr;
2505 do_quotes &= 1; /* result is 1 with even number of quotes */
2508 * If we find an uneven count, check current line and previous
2509 * one for a '\' at the end.
2511 if (!do_quotes)
2513 inquote = FALSE;
2514 if (ptr[-1] == '\\')
2516 do_quotes = 1;
2517 if (start_in_quotes == MAYBE)
2519 /* Do we need to use at_start here? */
2520 inquote = TRUE;
2521 start_in_quotes = TRUE;
2523 else if (backwards)
2524 inquote = TRUE;
2526 if (pos.lnum > 1)
2528 ptr = ml_get(pos.lnum - 1);
2529 if (*ptr && *(ptr + STRLEN(ptr) - 1) == '\\')
2531 do_quotes = 1;
2532 if (start_in_quotes == MAYBE)
2534 inquote = at_start;
2535 if (inquote)
2536 start_in_quotes = TRUE;
2538 else if (!backwards)
2539 inquote = TRUE;
2542 /* ml_get() only keeps one line, need to get linep again */
2543 linep = ml_get(pos.lnum);
2547 if (start_in_quotes == MAYBE)
2548 start_in_quotes = FALSE;
2551 * If 'smartmatch' is set:
2552 * Things inside quotes are ignored by setting 'inquote'. If we
2553 * find a quote without a preceding '\' invert 'inquote'. At the
2554 * end of a line not ending in '\' we reset 'inquote'.
2556 * In lines with an uneven number of quotes (without preceding '\')
2557 * we do not know which part to ignore. Therefore we only set
2558 * inquote if the number of quotes in a line is even, unless this
2559 * line or the previous one ends in a '\'. Complicated, isn't it?
2561 switch (c = linep[pos.col])
2563 case NUL:
2564 /* at end of line without trailing backslash, reset inquote */
2565 if (pos.col == 0 || linep[pos.col - 1] != '\\')
2567 inquote = FALSE;
2568 start_in_quotes = FALSE;
2570 break;
2572 case '"':
2573 /* a quote that is preceded with an odd number of backslashes is
2574 * ignored */
2575 if (do_quotes)
2577 int col;
2579 for (col = pos.col - 1; col >= 0; --col)
2580 if (linep[col] != '\\')
2581 break;
2582 if ((((int)pos.col - 1 - col) & 1) == 0)
2584 inquote = !inquote;
2585 start_in_quotes = FALSE;
2588 break;
2591 * If smart matching ('cpoptions' does not contain '%'):
2592 * Skip things in single quotes: 'x' or '\x'. Be careful for single
2593 * single quotes, eg jon's. Things like '\233' or '\x3f' are not
2594 * skipped, there is never a brace in them.
2595 * Ignore this when finding matches for `'.
2597 case '\'':
2598 if (!cpo_match && initc != '\'' && findc != '\'')
2600 if (backwards)
2602 if (pos.col > 1)
2604 if (linep[pos.col - 2] == '\'')
2606 pos.col -= 2;
2607 break;
2609 else if (linep[pos.col - 2] == '\\' &&
2610 pos.col > 2 && linep[pos.col - 3] == '\'')
2612 pos.col -= 3;
2613 break;
2617 else if (linep[pos.col + 1]) /* forward search */
2619 if (linep[pos.col + 1] == '\\' &&
2620 linep[pos.col + 2] && linep[pos.col + 3] == '\'')
2622 pos.col += 3;
2623 break;
2625 else if (linep[pos.col + 2] == '\'')
2627 pos.col += 2;
2628 break;
2632 /* FALLTHROUGH */
2634 default:
2635 #ifdef FEAT_LISP
2637 * For Lisp skip over backslashed (), {} and [].
2638 * (actually, we skip #\( et al)
2640 if (curbuf->b_p_lisp
2641 && vim_strchr((char_u *)"(){}[]", c) != NULL
2642 && pos.col > 1
2643 && check_prevcol(linep, pos.col, '\\', NULL)
2644 && check_prevcol(linep, pos.col - 1, '#', NULL))
2645 break;
2646 #endif
2648 /* Check for match outside of quotes, and inside of
2649 * quotes when the start is also inside of quotes. */
2650 if ((!inquote || start_in_quotes == TRUE)
2651 && (c == initc || c == findc))
2653 int col, bslcnt = 0;
2655 if (!cpo_bsl)
2657 for (col = pos.col; check_prevcol(linep, col, '\\', &col);)
2658 bslcnt++;
2660 /* Only accept a match when 'M' is in 'cpo' or when escaping
2661 * is what we expect. */
2662 if (cpo_bsl || (bslcnt & 1) == match_escaped)
2664 if (c == initc)
2665 count++;
2666 else
2668 if (count == 0)
2669 return &pos;
2670 count--;
2677 if (comment_dir == BACKWARD && count > 0)
2679 pos = match_pos;
2680 return &pos;
2682 return (pos_T *)NULL; /* never found it */
2686 * Check if line[] contains a / / comment.
2687 * Return MAXCOL if not, otherwise return the column.
2688 * TODO: skip strings.
2690 static int
2691 check_linecomment(line)
2692 char_u *line;
2694 char_u *p;
2696 p = line;
2697 #ifdef FEAT_LISP
2698 /* skip Lispish one-line comments */
2699 if (curbuf->b_p_lisp)
2701 if (vim_strchr(p, ';') != NULL) /* there may be comments */
2703 int instr = FALSE; /* inside of string */
2705 p = line; /* scan from start */
2706 while ((p = vim_strpbrk(p, (char_u *)"\";")) != NULL)
2708 if (*p == '"')
2710 if (instr)
2712 if (*(p - 1) != '\\') /* skip escaped quote */
2713 instr = FALSE;
2715 else if (p == line || ((p - line) >= 2
2716 /* skip #\" form */
2717 && *(p - 1) != '\\' && *(p - 2) != '#'))
2718 instr = TRUE;
2720 else if (!instr && ((p - line) < 2
2721 || (*(p - 1) != '\\' && *(p - 2) != '#')))
2722 break; /* found! */
2723 ++p;
2726 else
2727 p = NULL;
2729 else
2730 #endif
2731 while ((p = vim_strchr(p, '/')) != NULL)
2733 /* accept a double /, unless it's preceded with * and followed by *,
2734 * because * / / * is an end and start of a C comment */
2735 if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*'))
2736 break;
2737 ++p;
2740 if (p == NULL)
2741 return MAXCOL;
2742 return (int)(p - line);
2746 * Move cursor briefly to character matching the one under the cursor.
2747 * Used for Insert mode and "r" command.
2748 * Show the match only if it is visible on the screen.
2749 * If there isn't a match, then beep.
2751 void
2752 showmatch(c)
2753 int c; /* char to show match for */
2755 pos_T *lpos, save_cursor;
2756 pos_T mpos;
2757 colnr_T vcol;
2758 long save_so;
2759 long save_siso;
2760 #ifdef CURSOR_SHAPE
2761 int save_state;
2762 #endif
2763 colnr_T save_dollar_vcol;
2764 char_u *p;
2767 * Only show match for chars in the 'matchpairs' option.
2769 /* 'matchpairs' is "x:y,x:y" */
2770 for (p = curbuf->b_p_mps; *p != NUL; p += 2)
2772 #ifdef FEAT_RIGHTLEFT
2773 if (*p == c && (curwin->w_p_rl ^ p_ri))
2774 break;
2775 #endif
2776 p += 2;
2777 if (*p == c
2778 #ifdef FEAT_RIGHTLEFT
2779 && !(curwin->w_p_rl ^ p_ri)
2780 #endif
2782 break;
2783 if (p[1] != ',')
2784 return;
2787 if ((lpos = findmatch(NULL, NUL)) == NULL) /* no match, so beep */
2788 vim_beep();
2789 else if (lpos->lnum >= curwin->w_topline)
2791 if (!curwin->w_p_wrap)
2792 getvcol(curwin, lpos, NULL, &vcol, NULL);
2793 if (curwin->w_p_wrap || (vcol >= curwin->w_leftcol
2794 && vcol < curwin->w_leftcol + W_WIDTH(curwin)))
2796 mpos = *lpos; /* save the pos, update_screen() may change it */
2797 save_cursor = curwin->w_cursor;
2798 save_so = p_so;
2799 save_siso = p_siso;
2800 /* Handle "$" in 'cpo': If the ')' is typed on top of the "$",
2801 * stop displaying the "$". */
2802 if (dollar_vcol > 0 && dollar_vcol == curwin->w_virtcol)
2803 dollar_vcol = 0;
2804 ++curwin->w_virtcol; /* do display ')' just before "$" */
2805 update_screen(VALID); /* show the new char first */
2807 save_dollar_vcol = dollar_vcol;
2808 #ifdef CURSOR_SHAPE
2809 save_state = State;
2810 State = SHOWMATCH;
2811 ui_cursor_shape(); /* may show different cursor shape */
2812 #endif
2813 curwin->w_cursor = mpos; /* move to matching char */
2814 p_so = 0; /* don't use 'scrolloff' here */
2815 p_siso = 0; /* don't use 'sidescrolloff' here */
2816 showruler(FALSE);
2817 setcursor();
2818 cursor_on(); /* make sure that the cursor is shown */
2819 out_flush();
2820 #ifdef FEAT_GUI
2821 if (gui.in_use)
2823 gui_update_cursor(TRUE, FALSE);
2824 gui_mch_flush();
2826 #endif
2827 /* Restore dollar_vcol(), because setcursor() may call curs_rows()
2828 * which resets it if the matching position is in a previous line
2829 * and has a higher column number. */
2830 dollar_vcol = save_dollar_vcol;
2833 * brief pause, unless 'm' is present in 'cpo' and a character is
2834 * available.
2836 if (vim_strchr(p_cpo, CPO_SHOWMATCH) != NULL)
2837 ui_delay(p_mat * 100L, TRUE);
2838 else if (!char_avail())
2839 ui_delay(p_mat * 100L, FALSE);
2840 curwin->w_cursor = save_cursor; /* restore cursor position */
2841 p_so = save_so;
2842 p_siso = save_siso;
2843 #ifdef CURSOR_SHAPE
2844 State = save_state;
2845 ui_cursor_shape(); /* may show different cursor shape */
2846 #endif
2852 * findsent(dir, count) - Find the start of the next sentence in direction
2853 * "dir" Sentences are supposed to end in ".", "!" or "?" followed by white
2854 * space or a line break. Also stop at an empty line.
2855 * Return OK if the next sentence was found.
2858 findsent(dir, count)
2859 int dir;
2860 long count;
2862 pos_T pos, tpos;
2863 int c;
2864 int (*func) __ARGS((pos_T *));
2865 int startlnum;
2866 int noskip = FALSE; /* do not skip blanks */
2867 int cpo_J;
2868 int found_dot;
2870 pos = curwin->w_cursor;
2871 if (dir == FORWARD)
2872 func = incl;
2873 else
2874 func = decl;
2876 while (count--)
2879 * if on an empty line, skip upto a non-empty line
2881 if (gchar_pos(&pos) == NUL)
2884 if ((*func)(&pos) == -1)
2885 break;
2886 while (gchar_pos(&pos) == NUL);
2887 if (dir == FORWARD)
2888 goto found;
2891 * if on the start of a paragraph or a section and searching forward,
2892 * go to the next line
2894 else if (dir == FORWARD && pos.col == 0 &&
2895 startPS(pos.lnum, NUL, FALSE))
2897 if (pos.lnum == curbuf->b_ml.ml_line_count)
2898 return FAIL;
2899 ++pos.lnum;
2900 goto found;
2902 else if (dir == BACKWARD)
2903 decl(&pos);
2905 /* go back to the previous non-blank char */
2906 found_dot = FALSE;
2907 while ((c = gchar_pos(&pos)) == ' ' || c == '\t' ||
2908 (dir == BACKWARD && vim_strchr((char_u *)".!?)]\"'", c) != NULL)
2909 #ifdef FEAT_MBYTE
2910 || (dir == BACKWARD && (*mb_char2len)(c) > 1
2911 && mb_get_class(ml_get_pos(&pos)) == 1)
2912 #endif
2915 if (vim_strchr((char_u *)".!?", c) != NULL)
2917 /* Only skip over a '.', '!' and '?' once. */
2918 if (found_dot)
2919 break;
2920 found_dot = TRUE;
2922 if (decl(&pos) == -1)
2923 break;
2924 /* when going forward: Stop in front of empty line */
2925 if (lineempty(pos.lnum) && dir == FORWARD)
2927 incl(&pos);
2928 goto found;
2932 /* remember the line where the search started */
2933 startlnum = pos.lnum;
2934 cpo_J = vim_strchr(p_cpo, CPO_ENDOFSENT) != NULL;
2936 for (;;) /* find end of sentence */
2938 c = gchar_pos(&pos);
2939 if (c == NUL || (pos.col == 0 && startPS(pos.lnum, NUL, FALSE)))
2941 if (dir == BACKWARD && pos.lnum != startlnum)
2942 ++pos.lnum;
2943 break;
2945 if (c == '.' || c == '!' || c == '?')
2947 tpos = pos;
2949 if ((c = inc(&tpos)) == -1)
2950 break;
2951 while (vim_strchr((char_u *)")]\"'", c = gchar_pos(&tpos))
2952 != NULL);
2953 if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL
2954 || (cpo_J && (c == ' ' && inc(&tpos) >= 0
2955 && gchar_pos(&tpos) == ' ')))
2957 pos = tpos;
2958 if (gchar_pos(&pos) == NUL) /* skip NUL at EOL */
2959 inc(&pos);
2960 break;
2963 #ifdef FEAT_MBYTE
2964 if (has_mbyte && (*mb_char2len)(c) > 1
2965 && mb_get_class(ml_get_pos(&pos)) == 1)
2967 tpos = pos;
2968 for (;;)
2970 c = inc(&tpos);
2971 if (c == -1 || (*mb_char2len)(c) <= 1
2972 || mb_get_class(ml_get_pos(&tpos)) != 1)
2973 break;
2975 pos = tpos;
2976 if (gchar_pos(&pos) == NUL)
2977 inc(&pos);
2978 break;
2980 #endif
2981 if ((*func)(&pos) == -1)
2983 if (count)
2984 return FAIL;
2985 noskip = TRUE;
2986 break;
2989 found:
2990 /* skip white space */
2991 while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t'))
2992 if (incl(&pos) == -1)
2993 break;
2996 setpcmark();
2997 curwin->w_cursor = pos;
2998 return OK;
3002 * Find the next paragraph or section in direction 'dir'.
3003 * Paragraphs are currently supposed to be separated by empty lines.
3004 * If 'what' is NUL we go to the next paragraph.
3005 * If 'what' is '{' or '}' we go to the next section.
3006 * If 'both' is TRUE also stop at '}'.
3007 * Return TRUE if the next paragraph or section was found.
3010 findpar(pincl, dir, count, what, both)
3011 int *pincl; /* Return: TRUE if last char is to be included */
3012 int dir;
3013 long count;
3014 int what;
3015 int both;
3017 linenr_T curr;
3018 int did_skip; /* TRUE after separating lines have been skipped */
3019 int first; /* TRUE on first line */
3020 int posix = (vim_strchr(p_cpo, CPO_PARA) != NULL);
3021 #ifdef FEAT_FOLDING
3022 linenr_T fold_first; /* first line of a closed fold */
3023 linenr_T fold_last; /* last line of a closed fold */
3024 int fold_skipped; /* TRUE if a closed fold was skipped this
3025 iteration */
3026 #endif
3028 curr = curwin->w_cursor.lnum;
3030 while (count--)
3032 did_skip = FALSE;
3033 for (first = TRUE; ; first = FALSE)
3035 if (*ml_get(curr) != NUL)
3036 did_skip = TRUE;
3038 #ifdef FEAT_FOLDING
3039 /* skip folded lines */
3040 fold_skipped = FALSE;
3041 if (first && hasFolding(curr, &fold_first, &fold_last))
3043 curr = ((dir > 0) ? fold_last : fold_first) + dir;
3044 fold_skipped = TRUE;
3046 #endif
3048 /* POSIX has it's own ideas of what a paragraph boundary is and it
3049 * doesn't match historical Vi: It also stops at a "{" in the
3050 * first column and at an empty line. */
3051 if (!first && did_skip && (startPS(curr, what, both)
3052 || (posix && what == NUL && *ml_get(curr) == '{')))
3053 break;
3055 #ifdef FEAT_FOLDING
3056 if (fold_skipped)
3057 curr -= dir;
3058 #endif
3059 if ((curr += dir) < 1 || curr > curbuf->b_ml.ml_line_count)
3061 if (count)
3062 return FALSE;
3063 curr -= dir;
3064 break;
3068 setpcmark();
3069 if (both && *ml_get(curr) == '}') /* include line with '}' */
3070 ++curr;
3071 curwin->w_cursor.lnum = curr;
3072 if (curr == curbuf->b_ml.ml_line_count && what != '}')
3074 if ((curwin->w_cursor.col = (colnr_T)STRLEN(ml_get(curr))) != 0)
3076 --curwin->w_cursor.col;
3077 *pincl = TRUE;
3080 else
3081 curwin->w_cursor.col = 0;
3082 return TRUE;
3086 * check if the string 's' is a nroff macro that is in option 'opt'
3088 static int
3089 inmacro(opt, s)
3090 char_u *opt;
3091 char_u *s;
3093 char_u *macro;
3095 for (macro = opt; macro[0]; ++macro)
3097 /* Accept two characters in the option being equal to two characters
3098 * in the line. A space in the option matches with a space in the
3099 * line or the line having ended. */
3100 if ( (macro[0] == s[0]
3101 || (macro[0] == ' '
3102 && (s[0] == NUL || s[0] == ' ')))
3103 && (macro[1] == s[1]
3104 || ((macro[1] == NUL || macro[1] == ' ')
3105 && (s[0] == NUL || s[1] == NUL || s[1] == ' '))))
3106 break;
3107 ++macro;
3108 if (macro[0] == NUL)
3109 break;
3111 return (macro[0] != NUL);
3115 * startPS: return TRUE if line 'lnum' is the start of a section or paragraph.
3116 * If 'para' is '{' or '}' only check for sections.
3117 * If 'both' is TRUE also stop at '}'
3120 startPS(lnum, para, both)
3121 linenr_T lnum;
3122 int para;
3123 int both;
3125 char_u *s;
3127 s = ml_get(lnum);
3128 if (*s == para || *s == '\f' || (both && *s == '}'))
3129 return TRUE;
3130 if (*s == '.' && (inmacro(p_sections, s + 1) ||
3131 (!para && inmacro(p_para, s + 1))))
3132 return TRUE;
3133 return FALSE;
3137 * The following routines do the word searches performed by the 'w', 'W',
3138 * 'b', 'B', 'e', and 'E' commands.
3142 * To perform these searches, characters are placed into one of three
3143 * classes, and transitions between classes determine word boundaries.
3145 * The classes are:
3147 * 0 - white space
3148 * 1 - punctuation
3149 * 2 or higher - keyword characters (letters, digits and underscore)
3152 static int cls_bigword; /* TRUE for "W", "B" or "E" */
3155 * cls() - returns the class of character at curwin->w_cursor
3157 * If a 'W', 'B', or 'E' motion is being done (cls_bigword == TRUE), chars
3158 * from class 2 and higher are reported as class 1 since only white space
3159 * boundaries are of interest.
3161 static int
3162 cls()
3164 int c;
3166 c = gchar_cursor();
3167 #ifdef FEAT_FKMAP /* when 'akm' (Farsi mode), take care of Farsi blank */
3168 if (p_altkeymap && c == F_BLANK)
3169 return 0;
3170 #endif
3171 if (c == ' ' || c == '\t' || c == NUL)
3172 return 0;
3173 #ifdef FEAT_MBYTE
3174 if (enc_dbcs != 0 && c > 0xFF)
3176 /* If cls_bigword, report multi-byte chars as class 1. */
3177 if (enc_dbcs == DBCS_KOR && cls_bigword)
3178 return 1;
3180 /* process code leading/trailing bytes */
3181 return dbcs_class(((unsigned)c >> 8), (c & 0xFF));
3183 if (enc_utf8)
3185 c = utf_class(c);
3186 if (c != 0 && cls_bigword)
3187 return 1;
3188 return c;
3190 #endif
3192 /* If cls_bigword is TRUE, report all non-blanks as class 1. */
3193 if (cls_bigword)
3194 return 1;
3196 if (vim_iswordc(c))
3197 return 2;
3198 return 1;
3203 * fwd_word(count, type, eol) - move forward one word
3205 * Returns FAIL if the cursor was already at the end of the file.
3206 * If eol is TRUE, last word stops at end of line (for operators).
3209 fwd_word(count, bigword, eol)
3210 long count;
3211 int bigword; /* "W", "E" or "B" */
3212 int eol;
3214 int sclass; /* starting class */
3215 int i;
3216 int last_line;
3218 #ifdef FEAT_VIRTUALEDIT
3219 curwin->w_cursor.coladd = 0;
3220 #endif
3221 cls_bigword = bigword;
3222 while (--count >= 0)
3224 #ifdef FEAT_FOLDING
3225 /* When inside a range of folded lines, move to the last char of the
3226 * last line. */
3227 if (hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum))
3228 coladvance((colnr_T)MAXCOL);
3229 #endif
3230 sclass = cls();
3233 * We always move at least one character, unless on the last
3234 * character in the buffer.
3236 last_line = (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count);
3237 i = inc_cursor();
3238 if (i == -1 || (i >= 1 && last_line)) /* started at last char in file */
3239 return FAIL;
3240 if (i >= 1 && eol && count == 0) /* started at last char in line */
3241 return OK;
3244 * Go one char past end of current word (if any)
3246 if (sclass != 0)
3247 while (cls() == sclass)
3249 i = inc_cursor();
3250 if (i == -1 || (i >= 1 && eol && count == 0))
3251 return OK;
3255 * go to next non-white
3257 while (cls() == 0)
3260 * We'll stop if we land on a blank line
3262 if (curwin->w_cursor.col == 0 && *ml_get_curline() == NUL)
3263 break;
3265 i = inc_cursor();
3266 if (i == -1 || (i >= 1 && eol && count == 0))
3267 return OK;
3270 return OK;
3274 * bck_word() - move backward 'count' words
3276 * If stop is TRUE and we are already on the start of a word, move one less.
3278 * Returns FAIL if top of the file was reached.
3281 bck_word(count, bigword, stop)
3282 long count;
3283 int bigword;
3284 int stop;
3286 int sclass; /* starting class */
3288 #ifdef FEAT_VIRTUALEDIT
3289 curwin->w_cursor.coladd = 0;
3290 #endif
3291 cls_bigword = bigword;
3292 while (--count >= 0)
3294 #ifdef FEAT_FOLDING
3295 /* When inside a range of folded lines, move to the first char of the
3296 * first line. */
3297 if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL))
3298 curwin->w_cursor.col = 0;
3299 #endif
3300 sclass = cls();
3301 if (dec_cursor() == -1) /* started at start of file */
3302 return FAIL;
3304 if (!stop || sclass == cls() || sclass == 0)
3307 * Skip white space before the word.
3308 * Stop on an empty line.
3310 while (cls() == 0)
3312 if (curwin->w_cursor.col == 0
3313 && lineempty(curwin->w_cursor.lnum))
3314 goto finished;
3315 if (dec_cursor() == -1) /* hit start of file, stop here */
3316 return OK;
3320 * Move backward to start of this word.
3322 if (skip_chars(cls(), BACKWARD))
3323 return OK;
3326 inc_cursor(); /* overshot - forward one */
3327 finished:
3328 stop = FALSE;
3330 return OK;
3334 * end_word() - move to the end of the word
3336 * There is an apparent bug in the 'e' motion of the real vi. At least on the
3337 * System V Release 3 version for the 80386. Unlike 'b' and 'w', the 'e'
3338 * motion crosses blank lines. When the real vi crosses a blank line in an
3339 * 'e' motion, the cursor is placed on the FIRST character of the next
3340 * non-blank line. The 'E' command, however, works correctly. Since this
3341 * appears to be a bug, I have not duplicated it here.
3343 * Returns FAIL if end of the file was reached.
3345 * If stop is TRUE and we are already on the end of a word, move one less.
3346 * If empty is TRUE stop on an empty line.
3349 end_word(count, bigword, stop, empty)
3350 long count;
3351 int bigword;
3352 int stop;
3353 int empty;
3355 int sclass; /* starting class */
3357 #ifdef FEAT_VIRTUALEDIT
3358 curwin->w_cursor.coladd = 0;
3359 #endif
3360 cls_bigword = bigword;
3361 while (--count >= 0)
3363 #ifdef FEAT_FOLDING
3364 /* When inside a range of folded lines, move to the last char of the
3365 * last line. */
3366 if (hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum))
3367 coladvance((colnr_T)MAXCOL);
3368 #endif
3369 sclass = cls();
3370 if (inc_cursor() == -1)
3371 return FAIL;
3374 * If we're in the middle of a word, we just have to move to the end
3375 * of it.
3377 if (cls() == sclass && sclass != 0)
3380 * Move forward to end of the current word
3382 if (skip_chars(sclass, FORWARD))
3383 return FAIL;
3385 else if (!stop || sclass == 0)
3388 * We were at the end of a word. Go to the end of the next word.
3389 * First skip white space, if 'empty' is TRUE, stop at empty line.
3391 while (cls() == 0)
3393 if (empty && curwin->w_cursor.col == 0
3394 && lineempty(curwin->w_cursor.lnum))
3395 goto finished;
3396 if (inc_cursor() == -1) /* hit end of file, stop here */
3397 return FAIL;
3401 * Move forward to the end of this word.
3403 if (skip_chars(cls(), FORWARD))
3404 return FAIL;
3406 dec_cursor(); /* overshot - one char backward */
3407 finished:
3408 stop = FALSE; /* we move only one word less */
3410 return OK;
3414 * Move back to the end of the word.
3416 * Returns FAIL if start of the file was reached.
3419 bckend_word(count, bigword, eol)
3420 long count;
3421 int bigword; /* TRUE for "B" */
3422 int eol; /* TRUE: stop at end of line. */
3424 int sclass; /* starting class */
3425 int i;
3427 #ifdef FEAT_VIRTUALEDIT
3428 curwin->w_cursor.coladd = 0;
3429 #endif
3430 cls_bigword = bigword;
3431 while (--count >= 0)
3433 sclass = cls();
3434 if ((i = dec_cursor()) == -1)
3435 return FAIL;
3436 if (eol && i == 1)
3437 return OK;
3440 * Move backward to before the start of this word.
3442 if (sclass != 0)
3444 while (cls() == sclass)
3445 if ((i = dec_cursor()) == -1 || (eol && i == 1))
3446 return OK;
3450 * Move backward to end of the previous word
3452 while (cls() == 0)
3454 if (curwin->w_cursor.col == 0 && lineempty(curwin->w_cursor.lnum))
3455 break;
3456 if ((i = dec_cursor()) == -1 || (eol && i == 1))
3457 return OK;
3460 return OK;
3464 * Skip a row of characters of the same class.
3465 * Return TRUE when end-of-file reached, FALSE otherwise.
3467 static int
3468 skip_chars(cclass, dir)
3469 int cclass;
3470 int dir;
3472 while (cls() == cclass)
3473 if ((dir == FORWARD ? inc_cursor() : dec_cursor()) == -1)
3474 return TRUE;
3475 return FALSE;
3478 #ifdef FEAT_TEXTOBJ
3480 * Go back to the start of the word or the start of white space
3482 static void
3483 back_in_line()
3485 int sclass; /* starting class */
3487 sclass = cls();
3488 for (;;)
3490 if (curwin->w_cursor.col == 0) /* stop at start of line */
3491 break;
3492 dec_cursor();
3493 if (cls() != sclass) /* stop at start of word */
3495 inc_cursor();
3496 break;
3501 static void
3502 find_first_blank(posp)
3503 pos_T *posp;
3505 int c;
3507 while (decl(posp) != -1)
3509 c = gchar_pos(posp);
3510 if (!vim_iswhite(c))
3512 incl(posp);
3513 break;
3519 * Skip count/2 sentences and count/2 separating white spaces.
3521 static void
3522 findsent_forward(count, at_start_sent)
3523 long count;
3524 int at_start_sent; /* cursor is at start of sentence */
3526 while (count--)
3528 findsent(FORWARD, 1L);
3529 if (at_start_sent)
3530 find_first_blank(&curwin->w_cursor);
3531 if (count == 0 || at_start_sent)
3532 decl(&curwin->w_cursor);
3533 at_start_sent = !at_start_sent;
3538 * Find word under cursor, cursor at end.
3539 * Used while an operator is pending, and in Visual mode.
3542 current_word(oap, count, include, bigword)
3543 oparg_T *oap;
3544 long count;
3545 int include; /* TRUE: include word and white space */
3546 int bigword; /* FALSE == word, TRUE == WORD */
3548 pos_T start_pos;
3549 pos_T pos;
3550 int inclusive = TRUE;
3551 int include_white = FALSE;
3553 cls_bigword = bigword;
3554 clearpos(&start_pos);
3556 #ifdef FEAT_VISUAL
3557 /* Correct cursor when 'selection' is exclusive */
3558 if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor))
3559 dec_cursor();
3562 * When Visual mode is not active, or when the VIsual area is only one
3563 * character, select the word and/or white space under the cursor.
3565 if (!VIsual_active || equalpos(curwin->w_cursor, VIsual))
3566 #endif
3569 * Go to start of current word or white space.
3571 back_in_line();
3572 start_pos = curwin->w_cursor;
3575 * If the start is on white space, and white space should be included
3576 * (" word"), or start is not on white space, and white space should
3577 * not be included ("word"), find end of word.
3579 if ((cls() == 0) == include)
3581 if (end_word(1L, bigword, TRUE, TRUE) == FAIL)
3582 return FAIL;
3584 else
3587 * If the start is not on white space, and white space should be
3588 * included ("word "), or start is on white space and white
3589 * space should not be included (" "), find start of word.
3590 * If we end up in the first column of the next line (single char
3591 * word) back up to end of the line.
3593 fwd_word(1L, bigword, TRUE);
3594 if (curwin->w_cursor.col == 0)
3595 decl(&curwin->w_cursor);
3596 else
3597 oneleft();
3599 if (include)
3600 include_white = TRUE;
3603 #ifdef FEAT_VISUAL
3604 if (VIsual_active)
3606 /* should do something when inclusive == FALSE ! */
3607 VIsual = start_pos;
3608 redraw_curbuf_later(INVERTED); /* update the inversion */
3610 else
3611 #endif
3613 oap->start = start_pos;
3614 oap->motion_type = MCHAR;
3616 --count;
3620 * When count is still > 0, extend with more objects.
3622 while (count > 0)
3624 inclusive = TRUE;
3625 #ifdef FEAT_VISUAL
3626 if (VIsual_active && lt(curwin->w_cursor, VIsual))
3629 * In Visual mode, with cursor at start: move cursor back.
3631 if (decl(&curwin->w_cursor) == -1)
3632 return FAIL;
3633 if (include != (cls() != 0))
3635 if (bck_word(1L, bigword, TRUE) == FAIL)
3636 return FAIL;
3638 else
3640 if (bckend_word(1L, bigword, TRUE) == FAIL)
3641 return FAIL;
3642 (void)incl(&curwin->w_cursor);
3645 else
3646 #endif
3649 * Move cursor forward one word and/or white area.
3651 if (incl(&curwin->w_cursor) == -1)
3652 return FAIL;
3653 if (include != (cls() == 0))
3655 if (fwd_word(1L, bigword, TRUE) == FAIL && count > 1)
3656 return FAIL;
3658 * If end is just past a new-line, we don't want to include
3659 * the first character on the line.
3660 * Put cursor on last char of white.
3662 if (oneleft() == FAIL)
3663 inclusive = FALSE;
3665 else
3667 if (end_word(1L, bigword, TRUE, TRUE) == FAIL)
3668 return FAIL;
3671 --count;
3674 if (include_white && (cls() != 0
3675 || (curwin->w_cursor.col == 0 && !inclusive)))
3678 * If we don't include white space at the end, move the start
3679 * to include some white space there. This makes "daw" work
3680 * better on the last word in a sentence (and "2daw" on last-but-one
3681 * word). Also when "2daw" deletes "word." at the end of the line
3682 * (cursor is at start of next line).
3683 * But don't delete white space at start of line (indent).
3685 pos = curwin->w_cursor; /* save cursor position */
3686 curwin->w_cursor = start_pos;
3687 if (oneleft() == OK)
3689 back_in_line();
3690 if (cls() == 0 && curwin->w_cursor.col > 0)
3692 #ifdef FEAT_VISUAL
3693 if (VIsual_active)
3694 VIsual = curwin->w_cursor;
3695 else
3696 #endif
3697 oap->start = curwin->w_cursor;
3700 curwin->w_cursor = pos; /* put cursor back at end */
3703 #ifdef FEAT_VISUAL
3704 if (VIsual_active)
3706 if (*p_sel == 'e' && inclusive && ltoreq(VIsual, curwin->w_cursor))
3707 inc_cursor();
3708 if (VIsual_mode == 'V')
3710 VIsual_mode = 'v';
3711 redraw_cmdline = TRUE; /* show mode later */
3714 else
3715 #endif
3716 oap->inclusive = inclusive;
3718 return OK;
3722 * Find sentence(s) under the cursor, cursor at end.
3723 * When Visual active, extend it by one or more sentences.
3726 current_sent(oap, count, include)
3727 oparg_T *oap;
3728 long count;
3729 int include;
3731 pos_T start_pos;
3732 pos_T pos;
3733 int start_blank;
3734 int c;
3735 int at_start_sent;
3736 long ncount;
3738 start_pos = curwin->w_cursor;
3739 pos = start_pos;
3740 findsent(FORWARD, 1L); /* Find start of next sentence. */
3742 #ifdef FEAT_VISUAL
3744 * When visual area is bigger than one character: Extend it.
3746 if (VIsual_active && !equalpos(start_pos, VIsual))
3748 extend:
3749 if (lt(start_pos, VIsual))
3752 * Cursor at start of Visual area.
3753 * Find out where we are:
3754 * - in the white space before a sentence
3755 * - in a sentence or just after it
3756 * - at the start of a sentence
3758 at_start_sent = TRUE;
3759 decl(&pos);
3760 while (lt(pos, curwin->w_cursor))
3762 c = gchar_pos(&pos);
3763 if (!vim_iswhite(c))
3765 at_start_sent = FALSE;
3766 break;
3768 incl(&pos);
3770 if (!at_start_sent)
3772 findsent(BACKWARD, 1L);
3773 if (equalpos(curwin->w_cursor, start_pos))
3774 at_start_sent = TRUE; /* exactly at start of sentence */
3775 else
3776 /* inside a sentence, go to its end (start of next) */
3777 findsent(FORWARD, 1L);
3779 if (include) /* "as" gets twice as much as "is" */
3780 count *= 2;
3781 while (count--)
3783 if (at_start_sent)
3784 find_first_blank(&curwin->w_cursor);
3785 c = gchar_cursor();
3786 if (!at_start_sent || (!include && !vim_iswhite(c)))
3787 findsent(BACKWARD, 1L);
3788 at_start_sent = !at_start_sent;
3791 else
3794 * Cursor at end of Visual area.
3795 * Find out where we are:
3796 * - just before a sentence
3797 * - just before or in the white space before a sentence
3798 * - in a sentence
3800 incl(&pos);
3801 at_start_sent = TRUE;
3802 if (!equalpos(pos, curwin->w_cursor)) /* not just before a sentence */
3804 at_start_sent = FALSE;
3805 while (lt(pos, curwin->w_cursor))
3807 c = gchar_pos(&pos);
3808 if (!vim_iswhite(c))
3810 at_start_sent = TRUE;
3811 break;
3813 incl(&pos);
3815 if (at_start_sent) /* in the sentence */
3816 findsent(BACKWARD, 1L);
3817 else /* in/before white before a sentence */
3818 curwin->w_cursor = start_pos;
3821 if (include) /* "as" gets twice as much as "is" */
3822 count *= 2;
3823 findsent_forward(count, at_start_sent);
3824 if (*p_sel == 'e')
3825 ++curwin->w_cursor.col;
3827 return OK;
3829 #endif
3832 * If cursor started on blank, check if it is just before the start of the
3833 * next sentence.
3835 while (c = gchar_pos(&pos), vim_iswhite(c)) /* vim_iswhite() is a macro */
3836 incl(&pos);
3837 if (equalpos(pos, curwin->w_cursor))
3839 start_blank = TRUE;
3840 find_first_blank(&start_pos); /* go back to first blank */
3842 else
3844 start_blank = FALSE;
3845 findsent(BACKWARD, 1L);
3846 start_pos = curwin->w_cursor;
3848 if (include)
3849 ncount = count * 2;
3850 else
3852 ncount = count;
3853 if (start_blank)
3854 --ncount;
3856 if (ncount > 0)
3857 findsent_forward(ncount, TRUE);
3858 else
3859 decl(&curwin->w_cursor);
3861 if (include)
3864 * If the blank in front of the sentence is included, exclude the
3865 * blanks at the end of the sentence, go back to the first blank.
3866 * If there are no trailing blanks, try to include leading blanks.
3868 if (start_blank)
3870 find_first_blank(&curwin->w_cursor);
3871 c = gchar_pos(&curwin->w_cursor); /* vim_iswhite() is a macro */
3872 if (vim_iswhite(c))
3873 decl(&curwin->w_cursor);
3875 else if (c = gchar_cursor(), !vim_iswhite(c))
3876 find_first_blank(&start_pos);
3879 #ifdef FEAT_VISUAL
3880 if (VIsual_active)
3882 /* avoid getting stuck with "is" on a single space before a sent. */
3883 if (equalpos(start_pos, curwin->w_cursor))
3884 goto extend;
3885 if (*p_sel == 'e')
3886 ++curwin->w_cursor.col;
3887 VIsual = start_pos;
3888 VIsual_mode = 'v';
3889 redraw_curbuf_later(INVERTED); /* update the inversion */
3891 else
3892 #endif
3894 /* include a newline after the sentence, if there is one */
3895 if (incl(&curwin->w_cursor) == -1)
3896 oap->inclusive = TRUE;
3897 else
3898 oap->inclusive = FALSE;
3899 oap->start = start_pos;
3900 oap->motion_type = MCHAR;
3902 return OK;
3906 * Find block under the cursor, cursor at end.
3907 * "what" and "other" are two matching parenthesis/paren/etc.
3910 current_block(oap, count, include, what, other)
3911 oparg_T *oap;
3912 long count;
3913 int include; /* TRUE == include white space */
3914 int what; /* '(', '{', etc. */
3915 int other; /* ')', '}', etc. */
3917 pos_T old_pos;
3918 pos_T *pos = NULL;
3919 pos_T start_pos;
3920 pos_T *end_pos;
3921 pos_T old_start, old_end;
3922 char_u *save_cpo;
3923 int sol = FALSE; /* '{' at start of line */
3925 old_pos = curwin->w_cursor;
3926 old_end = curwin->w_cursor; /* remember where we started */
3927 old_start = old_end;
3930 * If we start on '(', '{', ')', '}', etc., use the whole block inclusive.
3932 #ifdef FEAT_VISUAL
3933 if (!VIsual_active || equalpos(VIsual, curwin->w_cursor))
3934 #endif
3936 setpcmark();
3937 if (what == '{') /* ignore indent */
3938 while (inindent(1))
3939 if (inc_cursor() != 0)
3940 break;
3941 if (gchar_cursor() == what)
3942 /* cursor on '(' or '{', move cursor just after it */
3943 ++curwin->w_cursor.col;
3945 #ifdef FEAT_VISUAL
3946 else if (lt(VIsual, curwin->w_cursor))
3948 old_start = VIsual;
3949 curwin->w_cursor = VIsual; /* cursor at low end of Visual */
3951 else
3952 old_end = VIsual;
3953 #endif
3956 * Search backwards for unclosed '(', '{', etc..
3957 * Put this position in start_pos.
3958 * Ignore quotes here.
3960 save_cpo = p_cpo;
3961 p_cpo = (char_u *)"%";
3962 while (count-- > 0)
3964 if ((pos = findmatch(NULL, what)) == NULL)
3965 break;
3966 curwin->w_cursor = *pos;
3967 start_pos = *pos; /* the findmatch for end_pos will overwrite *pos */
3969 p_cpo = save_cpo;
3972 * Search for matching ')', '}', etc.
3973 * Put this position in curwin->w_cursor.
3975 if (pos == NULL || (end_pos = findmatch(NULL, other)) == NULL)
3977 curwin->w_cursor = old_pos;
3978 return FAIL;
3980 curwin->w_cursor = *end_pos;
3983 * Try to exclude the '(', '{', ')', '}', etc. when "include" is FALSE.
3984 * If the ending '}' is only preceded by indent, skip that indent.
3985 * But only if the resulting area is not smaller than what we started with.
3987 while (!include)
3989 incl(&start_pos);
3990 sol = (curwin->w_cursor.col == 0);
3991 decl(&curwin->w_cursor);
3992 if (what == '{')
3993 while (inindent(1))
3995 sol = TRUE;
3996 if (decl(&curwin->w_cursor) != 0)
3997 break;
3999 #ifdef FEAT_VISUAL
4001 * In Visual mode, when the resulting area is not bigger than what we
4002 * started with, extend it to the next block, and then exclude again.
4004 if (!lt(start_pos, old_start) && !lt(old_end, curwin->w_cursor)
4005 && VIsual_active)
4007 curwin->w_cursor = old_start;
4008 decl(&curwin->w_cursor);
4009 if ((pos = findmatch(NULL, what)) == NULL)
4011 curwin->w_cursor = old_pos;
4012 return FAIL;
4014 start_pos = *pos;
4015 curwin->w_cursor = *pos;
4016 if ((end_pos = findmatch(NULL, other)) == NULL)
4018 curwin->w_cursor = old_pos;
4019 return FAIL;
4021 curwin->w_cursor = *end_pos;
4023 else
4024 #endif
4025 break;
4028 #ifdef FEAT_VISUAL
4029 if (VIsual_active)
4031 if (*p_sel == 'e')
4032 ++curwin->w_cursor.col;
4033 if (sol && gchar_cursor() != NUL)
4034 inc(&curwin->w_cursor); /* include the line break */
4035 VIsual = start_pos;
4036 VIsual_mode = 'v';
4037 redraw_curbuf_later(INVERTED); /* update the inversion */
4038 showmode();
4040 else
4041 #endif
4043 oap->start = start_pos;
4044 oap->motion_type = MCHAR;
4045 oap->inclusive = FALSE;
4046 if (sol)
4047 incl(&curwin->w_cursor);
4048 else if (ltoreq(start_pos, curwin->w_cursor))
4049 /* Include the character under the cursor. */
4050 oap->inclusive = TRUE;
4051 else
4052 /* End is before the start (no text in between <>, [], etc.): don't
4053 * operate on any text. */
4054 curwin->w_cursor = start_pos;
4057 return OK;
4060 static int in_html_tag __ARGS((int));
4063 * Return TRUE if the cursor is on a "<aaa>" tag. Ignore "<aaa/>".
4064 * When "end_tag" is TRUE return TRUE if the cursor is on "</aaa>".
4066 static int
4067 in_html_tag(end_tag)
4068 int end_tag;
4070 char_u *line = ml_get_curline();
4071 char_u *p;
4072 int c;
4073 int lc = NUL;
4074 pos_T pos;
4076 #ifdef FEAT_MBYTE
4077 if (enc_dbcs)
4079 char_u *lp = NULL;
4081 /* We search forward until the cursor, because searching backwards is
4082 * very slow for DBCS encodings. */
4083 for (p = line; p < line + curwin->w_cursor.col; mb_ptr_adv(p))
4084 if (*p == '>' || *p == '<')
4086 lc = *p;
4087 lp = p;
4089 if (*p != '<') /* check for '<' under cursor */
4091 if (lc != '<')
4092 return FALSE;
4093 p = lp;
4096 else
4097 #endif
4099 for (p = line + curwin->w_cursor.col; p > line; )
4101 if (*p == '<') /* find '<' under/before cursor */
4102 break;
4103 mb_ptr_back(line, p);
4104 if (*p == '>') /* find '>' before cursor */
4105 break;
4107 if (*p != '<')
4108 return FALSE;
4111 pos.lnum = curwin->w_cursor.lnum;
4112 pos.col = (colnr_T)(p - line);
4114 mb_ptr_adv(p);
4115 if (end_tag)
4116 /* check that there is a '/' after the '<' */
4117 return *p == '/';
4119 /* check that there is no '/' after the '<' */
4120 if (*p == '/')
4121 return FALSE;
4123 /* check that the matching '>' is not preceded by '/' */
4124 for (;;)
4126 if (inc(&pos) < 0)
4127 return FALSE;
4128 c = *ml_get_pos(&pos);
4129 if (c == '>')
4130 break;
4131 lc = c;
4133 return lc != '/';
4137 * Find tag block under the cursor, cursor at end.
4140 current_tagblock(oap, count_arg, include)
4141 oparg_T *oap;
4142 long count_arg;
4143 int include; /* TRUE == include white space */
4145 long count = count_arg;
4146 long n;
4147 pos_T old_pos;
4148 pos_T start_pos;
4149 pos_T end_pos;
4150 pos_T old_start, old_end;
4151 char_u *spat, *epat;
4152 char_u *p;
4153 char_u *cp;
4154 int len;
4155 int r;
4156 int do_include = include;
4157 int save_p_ws = p_ws;
4158 int retval = FAIL;
4160 p_ws = FALSE;
4162 old_pos = curwin->w_cursor;
4163 old_end = curwin->w_cursor; /* remember where we started */
4164 old_start = old_end;
4165 #ifdef FEAT_VISUAL
4166 if (!VIsual_active || *p_sel == 'e')
4167 #endif
4168 decl(&old_end); /* old_end is inclusive */
4171 * If we start on "<aaa>" select that block.
4173 #ifdef FEAT_VISUAL
4174 if (!VIsual_active || equalpos(VIsual, curwin->w_cursor))
4175 #endif
4177 setpcmark();
4179 /* ignore indent */
4180 while (inindent(1))
4181 if (inc_cursor() != 0)
4182 break;
4184 if (in_html_tag(FALSE))
4186 /* cursor on start tag, move to its '>' */
4187 while (*ml_get_cursor() != '>')
4188 if (inc_cursor() < 0)
4189 break;
4191 else if (in_html_tag(TRUE))
4193 /* cursor on end tag, move to just before it */
4194 while (*ml_get_cursor() != '<')
4195 if (dec_cursor() < 0)
4196 break;
4197 dec_cursor();
4198 old_end = curwin->w_cursor;
4201 #ifdef FEAT_VISUAL
4202 else if (lt(VIsual, curwin->w_cursor))
4204 old_start = VIsual;
4205 curwin->w_cursor = VIsual; /* cursor at low end of Visual */
4207 else
4208 old_end = VIsual;
4209 #endif
4211 again:
4213 * Search backwards for unclosed "<aaa>".
4214 * Put this position in start_pos.
4216 for (n = 0; n < count; ++n)
4218 if (do_searchpair((char_u *)"<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)",
4219 (char_u *)"",
4220 (char_u *)"</[^>]*>", BACKWARD, (char_u *)"", 0,
4221 NULL, (linenr_T)0, 0L) <= 0)
4223 curwin->w_cursor = old_pos;
4224 goto theend;
4227 start_pos = curwin->w_cursor;
4230 * Search for matching "</aaa>". First isolate the "aaa".
4232 inc_cursor();
4233 p = ml_get_cursor();
4234 for (cp = p; *cp != NUL && *cp != '>' && !vim_iswhite(*cp); mb_ptr_adv(cp))
4236 len = (int)(cp - p);
4237 if (len == 0)
4239 curwin->w_cursor = old_pos;
4240 goto theend;
4242 spat = alloc(len + 29);
4243 epat = alloc(len + 9);
4244 if (spat == NULL || epat == NULL)
4246 vim_free(spat);
4247 vim_free(epat);
4248 curwin->w_cursor = old_pos;
4249 goto theend;
4251 sprintf((char *)spat, "<%.*s\\%%(\\_[^>]\\{-}[^/]>\\|>\\)\\c", len, p);
4252 sprintf((char *)epat, "</%.*s>\\c", len, p);
4254 r = do_searchpair(spat, (char_u *)"", epat, FORWARD, (char_u *)"",
4255 0, NULL, (linenr_T)0, 0L);
4257 vim_free(spat);
4258 vim_free(epat);
4260 if (r < 1 || lt(curwin->w_cursor, old_end))
4262 /* Can't find other end or it's before the previous end. Could be a
4263 * HTML tag that doesn't have a matching end. Search backwards for
4264 * another starting tag. */
4265 count = 1;
4266 curwin->w_cursor = start_pos;
4267 goto again;
4270 if (do_include || r < 1)
4272 /* Include up to the '>'. */
4273 while (*ml_get_cursor() != '>')
4274 if (inc_cursor() < 0)
4275 break;
4277 else
4279 /* Exclude the '<' of the end tag. */
4280 if (*ml_get_cursor() == '<')
4281 dec_cursor();
4283 end_pos = curwin->w_cursor;
4285 if (!do_include)
4287 /* Exclude the start tag. */
4288 curwin->w_cursor = start_pos;
4289 while (inc_cursor() >= 0)
4290 if (*ml_get_cursor() == '>')
4292 inc_cursor();
4293 start_pos = curwin->w_cursor;
4294 break;
4296 curwin->w_cursor = end_pos;
4298 /* If we now have the same text as before reset "do_include" and try
4299 * again. */
4300 if (equalpos(start_pos, old_start) && equalpos(end_pos, old_end))
4302 do_include = TRUE;
4303 curwin->w_cursor = old_start;
4304 count = count_arg;
4305 goto again;
4309 #ifdef FEAT_VISUAL
4310 if (VIsual_active)
4312 /* If the end is before the start there is no text between tags, select
4313 * the char under the cursor. */
4314 if (lt(end_pos, start_pos))
4315 curwin->w_cursor = start_pos;
4316 else if (*p_sel == 'e')
4317 ++curwin->w_cursor.col;
4318 VIsual = start_pos;
4319 VIsual_mode = 'v';
4320 redraw_curbuf_later(INVERTED); /* update the inversion */
4321 showmode();
4323 else
4324 #endif
4326 oap->start = start_pos;
4327 oap->motion_type = MCHAR;
4328 if (lt(end_pos, start_pos))
4330 /* End is before the start: there is no text between tags; operate
4331 * on an empty area. */
4332 curwin->w_cursor = start_pos;
4333 oap->inclusive = FALSE;
4335 else
4336 oap->inclusive = TRUE;
4338 retval = OK;
4340 theend:
4341 p_ws = save_p_ws;
4342 return retval;
4346 current_par(oap, count, include, type)
4347 oparg_T *oap;
4348 long count;
4349 int include; /* TRUE == include white space */
4350 int type; /* 'p' for paragraph, 'S' for section */
4352 linenr_T start_lnum;
4353 linenr_T end_lnum;
4354 int white_in_front;
4355 int dir;
4356 int start_is_white;
4357 int prev_start_is_white;
4358 int retval = OK;
4359 int do_white = FALSE;
4360 int t;
4361 int i;
4363 if (type == 'S') /* not implemented yet */
4364 return FAIL;
4366 start_lnum = curwin->w_cursor.lnum;
4368 #ifdef FEAT_VISUAL
4370 * When visual area is more than one line: extend it.
4372 if (VIsual_active && start_lnum != VIsual.lnum)
4374 extend:
4375 if (start_lnum < VIsual.lnum)
4376 dir = BACKWARD;
4377 else
4378 dir = FORWARD;
4379 for (i = count; --i >= 0; )
4381 if (start_lnum ==
4382 (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count))
4384 retval = FAIL;
4385 break;
4388 prev_start_is_white = -1;
4389 for (t = 0; t < 2; ++t)
4391 start_lnum += dir;
4392 start_is_white = linewhite(start_lnum);
4393 if (prev_start_is_white == start_is_white)
4395 start_lnum -= dir;
4396 break;
4398 for (;;)
4400 if (start_lnum == (dir == BACKWARD
4401 ? 1 : curbuf->b_ml.ml_line_count))
4402 break;
4403 if (start_is_white != linewhite(start_lnum + dir)
4404 || (!start_is_white
4405 && startPS(start_lnum + (dir > 0
4406 ? 1 : 0), 0, 0)))
4407 break;
4408 start_lnum += dir;
4410 if (!include)
4411 break;
4412 if (start_lnum == (dir == BACKWARD
4413 ? 1 : curbuf->b_ml.ml_line_count))
4414 break;
4415 prev_start_is_white = start_is_white;
4418 curwin->w_cursor.lnum = start_lnum;
4419 curwin->w_cursor.col = 0;
4420 return retval;
4422 #endif
4425 * First move back to the start_lnum of the paragraph or white lines
4427 white_in_front = linewhite(start_lnum);
4428 while (start_lnum > 1)
4430 if (white_in_front) /* stop at first white line */
4432 if (!linewhite(start_lnum - 1))
4433 break;
4435 else /* stop at first non-white line of start of paragraph */
4437 if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0))
4438 break;
4440 --start_lnum;
4444 * Move past the end of any white lines.
4446 end_lnum = start_lnum;
4447 while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum))
4448 ++end_lnum;
4450 --end_lnum;
4451 i = count;
4452 if (!include && white_in_front)
4453 --i;
4454 while (i--)
4456 if (end_lnum == curbuf->b_ml.ml_line_count)
4457 return FAIL;
4459 if (!include)
4460 do_white = linewhite(end_lnum + 1);
4462 if (include || !do_white)
4464 ++end_lnum;
4466 * skip to end of paragraph
4468 while (end_lnum < curbuf->b_ml.ml_line_count
4469 && !linewhite(end_lnum + 1)
4470 && !startPS(end_lnum + 1, 0, 0))
4471 ++end_lnum;
4474 if (i == 0 && white_in_front && include)
4475 break;
4478 * skip to end of white lines after paragraph
4480 if (include || do_white)
4481 while (end_lnum < curbuf->b_ml.ml_line_count
4482 && linewhite(end_lnum + 1))
4483 ++end_lnum;
4487 * If there are no empty lines at the end, try to find some empty lines at
4488 * the start (unless that has been done already).
4490 if (!white_in_front && !linewhite(end_lnum) && include)
4491 while (start_lnum > 1 && linewhite(start_lnum - 1))
4492 --start_lnum;
4494 #ifdef FEAT_VISUAL
4495 if (VIsual_active)
4497 /* Problem: when doing "Vipipip" nothing happens in a single white
4498 * line, we get stuck there. Trap this here. */
4499 if (VIsual_mode == 'V' && start_lnum == curwin->w_cursor.lnum)
4500 goto extend;
4501 VIsual.lnum = start_lnum;
4502 VIsual_mode = 'V';
4503 redraw_curbuf_later(INVERTED); /* update the inversion */
4504 showmode();
4506 else
4507 #endif
4509 oap->start.lnum = start_lnum;
4510 oap->start.col = 0;
4511 oap->motion_type = MLINE;
4513 curwin->w_cursor.lnum = end_lnum;
4514 curwin->w_cursor.col = 0;
4516 return OK;
4519 static int find_next_quote __ARGS((char_u *top_ptr, int col, int quotechar, char_u *escape));
4520 static int find_prev_quote __ARGS((char_u *line, int col_start, int quotechar, char_u *escape));
4523 * Search quote char from string line[col].
4524 * Quote character escaped by one of the characters in "escape" is not counted
4525 * as a quote.
4526 * Returns column number of "quotechar" or -1 when not found.
4528 static int
4529 find_next_quote(line, col, quotechar, escape)
4530 char_u *line;
4531 int col;
4532 int quotechar;
4533 char_u *escape; /* escape characters, can be NULL */
4535 int c;
4537 for (;;)
4539 c = line[col];
4540 if (c == NUL)
4541 return -1;
4542 else if (escape != NULL && vim_strchr(escape, c))
4543 ++col;
4544 else if (c == quotechar)
4545 break;
4546 #ifdef FEAT_MBYTE
4547 if (has_mbyte)
4548 col += (*mb_ptr2len)(line + col);
4549 else
4550 #endif
4551 ++col;
4553 return col;
4557 * Search backwards in "line" from column "col_start" to find "quotechar".
4558 * Quote character escaped by one of the characters in "escape" is not counted
4559 * as a quote.
4560 * Return the found column or zero.
4562 static int
4563 find_prev_quote(line, col_start, quotechar, escape)
4564 char_u *line;
4565 int col_start;
4566 int quotechar;
4567 char_u *escape; /* escape characters, can be NULL */
4569 int n;
4571 while (col_start > 0)
4573 --col_start;
4574 #ifdef FEAT_MBYTE
4575 col_start -= (*mb_head_off)(line, line + col_start);
4576 #endif
4577 n = 0;
4578 if (escape != NULL)
4579 while (col_start - n > 0 && vim_strchr(escape,
4580 line[col_start - n - 1]) != NULL)
4581 ++n;
4582 if (n & 1)
4583 col_start -= n; /* uneven number of escape chars, skip it */
4584 else if (line[col_start] == quotechar)
4585 break;
4587 return col_start;
4591 * Find quote under the cursor, cursor at end.
4592 * Returns TRUE if found, else FALSE.
4595 current_quote(oap, count, include, quotechar)
4596 oparg_T *oap;
4597 long count;
4598 int include; /* TRUE == include quote char */
4599 int quotechar; /* Quote character */
4601 char_u *line = ml_get_curline();
4602 int col_end;
4603 int col_start = curwin->w_cursor.col;
4604 int inclusive = FALSE;
4605 #ifdef FEAT_VISUAL
4606 int vis_empty = TRUE; /* Visual selection <= 1 char */
4607 int vis_bef_curs = FALSE; /* Visual starts before cursor */
4608 int inside_quotes = FALSE; /* Looks like "i'" done before */
4609 int selected_quote = FALSE; /* Has quote inside selection */
4610 int i;
4612 /* Correct cursor when 'selection' is exclusive */
4613 if (VIsual_active)
4615 vis_bef_curs = lt(VIsual, curwin->w_cursor);
4616 if (*p_sel == 'e' && vis_bef_curs)
4617 dec_cursor();
4618 vis_empty = equalpos(VIsual, curwin->w_cursor);
4621 if (!vis_empty)
4623 /* Check if the existing selection exactly spans the text inside
4624 * quotes. */
4625 if (vis_bef_curs)
4627 inside_quotes = VIsual.col > 0
4628 && line[VIsual.col - 1] == quotechar
4629 && line[curwin->w_cursor.col] != NUL
4630 && line[curwin->w_cursor.col + 1] == quotechar;
4631 i = VIsual.col;
4632 col_end = curwin->w_cursor.col;
4634 else
4636 inside_quotes = curwin->w_cursor.col > 0
4637 && line[curwin->w_cursor.col - 1] == quotechar
4638 && line[VIsual.col] != NUL
4639 && line[VIsual.col + 1] == quotechar;
4640 i = curwin->w_cursor.col;
4641 col_end = VIsual.col;
4644 /* Find out if we have a quote in the selection. */
4645 while (i <= col_end)
4646 if (line[i++] == quotechar)
4648 selected_quote = TRUE;
4649 break;
4653 if (!vis_empty && line[col_start] == quotechar)
4655 /* Already selecting something and on a quote character. Find the
4656 * next quoted string. */
4657 if (vis_bef_curs)
4659 /* Assume we are on a closing quote: move to after the next
4660 * opening quote. */
4661 col_start = find_next_quote(line, col_start + 1, quotechar, NULL);
4662 if (col_start < 0)
4663 return FALSE;
4664 col_end = find_next_quote(line, col_start + 1, quotechar,
4665 curbuf->b_p_qe);
4666 if (col_end < 0)
4668 /* We were on a starting quote perhaps? */
4669 col_end = col_start;
4670 col_start = curwin->w_cursor.col;
4673 else
4675 col_end = find_prev_quote(line, col_start, quotechar, NULL);
4676 if (line[col_end] != quotechar)
4677 return FALSE;
4678 col_start = find_prev_quote(line, col_end, quotechar,
4679 curbuf->b_p_qe);
4680 if (line[col_start] != quotechar)
4682 /* We were on an ending quote perhaps? */
4683 col_start = col_end;
4684 col_end = curwin->w_cursor.col;
4688 else
4689 #endif
4691 if (line[col_start] == quotechar
4692 #ifdef FEAT_VISUAL
4693 || !vis_empty
4694 #endif
4697 int first_col = col_start;
4699 #ifdef FEAT_VISUAL
4700 if (!vis_empty)
4702 if (vis_bef_curs)
4703 first_col = find_next_quote(line, col_start, quotechar, NULL);
4704 else
4705 first_col = find_prev_quote(line, col_start, quotechar, NULL);
4707 #endif
4708 /* The cursor is on a quote, we don't know if it's the opening or
4709 * closing quote. Search from the start of the line to find out.
4710 * Also do this when there is a Visual area, a' may leave the cursor
4711 * in between two strings. */
4712 col_start = 0;
4713 for (;;)
4715 /* Find open quote character. */
4716 col_start = find_next_quote(line, col_start, quotechar, NULL);
4717 if (col_start < 0 || col_start > first_col)
4718 return FALSE;
4719 /* Find close quote character. */
4720 col_end = find_next_quote(line, col_start + 1, quotechar,
4721 curbuf->b_p_qe);
4722 if (col_end < 0)
4723 return FALSE;
4724 /* If is cursor between start and end quote character, it is
4725 * target text object. */
4726 if (col_start <= first_col && first_col <= col_end)
4727 break;
4728 col_start = col_end + 1;
4731 else
4733 /* Search backward for a starting quote. */
4734 col_start = find_prev_quote(line, col_start, quotechar, curbuf->b_p_qe);
4735 if (line[col_start] != quotechar)
4737 /* No quote before the cursor, look after the cursor. */
4738 col_start = find_next_quote(line, col_start, quotechar, NULL);
4739 if (col_start < 0)
4740 return FALSE;
4743 /* Find close quote character. */
4744 col_end = find_next_quote(line, col_start + 1, quotechar,
4745 curbuf->b_p_qe);
4746 if (col_end < 0)
4747 return FALSE;
4750 /* When "include" is TRUE, include spaces after closing quote or before
4751 * the starting quote. */
4752 if (include)
4754 if (vim_iswhite(line[col_end + 1]))
4755 while (vim_iswhite(line[col_end + 1]))
4756 ++col_end;
4757 else
4758 while (col_start > 0 && vim_iswhite(line[col_start - 1]))
4759 --col_start;
4762 /* Set start position. After vi" another i" must include the ".
4763 * For v2i" include the quotes. */
4764 if (!include && count < 2
4765 #ifdef FEAT_VISUAL
4766 && (vis_empty || !inside_quotes)
4767 #endif
4769 ++col_start;
4770 curwin->w_cursor.col = col_start;
4771 #ifdef FEAT_VISUAL
4772 if (VIsual_active)
4774 /* Set the start of the Visual area when the Visual area was empty, we
4775 * were just inside quotes or the Visual area didn't start at a quote
4776 * and didn't include a quote.
4778 if (vis_empty
4779 || (vis_bef_curs
4780 && !selected_quote
4781 && (inside_quotes
4782 || (line[VIsual.col] != quotechar
4783 && (VIsual.col == 0
4784 || line[VIsual.col - 1] != quotechar)))))
4786 VIsual = curwin->w_cursor;
4787 redraw_curbuf_later(INVERTED);
4790 else
4791 #endif
4793 oap->start = curwin->w_cursor;
4794 oap->motion_type = MCHAR;
4797 /* Set end position. */
4798 curwin->w_cursor.col = col_end;
4799 if ((include || count > 1
4800 #ifdef FEAT_VISUAL
4801 /* After vi" another i" must include the ". */
4802 || (!vis_empty && inside_quotes)
4803 #endif
4804 ) && inc_cursor() == 2)
4805 inclusive = TRUE;
4806 #ifdef FEAT_VISUAL
4807 if (VIsual_active)
4809 if (vis_empty || vis_bef_curs)
4811 /* decrement cursor when 'selection' is not exclusive */
4812 if (*p_sel != 'e')
4813 dec_cursor();
4815 else
4817 /* Cursor is at start of Visual area. Set the end of the Visual
4818 * area when it was just inside quotes or it didn't end at a
4819 * quote. */
4820 if (inside_quotes
4821 || (!selected_quote
4822 && line[VIsual.col] != quotechar
4823 && (line[VIsual.col] == NUL
4824 || line[VIsual.col + 1] != quotechar)))
4826 dec_cursor();
4827 VIsual = curwin->w_cursor;
4829 curwin->w_cursor.col = col_start;
4831 if (VIsual_mode == 'V')
4833 VIsual_mode = 'v';
4834 redraw_cmdline = TRUE; /* show mode later */
4837 else
4838 #endif
4840 /* Set inclusive and other oap's flags. */
4841 oap->inclusive = inclusive;
4844 return OK;
4847 #endif /* FEAT_TEXTOBJ */
4849 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(FEAT_TEXTOBJ) \
4850 || defined(PROTO)
4852 * return TRUE if line 'lnum' is empty or has white chars only.
4855 linewhite(lnum)
4856 linenr_T lnum;
4858 char_u *p;
4860 p = skipwhite(ml_get(lnum));
4861 return (*p == NUL);
4863 #endif
4865 #if defined(FEAT_FIND_ID) || defined(PROTO)
4867 * Find identifiers or defines in included files.
4868 * if p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase.
4870 void
4871 find_pattern_in_path(ptr, dir, len, whole, skip_comments,
4872 type, count, action, start_lnum, end_lnum)
4873 char_u *ptr; /* pointer to search pattern */
4874 int dir UNUSED; /* direction of expansion */
4875 int len; /* length of search pattern */
4876 int whole; /* match whole words only */
4877 int skip_comments; /* don't match inside comments */
4878 int type; /* Type of search; are we looking for a type?
4879 a macro? */
4880 long count;
4881 int action; /* What to do when we find it */
4882 linenr_T start_lnum; /* first line to start searching */
4883 linenr_T end_lnum; /* last line for searching */
4885 SearchedFile *files; /* Stack of included files */
4886 SearchedFile *bigger; /* When we need more space */
4887 int max_path_depth = 50;
4888 long match_count = 1;
4890 char_u *pat;
4891 char_u *new_fname;
4892 char_u *curr_fname = curbuf->b_fname;
4893 char_u *prev_fname = NULL;
4894 linenr_T lnum;
4895 int depth;
4896 int depth_displayed; /* For type==CHECK_PATH */
4897 int old_files;
4898 int already_searched;
4899 char_u *file_line;
4900 char_u *line;
4901 char_u *p;
4902 char_u save_char;
4903 int define_matched;
4904 regmatch_T regmatch;
4905 regmatch_T incl_regmatch;
4906 regmatch_T def_regmatch;
4907 int matched = FALSE;
4908 int did_show = FALSE;
4909 int found = FALSE;
4910 int i;
4911 char_u *already = NULL;
4912 char_u *startp = NULL;
4913 char_u *inc_opt = NULL;
4914 #ifdef RISCOS
4915 int previous_munging = __riscosify_control;
4916 #endif
4917 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
4918 win_T *curwin_save = NULL;
4919 #endif
4921 regmatch.regprog = NULL;
4922 incl_regmatch.regprog = NULL;
4923 def_regmatch.regprog = NULL;
4925 file_line = alloc(LSIZE);
4926 if (file_line == NULL)
4927 return;
4929 #ifdef RISCOS
4930 /* UnixLib knows best how to munge c file names - turn munging back on. */
4931 int __riscosify_control = 0;
4932 #endif
4934 if (type != CHECK_PATH && type != FIND_DEFINE
4935 #ifdef FEAT_INS_EXPAND
4936 /* when CONT_SOL is set compare "ptr" with the beginning of the line
4937 * is faster than quote_meta/regcomp/regexec "ptr" -- Acevedo */
4938 && !(compl_cont_status & CONT_SOL)
4939 #endif
4942 pat = alloc(len + 5);
4943 if (pat == NULL)
4944 goto fpip_end;
4945 sprintf((char *)pat, whole ? "\\<%.*s\\>" : "%.*s", len, ptr);
4946 /* ignore case according to p_ic, p_scs and pat */
4947 regmatch.rm_ic = ignorecase(pat);
4948 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
4949 vim_free(pat);
4950 if (regmatch.regprog == NULL)
4951 goto fpip_end;
4953 inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc;
4954 if (*inc_opt != NUL)
4956 incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0);
4957 if (incl_regmatch.regprog == NULL)
4958 goto fpip_end;
4959 incl_regmatch.rm_ic = FALSE; /* don't ignore case in incl. pat. */
4961 if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL))
4963 def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL
4964 ? p_def : curbuf->b_p_def, p_magic ? RE_MAGIC : 0);
4965 if (def_regmatch.regprog == NULL)
4966 goto fpip_end;
4967 def_regmatch.rm_ic = FALSE; /* don't ignore case in define pat. */
4969 files = (SearchedFile *)lalloc_clear((long_u)
4970 (max_path_depth * sizeof(SearchedFile)), TRUE);
4971 if (files == NULL)
4972 goto fpip_end;
4973 old_files = max_path_depth;
4974 depth = depth_displayed = -1;
4976 lnum = start_lnum;
4977 if (end_lnum > curbuf->b_ml.ml_line_count)
4978 end_lnum = curbuf->b_ml.ml_line_count;
4979 if (lnum > end_lnum) /* do at least one line */
4980 lnum = end_lnum;
4981 line = ml_get(lnum);
4983 for (;;)
4985 if (incl_regmatch.regprog != NULL
4986 && vim_regexec(&incl_regmatch, line, (colnr_T)0))
4988 char_u *p_fname = (curr_fname == curbuf->b_fname)
4989 ? curbuf->b_ffname : curr_fname;
4991 if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL)
4992 /* Use text from '\zs' to '\ze' (or end) of 'include'. */
4993 new_fname = find_file_name_in_path(incl_regmatch.startp[0],
4994 (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]),
4995 FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname);
4996 else
4997 /* Use text after match with 'include'. */
4998 new_fname = file_name_in_line(incl_regmatch.endp[0], 0,
4999 FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL);
5000 already_searched = FALSE;
5001 if (new_fname != NULL)
5003 /* Check whether we have already searched in this file */
5004 for (i = 0;; i++)
5006 if (i == depth + 1)
5007 i = old_files;
5008 if (i == max_path_depth)
5009 break;
5010 if (fullpathcmp(new_fname, files[i].name, TRUE) & FPC_SAME)
5012 if (type != CHECK_PATH &&
5013 action == ACTION_SHOW_ALL && files[i].matched)
5015 msg_putchar('\n'); /* cursor below last one */
5016 if (!got_int) /* don't display if 'q'
5017 typed at "--more--"
5018 message */
5020 msg_home_replace_hl(new_fname);
5021 MSG_PUTS(_(" (includes previously listed match)"));
5022 prev_fname = NULL;
5025 vim_free(new_fname);
5026 new_fname = NULL;
5027 already_searched = TRUE;
5028 break;
5033 if (type == CHECK_PATH && (action == ACTION_SHOW_ALL
5034 || (new_fname == NULL && !already_searched)))
5036 if (did_show)
5037 msg_putchar('\n'); /* cursor below last one */
5038 else
5040 gotocmdline(TRUE); /* cursor at status line */
5041 MSG_PUTS_TITLE(_("--- Included files "));
5042 if (action != ACTION_SHOW_ALL)
5043 MSG_PUTS_TITLE(_("not found "));
5044 MSG_PUTS_TITLE(_("in path ---\n"));
5046 did_show = TRUE;
5047 while (depth_displayed < depth && !got_int)
5049 ++depth_displayed;
5050 for (i = 0; i < depth_displayed; i++)
5051 MSG_PUTS(" ");
5052 msg_home_replace(files[depth_displayed].name);
5053 MSG_PUTS(" -->\n");
5055 if (!got_int) /* don't display if 'q' typed
5056 for "--more--" message */
5058 for (i = 0; i <= depth_displayed; i++)
5059 MSG_PUTS(" ");
5060 if (new_fname != NULL)
5062 /* using "new_fname" is more reliable, e.g., when
5063 * 'includeexpr' is set. */
5064 msg_outtrans_attr(new_fname, hl_attr(HLF_D));
5066 else
5069 * Isolate the file name.
5070 * Include the surrounding "" or <> if present.
5072 for (p = incl_regmatch.endp[0]; !vim_isfilec(*p); p++)
5074 for (i = 0; vim_isfilec(p[i]); i++)
5076 if (i == 0)
5078 /* Nothing found, use the rest of the line. */
5079 p = incl_regmatch.endp[0];
5080 i = (int)STRLEN(p);
5082 else
5084 if (p[-1] == '"' || p[-1] == '<')
5086 --p;
5087 ++i;
5089 if (p[i] == '"' || p[i] == '>')
5090 ++i;
5092 save_char = p[i];
5093 p[i] = NUL;
5094 msg_outtrans_attr(p, hl_attr(HLF_D));
5095 p[i] = save_char;
5098 if (new_fname == NULL && action == ACTION_SHOW_ALL)
5100 if (already_searched)
5101 MSG_PUTS(_(" (Already listed)"));
5102 else
5103 MSG_PUTS(_(" NOT FOUND"));
5106 out_flush(); /* output each line directly */
5109 if (new_fname != NULL)
5111 /* Push the new file onto the file stack */
5112 if (depth + 1 == old_files)
5114 bigger = (SearchedFile *)lalloc((long_u)(
5115 max_path_depth * 2 * sizeof(SearchedFile)), TRUE);
5116 if (bigger != NULL)
5118 for (i = 0; i <= depth; i++)
5119 bigger[i] = files[i];
5120 for (i = depth + 1; i < old_files + max_path_depth; i++)
5122 bigger[i].fp = NULL;
5123 bigger[i].name = NULL;
5124 bigger[i].lnum = 0;
5125 bigger[i].matched = FALSE;
5127 for (i = old_files; i < max_path_depth; i++)
5128 bigger[i + max_path_depth] = files[i];
5129 old_files += max_path_depth;
5130 max_path_depth *= 2;
5131 vim_free(files);
5132 files = bigger;
5135 if ((files[depth + 1].fp = mch_fopen((char *)new_fname, "r"))
5136 == NULL)
5137 vim_free(new_fname);
5138 else
5140 if (++depth == old_files)
5143 * lalloc() for 'bigger' must have failed above. We
5144 * will forget one of our already visited files now.
5146 vim_free(files[old_files].name);
5147 ++old_files;
5149 files[depth].name = curr_fname = new_fname;
5150 files[depth].lnum = 0;
5151 files[depth].matched = FALSE;
5152 #ifdef FEAT_INS_EXPAND
5153 if (action == ACTION_EXPAND)
5155 msg_hist_off = TRUE; /* reset in msg_trunc_attr() */
5156 vim_snprintf((char*)IObuff, IOSIZE,
5157 _("Scanning included file: %s"),
5158 (char *)new_fname);
5159 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
5161 else
5162 #endif
5163 if (p_verbose >= 5)
5165 verbose_enter();
5166 smsg((char_u *)_("Searching included file %s"),
5167 (char *)new_fname);
5168 verbose_leave();
5174 else
5177 * Check if the line is a define (type == FIND_DEFINE)
5179 p = line;
5180 search_line:
5181 define_matched = FALSE;
5182 if (def_regmatch.regprog != NULL
5183 && vim_regexec(&def_regmatch, line, (colnr_T)0))
5186 * Pattern must be first identifier after 'define', so skip
5187 * to that position before checking for match of pattern. Also
5188 * don't let it match beyond the end of this identifier.
5190 p = def_regmatch.endp[0];
5191 while (*p && !vim_iswordc(*p))
5192 p++;
5193 define_matched = TRUE;
5197 * Look for a match. Don't do this if we are looking for a
5198 * define and this line didn't match define_prog above.
5200 if (def_regmatch.regprog == NULL || define_matched)
5202 if (define_matched
5203 #ifdef FEAT_INS_EXPAND
5204 || (compl_cont_status & CONT_SOL)
5205 #endif
5208 /* compare the first "len" chars from "ptr" */
5209 startp = skipwhite(p);
5210 if (p_ic)
5211 matched = !MB_STRNICMP(startp, ptr, len);
5212 else
5213 matched = !STRNCMP(startp, ptr, len);
5214 if (matched && define_matched && whole
5215 && vim_iswordc(startp[len]))
5216 matched = FALSE;
5218 else if (regmatch.regprog != NULL
5219 && vim_regexec(&regmatch, line, (colnr_T)(p - line)))
5221 matched = TRUE;
5222 startp = regmatch.startp[0];
5224 * Check if the line is not a comment line (unless we are
5225 * looking for a define). A line starting with "# define"
5226 * is not considered to be a comment line.
5228 if (!define_matched && skip_comments)
5230 #ifdef FEAT_COMMENTS
5231 if ((*line != '#' ||
5232 STRNCMP(skipwhite(line + 1), "define", 6) != 0)
5233 && get_leader_len(line, NULL, FALSE))
5234 matched = FALSE;
5237 * Also check for a "/ *" or "/ /" before the match.
5238 * Skips lines like "int backwards; / * normal index
5239 * * /" when looking for "normal".
5240 * Note: Doesn't skip "/ *" in comments.
5242 p = skipwhite(line);
5243 if (matched
5244 || (p[0] == '/' && p[1] == '*') || p[0] == '*')
5245 #endif
5246 for (p = line; *p && p < startp; ++p)
5248 if (matched
5249 && p[0] == '/'
5250 && (p[1] == '*' || p[1] == '/'))
5252 matched = FALSE;
5253 /* After "//" all text is comment */
5254 if (p[1] == '/')
5255 break;
5256 ++p;
5258 else if (!matched && p[0] == '*' && p[1] == '/')
5260 /* Can find match after "* /". */
5261 matched = TRUE;
5262 ++p;
5269 if (matched)
5271 #ifdef FEAT_INS_EXPAND
5272 if (action == ACTION_EXPAND)
5274 int reuse = 0;
5275 int add_r;
5276 char_u *aux;
5278 if (depth == -1 && lnum == curwin->w_cursor.lnum)
5279 break;
5280 found = TRUE;
5281 aux = p = startp;
5282 if (compl_cont_status & CONT_ADDING)
5284 p += compl_length;
5285 if (vim_iswordp(p))
5286 goto exit_matched;
5287 p = find_word_start(p);
5289 p = find_word_end(p);
5290 i = (int)(p - aux);
5292 if ((compl_cont_status & CONT_ADDING) && i == compl_length)
5294 /* IOSIZE > compl_length, so the STRNCPY works */
5295 STRNCPY(IObuff, aux, i);
5297 /* Get the next line: when "depth" < 0 from the current
5298 * buffer, otherwise from the included file. Jump to
5299 * exit_matched when past the last line. */
5300 if (depth < 0)
5302 if (lnum >= end_lnum)
5303 goto exit_matched;
5304 line = ml_get(++lnum);
5306 else if (vim_fgets(line = file_line,
5307 LSIZE, files[depth].fp))
5308 goto exit_matched;
5310 /* we read a line, set "already" to check this "line" later
5311 * if depth >= 0 we'll increase files[depth].lnum far
5312 * bellow -- Acevedo */
5313 already = aux = p = skipwhite(line);
5314 p = find_word_start(p);
5315 p = find_word_end(p);
5316 if (p > aux)
5318 if (*aux != ')' && IObuff[i-1] != TAB)
5320 if (IObuff[i-1] != ' ')
5321 IObuff[i++] = ' ';
5322 /* IObuf =~ "\(\k\|\i\).* ", thus i >= 2*/
5323 if (p_js
5324 && (IObuff[i-2] == '.'
5325 || (vim_strchr(p_cpo, CPO_JOINSP) == NULL
5326 && (IObuff[i-2] == '?'
5327 || IObuff[i-2] == '!'))))
5328 IObuff[i++] = ' ';
5330 /* copy as much as possible of the new word */
5331 if (p - aux >= IOSIZE - i)
5332 p = aux + IOSIZE - i - 1;
5333 STRNCPY(IObuff + i, aux, p - aux);
5334 i += (int)(p - aux);
5335 reuse |= CONT_S_IPOS;
5337 IObuff[i] = NUL;
5338 aux = IObuff;
5340 if (i == compl_length)
5341 goto exit_matched;
5344 add_r = ins_compl_add_infercase(aux, i, p_ic,
5345 curr_fname == curbuf->b_fname ? NULL : curr_fname,
5346 dir, reuse);
5347 if (add_r == OK)
5348 /* if dir was BACKWARD then honor it just once */
5349 dir = FORWARD;
5350 else if (add_r == FAIL)
5351 break;
5353 else
5354 #endif
5355 if (action == ACTION_SHOW_ALL)
5357 found = TRUE;
5358 if (!did_show)
5359 gotocmdline(TRUE); /* cursor at status line */
5360 if (curr_fname != prev_fname)
5362 if (did_show)
5363 msg_putchar('\n'); /* cursor below last one */
5364 if (!got_int) /* don't display if 'q' typed
5365 at "--more--" message */
5366 msg_home_replace_hl(curr_fname);
5367 prev_fname = curr_fname;
5369 did_show = TRUE;
5370 if (!got_int)
5371 show_pat_in_path(line, type, TRUE, action,
5372 (depth == -1) ? NULL : files[depth].fp,
5373 (depth == -1) ? &lnum : &files[depth].lnum,
5374 match_count++);
5376 /* Set matched flag for this file and all the ones that
5377 * include it */
5378 for (i = 0; i <= depth; ++i)
5379 files[i].matched = TRUE;
5381 else if (--count <= 0)
5383 found = TRUE;
5384 if (depth == -1 && lnum == curwin->w_cursor.lnum
5385 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
5386 && g_do_tagpreview == 0
5387 #endif
5389 EMSG(_("E387: Match is on current line"));
5390 else if (action == ACTION_SHOW)
5392 show_pat_in_path(line, type, did_show, action,
5393 (depth == -1) ? NULL : files[depth].fp,
5394 (depth == -1) ? &lnum : &files[depth].lnum, 1L);
5395 did_show = TRUE;
5397 else
5399 #ifdef FEAT_GUI
5400 need_mouse_correct = TRUE;
5401 #endif
5402 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
5403 /* ":psearch" uses the preview window */
5404 if (g_do_tagpreview != 0)
5406 curwin_save = curwin;
5407 prepare_tagpreview(TRUE);
5409 #endif
5410 if (action == ACTION_SPLIT)
5412 #ifdef FEAT_WINDOWS
5413 if (win_split(0, 0) == FAIL)
5414 #endif
5415 break;
5416 #ifdef FEAT_SCROLLBIND
5417 curwin->w_p_scb = FALSE;
5418 #endif
5420 if (depth == -1)
5422 /* match in current file */
5423 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
5424 if (g_do_tagpreview != 0)
5426 if (getfile(0, curwin_save->w_buffer->b_fname,
5427 NULL, TRUE, lnum, FALSE) > 0)
5428 break; /* failed to jump to file */
5430 else
5431 #endif
5432 setpcmark();
5433 curwin->w_cursor.lnum = lnum;
5435 else
5437 if (getfile(0, files[depth].name, NULL, TRUE,
5438 files[depth].lnum, FALSE) > 0)
5439 break; /* failed to jump to file */
5440 /* autocommands may have changed the lnum, we don't
5441 * want that here */
5442 curwin->w_cursor.lnum = files[depth].lnum;
5445 if (action != ACTION_SHOW)
5447 curwin->w_cursor.col = (colnr_T)(startp - line);
5448 curwin->w_set_curswant = TRUE;
5451 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
5452 if (g_do_tagpreview != 0
5453 && curwin != curwin_save && win_valid(curwin_save))
5455 /* Return cursor to where we were */
5456 validate_cursor();
5457 redraw_later(VALID);
5458 win_enter(curwin_save, TRUE);
5460 #endif
5461 break;
5463 #ifdef FEAT_INS_EXPAND
5464 exit_matched:
5465 #endif
5466 matched = FALSE;
5467 /* look for other matches in the rest of the line if we
5468 * are not at the end of it already */
5469 if (def_regmatch.regprog == NULL
5470 #ifdef FEAT_INS_EXPAND
5471 && action == ACTION_EXPAND
5472 && !(compl_cont_status & CONT_SOL)
5473 #endif
5474 && *startp != NUL
5475 && *(p = startp + 1) != NUL)
5476 goto search_line;
5478 line_breakcheck();
5479 #ifdef FEAT_INS_EXPAND
5480 if (action == ACTION_EXPAND)
5481 ins_compl_check_keys(30);
5482 if (got_int || compl_interrupted)
5483 #else
5484 if (got_int)
5485 #endif
5486 break;
5489 * Read the next line. When reading an included file and encountering
5490 * end-of-file, close the file and continue in the file that included
5491 * it.
5493 while (depth >= 0 && !already
5494 && vim_fgets(line = file_line, LSIZE, files[depth].fp))
5496 fclose(files[depth].fp);
5497 --old_files;
5498 files[old_files].name = files[depth].name;
5499 files[old_files].matched = files[depth].matched;
5500 --depth;
5501 curr_fname = (depth == -1) ? curbuf->b_fname
5502 : files[depth].name;
5503 if (depth < depth_displayed)
5504 depth_displayed = depth;
5506 if (depth >= 0) /* we could read the line */
5507 files[depth].lnum++;
5508 else if (!already)
5510 if (++lnum > end_lnum)
5511 break;
5512 line = ml_get(lnum);
5514 already = NULL;
5516 /* End of big for (;;) loop. */
5518 /* Close any files that are still open. */
5519 for (i = 0; i <= depth; i++)
5521 fclose(files[i].fp);
5522 vim_free(files[i].name);
5524 for (i = old_files; i < max_path_depth; i++)
5525 vim_free(files[i].name);
5526 vim_free(files);
5528 if (type == CHECK_PATH)
5530 if (!did_show)
5532 if (action != ACTION_SHOW_ALL)
5533 MSG(_("All included files were found"));
5534 else
5535 MSG(_("No included files"));
5538 else if (!found
5539 #ifdef FEAT_INS_EXPAND
5540 && action != ACTION_EXPAND
5541 #endif
5544 #ifdef FEAT_INS_EXPAND
5545 if (got_int || compl_interrupted)
5546 #else
5547 if (got_int)
5548 #endif
5549 EMSG(_(e_interr));
5550 else if (type == FIND_DEFINE)
5551 EMSG(_("E388: Couldn't find definition"));
5552 else
5553 EMSG(_("E389: Couldn't find pattern"));
5555 if (action == ACTION_SHOW || action == ACTION_SHOW_ALL)
5556 msg_end();
5558 fpip_end:
5559 vim_free(file_line);
5560 vim_free(regmatch.regprog);
5561 vim_free(incl_regmatch.regprog);
5562 vim_free(def_regmatch.regprog);
5564 #ifdef RISCOS
5565 /* Restore previous file munging state. */
5566 __riscosify_control = previous_munging;
5567 #endif
5570 static void
5571 show_pat_in_path(line, type, did_show, action, fp, lnum, count)
5572 char_u *line;
5573 int type;
5574 int did_show;
5575 int action;
5576 FILE *fp;
5577 linenr_T *lnum;
5578 long count;
5580 char_u *p;
5582 if (did_show)
5583 msg_putchar('\n'); /* cursor below last one */
5584 else if (!msg_silent)
5585 gotocmdline(TRUE); /* cursor at status line */
5586 if (got_int) /* 'q' typed at "--more--" message */
5587 return;
5588 for (;;)
5590 p = line + STRLEN(line) - 1;
5591 if (fp != NULL)
5593 /* We used fgets(), so get rid of newline at end */
5594 if (p >= line && *p == '\n')
5595 --p;
5596 if (p >= line && *p == '\r')
5597 --p;
5598 *(p + 1) = NUL;
5600 if (action == ACTION_SHOW_ALL)
5602 sprintf((char *)IObuff, "%3ld: ", count); /* show match nr */
5603 msg_puts(IObuff);
5604 sprintf((char *)IObuff, "%4ld", *lnum); /* show line nr */
5605 /* Highlight line numbers */
5606 msg_puts_attr(IObuff, hl_attr(HLF_N));
5607 MSG_PUTS(" ");
5609 msg_prt_line(line, FALSE);
5610 out_flush(); /* show one line at a time */
5612 /* Definition continues until line that doesn't end with '\' */
5613 if (got_int || type != FIND_DEFINE || p < line || *p != '\\')
5614 break;
5616 if (fp != NULL)
5618 if (vim_fgets(line, LSIZE, fp)) /* end of file */
5619 break;
5620 ++*lnum;
5622 else
5624 if (++*lnum > curbuf->b_ml.ml_line_count)
5625 break;
5626 line = ml_get(*lnum);
5628 msg_putchar('\n');
5631 #endif
5633 #ifdef FEAT_VIMINFO
5635 read_viminfo_search_pattern(virp, force)
5636 vir_T *virp;
5637 int force;
5639 char_u *lp;
5640 int idx = -1;
5641 int magic = FALSE;
5642 int no_scs = FALSE;
5643 int off_line = FALSE;
5644 int off_end = 0;
5645 long off = 0;
5646 int setlast = FALSE;
5647 #ifdef FEAT_SEARCH_EXTRA
5648 static int hlsearch_on = FALSE;
5649 #endif
5650 char_u *val;
5653 * Old line types:
5654 * "/pat", "&pat": search/subst. pat
5655 * "~/pat", "~&pat": last used search/subst. pat
5656 * New line types:
5657 * "~h", "~H": hlsearch highlighting off/on
5658 * "~<magic><smartcase><line><end><off><last><which>pat"
5659 * <magic>: 'm' off, 'M' on
5660 * <smartcase>: 's' off, 'S' on
5661 * <line>: 'L' line offset, 'l' char offset
5662 * <end>: 'E' from end, 'e' from start
5663 * <off>: decimal, offset
5664 * <last>: '~' last used pattern
5665 * <which>: '/' search pat, '&' subst. pat
5667 lp = virp->vir_line;
5668 if (lp[0] == '~' && (lp[1] == 'm' || lp[1] == 'M')) /* new line type */
5670 if (lp[1] == 'M') /* magic on */
5671 magic = TRUE;
5672 if (lp[2] == 's')
5673 no_scs = TRUE;
5674 if (lp[3] == 'L')
5675 off_line = TRUE;
5676 if (lp[4] == 'E')
5677 off_end = SEARCH_END;
5678 lp += 5;
5679 off = getdigits(&lp);
5681 if (lp[0] == '~') /* use this pattern for last-used pattern */
5683 setlast = TRUE;
5684 lp++;
5686 if (lp[0] == '/')
5687 idx = RE_SEARCH;
5688 else if (lp[0] == '&')
5689 idx = RE_SUBST;
5690 #ifdef FEAT_SEARCH_EXTRA
5691 else if (lp[0] == 'h') /* ~h: 'hlsearch' highlighting off */
5692 hlsearch_on = FALSE;
5693 else if (lp[0] == 'H') /* ~H: 'hlsearch' highlighting on */
5694 hlsearch_on = TRUE;
5695 #endif
5696 if (idx >= 0)
5698 if (force || spats[idx].pat == NULL)
5700 val = viminfo_readstring(virp, (int)(lp - virp->vir_line + 1),
5701 TRUE);
5702 if (val != NULL)
5704 set_last_search_pat(val, idx, magic, setlast);
5705 vim_free(val);
5706 spats[idx].no_scs = no_scs;
5707 spats[idx].off.line = off_line;
5708 spats[idx].off.end = off_end;
5709 spats[idx].off.off = off;
5710 #ifdef FEAT_SEARCH_EXTRA
5711 if (setlast)
5712 no_hlsearch = !hlsearch_on;
5713 #endif
5717 return viminfo_readline(virp);
5720 void
5721 write_viminfo_search_pattern(fp)
5722 FILE *fp;
5724 if (get_viminfo_parameter('/') != 0)
5726 #ifdef FEAT_SEARCH_EXTRA
5727 fprintf(fp, "\n# hlsearch on (H) or off (h):\n~%c",
5728 (no_hlsearch || find_viminfo_parameter('h') != NULL) ? 'h' : 'H');
5729 #endif
5730 wvsp_one(fp, RE_SEARCH, "", '/');
5731 wvsp_one(fp, RE_SUBST, _("Substitute "), '&');
5735 static void
5736 wvsp_one(fp, idx, s, sc)
5737 FILE *fp; /* file to write to */
5738 int idx; /* spats[] index */
5739 char *s; /* search pat */
5740 int sc; /* dir char */
5742 if (spats[idx].pat != NULL)
5744 fprintf(fp, _("\n# Last %sSearch Pattern:\n~"), s);
5745 /* off.dir is not stored, it's reset to forward */
5746 fprintf(fp, "%c%c%c%c%ld%s%c",
5747 spats[idx].magic ? 'M' : 'm', /* magic */
5748 spats[idx].no_scs ? 's' : 'S', /* smartcase */
5749 spats[idx].off.line ? 'L' : 'l', /* line offset */
5750 spats[idx].off.end ? 'E' : 'e', /* offset from end */
5751 spats[idx].off.off, /* offset */
5752 last_idx == idx ? "~" : "", /* last used pat */
5753 sc);
5754 viminfo_writestring(fp, spats[idx].pat);
5757 #endif /* FEAT_VIMINFO */