Merge branch 'vim' into feat/code-check
[vim_extended.git] / src / getchar.c
blob2262c25ca152714d0f80c5fea7d2f756c4599733
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 */
11 * getchar.c
13 * functions related with getting a character from the user/mapping/redo/...
15 * manipulations with redo buffer and stuff buffer
16 * mappings and abbreviations
19 #include "vim.h"
22 * These buffers are used for storing:
23 * - stuffed characters: A command that is translated into another command.
24 * - redo characters: will redo the last change.
25 * - recorded characters: for the "q" command.
27 * The bytes are stored like in the typeahead buffer:
28 * - K_SPECIAL introduces a special key (two more bytes follow). A literal
29 * K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
30 * - CSI introduces a GUI termcap code (also when gui.in_use is FALSE,
31 * otherwise switching the GUI on would make mappings invalid).
32 * A literal CSI is stored as CSI KS_EXTRA KE_CSI.
33 * These translations are also done on multi-byte characters!
35 * Escaping CSI bytes is done by the system-specific input functions, called
36 * by ui_inchar().
37 * Escaping K_SPECIAL is done by inchar().
38 * Un-escaping is done by vgetc().
41 #define MINIMAL_SIZE 20 /* minimal size for b_str */
43 static struct buffheader redobuff = {{NULL, {NUL}}, NULL, 0, 0};
44 static struct buffheader old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
45 #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO)
46 static struct buffheader save_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
47 static struct buffheader save_old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
48 #endif
49 static struct buffheader recordbuff = {{NULL, {NUL}}, NULL, 0, 0};
51 static int typeahead_char = 0; /* typeahead char that's not flushed */
54 * when block_redo is TRUE redo buffer will not be changed
55 * used by edit() to repeat insertions and 'V' command for redoing
57 static int block_redo = FALSE;
60 * Make a hash value for a mapping.
61 * "mode" is the lower 4 bits of the State for the mapping.
62 * "c1" is the first character of the "lhs".
63 * Returns a value between 0 and 255, index in maphash.
64 * Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
66 #define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + SELECTMODE + OP_PENDING)) ? (c1) : ((c1) ^ 0x80))
69 * Each mapping is put in one of the 256 hash lists, to speed up finding it.
71 static mapblock_T *(maphash[256]);
72 static int maphash_valid = FALSE;
75 * List used for abbreviations.
77 static mapblock_T *first_abbr = NULL; /* first entry in abbrlist */
79 static int KeyNoremap = 0; /* remapping flags */
82 * variables used by vgetorpeek() and flush_buffers()
84 * typebuf.tb_buf[] contains all characters that are not consumed yet.
85 * typebuf.tb_buf[typebuf.tb_off] is the first valid character.
86 * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
87 * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
88 * The head of the buffer may contain the result of mappings, abbreviations
89 * and @a commands. The length of this part is typebuf.tb_maplen.
90 * typebuf.tb_silent is the part where <silent> applies.
91 * After the head are characters that come from the terminal.
92 * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
93 * should not be considered for abbreviations.
94 * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
95 * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
96 * contains RM_NONE for the characters that are not to be remapped.
97 * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
98 * (typebuf has been put in globals.h, because check_termcode() needs it).
100 #define RM_YES 0 /* tb_noremap: remap */
101 #define RM_NONE 1 /* tb_noremap: don't remap */
102 #define RM_SCRIPT 2 /* tb_noremap: remap local script mappings */
103 #define RM_ABBR 4 /* tb_noremap: don't remap, do abbrev. */
105 /* typebuf.tb_buf has three parts: room in front (for result of mappings), the
106 * middle for typeahead and room for new characters (which needs to be 3 *
107 * MAXMAPLEN) for the Amiga).
109 #define TYPELEN_INIT (5 * (MAXMAPLEN + 3))
110 static char_u typebuf_init[TYPELEN_INIT]; /* initial typebuf.tb_buf */
111 static char_u noremapbuf_init[TYPELEN_INIT]; /* initial typebuf.tb_noremap */
113 static int last_recorded_len = 0; /* number of last recorded chars */
115 static char_u *get_buffcont __ARGS((struct buffheader *, int));
116 static void add_buff __ARGS((struct buffheader *, char_u *, long n));
117 static void add_num_buff __ARGS((struct buffheader *, long));
118 static void add_char_buff __ARGS((struct buffheader *, int));
119 static int read_stuff __ARGS((int advance));
120 static void start_stuff __ARGS((void));
121 static int read_redo __ARGS((int, int));
122 static void copy_redo __ARGS((int));
123 static void init_typebuf __ARGS((void));
124 static void gotchars __ARGS((char_u *, int));
125 static void may_sync_undo __ARGS((void));
126 static void closescript __ARGS((void));
127 static int vgetorpeek __ARGS((int));
128 static void map_free __ARGS((mapblock_T **));
129 static void validate_maphash __ARGS((void));
130 static void showmap __ARGS((mapblock_T *mp, int local));
131 #ifdef FEAT_EVAL
132 static char_u *eval_map_expr __ARGS((char_u *str, int c));
133 #endif
136 * Free and clear a buffer.
138 void
139 free_buff(buf)
140 struct buffheader *buf;
142 struct buffblock *p, *np;
144 for (p = buf->bh_first.b_next; p != NULL; p = np)
146 np = p->b_next;
147 vim_free(p);
149 buf->bh_first.b_next = NULL;
153 * Return the contents of a buffer as a single string.
154 * K_SPECIAL and CSI in the returned string are escaped.
156 static char_u *
157 get_buffcont(buffer, dozero)
158 struct buffheader *buffer;
159 int dozero; /* count == zero is not an error */
161 long_u count = 0;
162 char_u *p = NULL;
163 char_u *p2;
164 char_u *str;
165 struct buffblock *bp;
167 /* compute the total length of the string */
168 for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
169 count += (long_u)STRLEN(bp->b_str);
171 if ((count || dozero) && (p = lalloc(count + 1, TRUE)) != NULL)
173 p2 = p;
174 for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
175 for (str = bp->b_str; *str; )
176 *p2++ = *str++;
177 *p2 = NUL;
179 return (p);
183 * Return the contents of the record buffer as a single string
184 * and clear the record buffer.
185 * K_SPECIAL and CSI in the returned string are escaped.
187 char_u *
188 get_recorded()
190 char_u *p;
191 size_t len;
193 p = get_buffcont(&recordbuff, TRUE);
194 free_buff(&recordbuff);
197 * Remove the characters that were added the last time, these must be the
198 * (possibly mapped) characters that stopped the recording.
200 len = STRLEN(p);
201 if ((int)len >= last_recorded_len)
203 len -= last_recorded_len;
204 p[len] = NUL;
208 * When stopping recording from Insert mode with CTRL-O q, also remove the
209 * CTRL-O.
211 if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O)
212 p[len - 1] = NUL;
214 return (p);
218 * Return the contents of the redo buffer as a single string.
219 * K_SPECIAL and CSI in the returned string are escaped.
221 char_u *
222 get_inserted()
224 return get_buffcont(&redobuff, FALSE);
228 * Add string "s" after the current block of buffer "buf".
229 * K_SPECIAL and CSI should have been escaped already.
231 static void
232 add_buff(buf, s, slen)
233 struct buffheader *buf;
234 char_u *s;
235 long slen; /* length of "s" or -1 */
237 struct buffblock *p;
238 long_u len;
240 if (slen < 0)
241 slen = (long)STRLEN(s);
242 if (slen == 0) /* don't add empty strings */
243 return;
245 if (buf->bh_first.b_next == NULL) /* first add to list */
247 buf->bh_space = 0;
248 buf->bh_curr = &(buf->bh_first);
250 else if (buf->bh_curr == NULL) /* buffer has already been read */
252 EMSG(_("E222: Add to read buffer"));
253 return;
255 else if (buf->bh_index != 0)
256 mch_memmove(buf->bh_first.b_next->b_str,
257 buf->bh_first.b_next->b_str + buf->bh_index,
258 STRLEN(buf->bh_first.b_next->b_str + buf->bh_index) + 1);
259 buf->bh_index = 0;
261 if (buf->bh_space >= (int)slen)
263 len = (long_u)STRLEN(buf->bh_curr->b_str);
264 vim_strncpy(buf->bh_curr->b_str + len, s, (size_t)slen);
265 buf->bh_space -= slen;
267 else
269 if (slen < MINIMAL_SIZE)
270 len = MINIMAL_SIZE;
271 else
272 len = slen;
273 p = (struct buffblock *)lalloc((long_u)(sizeof(struct buffblock) + len),
274 TRUE);
275 if (p == NULL)
276 return; /* no space, just forget it */
277 buf->bh_space = (int)(len - slen);
278 vim_strncpy(p->b_str, s, (size_t)slen);
280 p->b_next = buf->bh_curr->b_next;
281 buf->bh_curr->b_next = p;
282 buf->bh_curr = p;
284 return;
288 * Add number "n" to buffer "buf".
290 static void
291 add_num_buff(buf, n)
292 struct buffheader *buf;
293 long n;
295 char_u number[32];
297 sprintf((char *)number, "%ld", n);
298 add_buff(buf, number, -1L);
302 * Add character 'c' to buffer "buf".
303 * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
305 static void
306 add_char_buff(buf, c)
307 struct buffheader *buf;
308 int c;
310 #ifdef FEAT_MBYTE
311 char_u bytes[MB_MAXBYTES + 1];
312 int len;
313 int i;
314 #endif
315 char_u temp[4];
317 #ifdef FEAT_MBYTE
318 if (IS_SPECIAL(c))
319 len = 1;
320 else
321 len = (*mb_char2bytes)(c, bytes);
322 for (i = 0; i < len; ++i)
324 if (!IS_SPECIAL(c))
325 c = bytes[i];
326 #endif
328 if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL)
330 /* translate special key code into three byte sequence */
331 temp[0] = K_SPECIAL;
332 temp[1] = K_SECOND(c);
333 temp[2] = K_THIRD(c);
334 temp[3] = NUL;
336 #ifdef FEAT_GUI
337 else if (c == CSI)
339 /* Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence */
340 temp[0] = CSI;
341 temp[1] = KS_EXTRA;
342 temp[2] = (int)KE_CSI;
343 temp[3] = NUL;
345 #endif
346 else
348 temp[0] = c;
349 temp[1] = NUL;
351 add_buff(buf, temp, -1L);
352 #ifdef FEAT_MBYTE
354 #endif
358 * Get one byte from the stuff buffer.
359 * If advance == TRUE go to the next char.
360 * No translation is done K_SPECIAL and CSI are escaped.
362 static int
363 read_stuff(advance)
364 int advance;
366 char_u c;
367 struct buffblock *curr;
369 if (stuffbuff.bh_first.b_next == NULL) /* buffer is empty */
370 return NUL;
372 curr = stuffbuff.bh_first.b_next;
373 c = curr->b_str[stuffbuff.bh_index];
375 if (advance)
377 if (curr->b_str[++stuffbuff.bh_index] == NUL)
379 stuffbuff.bh_first.b_next = curr->b_next;
380 vim_free(curr);
381 stuffbuff.bh_index = 0;
384 return c;
388 * Prepare the stuff buffer for reading (if it contains something).
390 static void
391 start_stuff()
393 if (stuffbuff.bh_first.b_next != NULL)
395 stuffbuff.bh_curr = &(stuffbuff.bh_first);
396 stuffbuff.bh_space = 0;
401 * Return TRUE if the stuff buffer is empty.
404 stuff_empty()
406 return (stuffbuff.bh_first.b_next == NULL);
410 * Set a typeahead character that won't be flushed.
412 void
413 typeahead_noflush(c)
414 int c;
416 typeahead_char = c;
420 * Remove the contents of the stuff buffer and the mapped characters in the
421 * typeahead buffer (used in case of an error). If 'typeahead' is true,
422 * flush all typeahead characters (used when interrupted by a CTRL-C).
424 void
425 flush_buffers(typeahead)
426 int typeahead;
428 init_typebuf();
430 start_stuff();
431 while (read_stuff(TRUE) != NUL)
434 if (typeahead) /* remove all typeahead */
437 * We have to get all characters, because we may delete the first part
438 * of an escape sequence.
439 * In an xterm we get one char at a time and we have to get them all.
441 while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L,
442 typebuf.tb_change_cnt) != 0)
444 typebuf.tb_off = MAXMAPLEN;
445 typebuf.tb_len = 0;
447 else /* remove mapped characters only */
449 typebuf.tb_off += typebuf.tb_maplen;
450 typebuf.tb_len -= typebuf.tb_maplen;
452 typebuf.tb_maplen = 0;
453 typebuf.tb_silent = 0;
454 cmd_silent = FALSE;
455 typebuf.tb_no_abbr_cnt = 0;
459 * The previous contents of the redo buffer is kept in old_redobuffer.
460 * This is used for the CTRL-O <.> command in insert mode.
462 void
463 ResetRedobuff()
465 if (!block_redo)
467 free_buff(&old_redobuff);
468 old_redobuff = redobuff;
469 redobuff.bh_first.b_next = NULL;
473 #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO)
475 * Save redobuff and old_redobuff to save_redobuff and save_old_redobuff.
476 * Used before executing autocommands and user functions.
478 static int save_level = 0;
480 void
481 saveRedobuff()
483 char_u *s;
485 if (save_level++ == 0)
487 save_redobuff = redobuff;
488 redobuff.bh_first.b_next = NULL;
489 save_old_redobuff = old_redobuff;
490 old_redobuff.bh_first.b_next = NULL;
492 /* Make a copy, so that ":normal ." in a function works. */
493 s = get_buffcont(&save_redobuff, FALSE);
494 if (s != NULL)
496 add_buff(&redobuff, s, -1L);
497 vim_free(s);
503 * Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff.
504 * Used after executing autocommands and user functions.
506 void
507 restoreRedobuff()
509 if (--save_level == 0)
511 free_buff(&redobuff);
512 redobuff = save_redobuff;
513 free_buff(&old_redobuff);
514 old_redobuff = save_old_redobuff;
517 #endif
520 * Append "s" to the redo buffer.
521 * K_SPECIAL and CSI should already have been escaped.
523 void
524 AppendToRedobuff(s)
525 char_u *s;
527 if (!block_redo)
528 add_buff(&redobuff, s, -1L);
532 * Append to Redo buffer literally, escaping special characters with CTRL-V.
533 * K_SPECIAL and CSI are escaped as well.
535 void
536 AppendToRedobuffLit(str, len)
537 char_u *str;
538 int len; /* length of "str" or -1 for up to the NUL */
540 char_u *s = str;
541 int c;
542 char_u *start;
544 if (block_redo)
545 return;
547 while (len < 0 ? *s != NUL : s - str < len)
549 /* Put a string of normal characters in the redo buffer (that's
550 * faster). */
551 start = s;
552 while (*s >= ' '
553 #ifndef EBCDIC
554 && *s < DEL /* EBCDIC: all chars above space are normal */
555 #endif
556 && (len < 0 || s - str < len))
557 ++s;
559 /* Don't put '0' or '^' as last character, just in case a CTRL-D is
560 * typed next. */
561 if (*s == NUL && (s[-1] == '0' || s[-1] == '^'))
562 --s;
563 if (s > start)
564 add_buff(&redobuff, start, (long)(s - start));
566 if (*s == NUL || (len >= 0 && s - str >= len))
567 break;
569 /* Handle a special or multibyte character. */
570 #ifdef FEAT_MBYTE
571 if (has_mbyte)
572 /* Handle composing chars separately. */
573 c = mb_cptr2char_adv(&s);
574 else
575 #endif
576 c = *s++;
577 if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^')))
578 add_char_buff(&redobuff, Ctrl_V);
580 /* CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0) */
581 if (*s == NUL && c == '0')
582 #ifdef EBCDIC
583 add_buff(&redobuff, (char_u *)"xf0", 3L);
584 #else
585 add_buff(&redobuff, (char_u *)"048", 3L);
586 #endif
587 else
588 add_char_buff(&redobuff, c);
593 * Append a character to the redo buffer.
594 * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
596 void
597 AppendCharToRedobuff(c)
598 int c;
600 if (!block_redo)
601 add_char_buff(&redobuff, c);
605 * Append a number to the redo buffer.
607 void
608 AppendNumberToRedobuff(n)
609 long n;
611 if (!block_redo)
612 add_num_buff(&redobuff, n);
616 * Append string "s" to the stuff buffer.
617 * CSI and K_SPECIAL must already have been escaped.
619 void
620 stuffReadbuff(s)
621 char_u *s;
623 add_buff(&stuffbuff, s, -1L);
626 void
627 stuffReadbuffLen(s, len)
628 char_u *s;
629 long len;
631 add_buff(&stuffbuff, s, len);
634 #if defined(FEAT_EVAL) || defined(PROTO)
636 * Stuff "s" into the stuff buffer, leaving special key codes unmodified and
637 * escaping other K_SPECIAL and CSI bytes.
639 void
640 stuffReadbuffSpec(s)
641 char_u *s;
643 while (*s != NUL)
645 if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL)
647 /* Insert special key literally. */
648 stuffReadbuffLen(s, 3L);
649 s += 3;
651 else
652 #ifdef FEAT_MBYTE
653 stuffcharReadbuff(mb_ptr2char_adv(&s));
654 #else
655 stuffcharReadbuff(*s++);
656 #endif
659 #endif
662 * Append a character to the stuff buffer.
663 * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
665 void
666 stuffcharReadbuff(c)
667 int c;
669 add_char_buff(&stuffbuff, c);
673 * Append a number to the stuff buffer.
675 void
676 stuffnumReadbuff(n)
677 long n;
679 add_num_buff(&stuffbuff, n);
683 * Read a character from the redo buffer. Translates K_SPECIAL, CSI and
684 * multibyte characters.
685 * The redo buffer is left as it is.
686 * if init is TRUE, prepare for redo, return FAIL if nothing to redo, OK
687 * otherwise
688 * if old is TRUE, use old_redobuff instead of redobuff
690 static int
691 read_redo(init, old_redo)
692 int init;
693 int old_redo;
695 static struct buffblock *bp;
696 static char_u *p;
697 int c;
698 #ifdef FEAT_MBYTE
699 int n;
700 char_u buf[MB_MAXBYTES];
701 int i;
702 #endif
704 if (init)
706 if (old_redo)
707 bp = old_redobuff.bh_first.b_next;
708 else
709 bp = redobuff.bh_first.b_next;
710 if (bp == NULL)
711 return FAIL;
712 p = bp->b_str;
713 return OK;
715 if ((c = *p) != NUL)
717 /* Reverse the conversion done by add_char_buff() */
718 #ifdef FEAT_MBYTE
719 /* For a multi-byte character get all the bytes and return the
720 * converted character. */
721 if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL))
722 n = MB_BYTE2LEN_CHECK(c);
723 else
724 n = 1;
725 for (i = 0; ; ++i)
726 #endif
728 if (c == K_SPECIAL) /* special key or escaped K_SPECIAL */
730 c = TO_SPECIAL(p[1], p[2]);
731 p += 2;
733 #ifdef FEAT_GUI
734 if (c == CSI) /* escaped CSI */
735 p += 2;
736 #endif
737 if (*++p == NUL && bp->b_next != NULL)
739 bp = bp->b_next;
740 p = bp->b_str;
742 #ifdef FEAT_MBYTE
743 buf[i] = c;
744 if (i == n - 1) /* last byte of a character */
746 if (n != 1)
747 c = (*mb_ptr2char)(buf);
748 break;
750 c = *p;
751 if (c == NUL) /* cannot happen? */
752 break;
753 #endif
757 return c;
761 * Copy the rest of the redo buffer into the stuff buffer (in a slow way).
762 * If old_redo is TRUE, use old_redobuff instead of redobuff.
763 * The escaped K_SPECIAL and CSI are copied without translation.
765 static void
766 copy_redo(old_redo)
767 int old_redo;
769 int c;
771 while ((c = read_redo(FALSE, old_redo)) != NUL)
772 stuffcharReadbuff(c);
776 * Stuff the redo buffer into the stuffbuff.
777 * Insert the redo count into the command.
778 * If "old_redo" is TRUE, the last but one command is repeated
779 * instead of the last command (inserting text). This is used for
780 * CTRL-O <.> in insert mode
782 * return FAIL for failure, OK otherwise
785 start_redo(count, old_redo)
786 long count;
787 int old_redo;
789 int c;
791 /* init the pointers; return if nothing to redo */
792 if (read_redo(TRUE, old_redo) == FAIL)
793 return FAIL;
795 c = read_redo(FALSE, old_redo);
797 /* copy the buffer name, if present */
798 if (c == '"')
800 add_buff(&stuffbuff, (char_u *)"\"", 1L);
801 c = read_redo(FALSE, old_redo);
803 /* if a numbered buffer is used, increment the number */
804 if (c >= '1' && c < '9')
805 ++c;
806 add_char_buff(&stuffbuff, c);
807 c = read_redo(FALSE, old_redo);
810 #ifdef FEAT_VISUAL
811 if (c == 'v') /* redo Visual */
813 VIsual = curwin->w_cursor;
814 VIsual_active = TRUE;
815 VIsual_select = FALSE;
816 VIsual_reselect = TRUE;
817 redo_VIsual_busy = TRUE;
818 c = read_redo(FALSE, old_redo);
820 #endif
822 /* try to enter the count (in place of a previous count) */
823 if (count)
825 while (VIM_ISDIGIT(c)) /* skip "old" count */
826 c = read_redo(FALSE, old_redo);
827 add_num_buff(&stuffbuff, count);
830 /* copy from the redo buffer into the stuff buffer */
831 add_char_buff(&stuffbuff, c);
832 copy_redo(old_redo);
833 return OK;
837 * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
838 * the redo buffer into the stuffbuff.
839 * return FAIL for failure, OK otherwise
842 start_redo_ins()
844 int c;
846 if (read_redo(TRUE, FALSE) == FAIL)
847 return FAIL;
848 start_stuff();
850 /* skip the count and the command character */
851 while ((c = read_redo(FALSE, FALSE)) != NUL)
853 if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL)
855 if (c == 'O' || c == 'o')
856 stuffReadbuff(NL_STR);
857 break;
861 /* copy the typed text from the redo buffer into the stuff buffer */
862 copy_redo(FALSE);
863 block_redo = TRUE;
864 return OK;
867 void
868 stop_redo_ins()
870 block_redo = FALSE;
874 * Initialize typebuf.tb_buf to point to typebuf_init.
875 * alloc() cannot be used here: In out-of-memory situations it would
876 * be impossible to type anything.
878 static void
879 init_typebuf()
881 if (typebuf.tb_buf == NULL)
883 typebuf.tb_buf = typebuf_init;
884 typebuf.tb_noremap = noremapbuf_init;
885 typebuf.tb_buflen = TYPELEN_INIT;
886 typebuf.tb_len = 0;
887 typebuf.tb_off = 0;
888 typebuf.tb_change_cnt = 1;
893 * insert a string in position 'offset' in the typeahead buffer (for "@r"
894 * and ":normal" command, vgetorpeek() and check_termcode())
896 * If noremap is REMAP_YES, new string can be mapped again.
897 * If noremap is REMAP_NONE, new string cannot be mapped again.
898 * If noremap is REMAP_SKIP, fist char of new string cannot be mapped again,
899 * but abbreviations are allowed.
900 * If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
901 * script-local mappings.
902 * If noremap is > 0, that many characters of the new string cannot be mapped.
904 * If nottyped is TRUE, the string does not return KeyTyped (don't use when
905 * offset is non-zero!).
907 * If silent is TRUE, cmd_silent is set when the characters are obtained.
909 * return FAIL for failure, OK otherwise
912 ins_typebuf(str, noremap, offset, nottyped, silent)
913 char_u *str;
914 int noremap;
915 int offset;
916 int nottyped;
917 int silent;
919 char_u *s1, *s2;
920 int newlen;
921 int addlen;
922 int i;
923 int newoff;
924 int val;
925 int nrm;
927 init_typebuf();
928 if (++typebuf.tb_change_cnt == 0)
929 typebuf.tb_change_cnt = 1;
931 addlen = (int)STRLEN(str);
934 * Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
936 if (offset == 0 && addlen <= typebuf.tb_off)
938 typebuf.tb_off -= addlen;
939 mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
943 * Need to allocate a new buffer.
944 * In typebuf.tb_buf there must always be room for 3 * MAXMAPLEN + 4
945 * characters. We add some extra room to avoid having to allocate too
946 * often.
948 else
950 newoff = MAXMAPLEN + 4;
951 newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4);
952 if (newlen < 0) /* string is getting too long */
954 EMSG(_(e_toocompl)); /* also calls flush_buffers */
955 setcursor();
956 return FAIL;
958 s1 = alloc(newlen);
959 if (s1 == NULL) /* out of memory */
960 return FAIL;
961 s2 = alloc(newlen);
962 if (s2 == NULL) /* out of memory */
964 vim_free(s1);
965 return FAIL;
967 typebuf.tb_buflen = newlen;
969 /* copy the old chars, before the insertion point */
970 mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off,
971 (size_t)offset);
972 /* copy the new chars */
973 mch_memmove(s1 + newoff + offset, str, (size_t)addlen);
974 /* copy the old chars, after the insertion point, including the NUL at
975 * the end */
976 mch_memmove(s1 + newoff + offset + addlen,
977 typebuf.tb_buf + typebuf.tb_off + offset,
978 (size_t)(typebuf.tb_len - offset + 1));
979 if (typebuf.tb_buf != typebuf_init)
980 vim_free(typebuf.tb_buf);
981 typebuf.tb_buf = s1;
983 mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
984 (size_t)offset);
985 mch_memmove(s2 + newoff + offset + addlen,
986 typebuf.tb_noremap + typebuf.tb_off + offset,
987 (size_t)(typebuf.tb_len - offset));
988 if (typebuf.tb_noremap != noremapbuf_init)
989 vim_free(typebuf.tb_noremap);
990 typebuf.tb_noremap = s2;
992 typebuf.tb_off = newoff;
994 typebuf.tb_len += addlen;
996 /* If noremap == REMAP_SCRIPT: do remap script-local mappings. */
997 if (noremap == REMAP_SCRIPT)
998 val = RM_SCRIPT;
999 else if (noremap == REMAP_SKIP)
1000 val = RM_ABBR;
1001 else
1002 val = RM_NONE;
1005 * Adjust typebuf.tb_noremap[] for the new characters:
1006 * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
1007 * (sometimes) not remappable
1008 * If noremap == REMAP_YES: all the new characters are mappable
1009 * If noremap > 0: "noremap" characters are not remappable, the rest
1010 * mappable
1012 if (noremap == REMAP_SKIP)
1013 nrm = 1;
1014 else if (noremap < 0)
1015 nrm = addlen;
1016 else
1017 nrm = noremap;
1018 for (i = 0; i < addlen; ++i)
1019 typebuf.tb_noremap[typebuf.tb_off + i + offset] =
1020 (--nrm >= 0) ? val : RM_YES;
1022 /* tb_maplen and tb_silent only remember the length of mapped and/or
1023 * silent mappings at the start of the buffer, assuming that a mapped
1024 * sequence doesn't result in typed characters. */
1025 if (nottyped || typebuf.tb_maplen > offset)
1026 typebuf.tb_maplen += addlen;
1027 if (silent || typebuf.tb_silent > offset)
1029 typebuf.tb_silent += addlen;
1030 cmd_silent = TRUE;
1032 if (typebuf.tb_no_abbr_cnt && offset == 0) /* and not used for abbrev.s */
1033 typebuf.tb_no_abbr_cnt += addlen;
1035 return OK;
1039 * Put character "c" back into the typeahead buffer.
1040 * Can be used for a character obtained by vgetc() that needs to be put back.
1041 * Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to
1042 * the char.
1044 void
1045 ins_char_typebuf(c)
1046 int c;
1048 #ifdef FEAT_MBYTE
1049 char_u buf[MB_MAXBYTES];
1050 #else
1051 char_u buf[4];
1052 #endif
1053 if (IS_SPECIAL(c))
1055 buf[0] = K_SPECIAL;
1056 buf[1] = K_SECOND(c);
1057 buf[2] = K_THIRD(c);
1058 buf[3] = NUL;
1060 else
1062 #ifdef FEAT_MBYTE
1063 buf[(*mb_char2bytes)(c, buf)] = NUL;
1064 #else
1065 buf[0] = c;
1066 buf[1] = NUL;
1067 #endif
1069 (void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
1073 * Return TRUE if the typeahead buffer was changed (while waiting for a
1074 * character to arrive). Happens when a message was received from a client or
1075 * from feedkeys().
1076 * But check in a more generic way to avoid trouble: When "typebuf.tb_buf"
1077 * changed it was reallocated and the old pointer can no longer be used.
1078 * Or "typebuf.tb_off" may have been changed and we would overwrite characters
1079 * that was just added.
1082 typebuf_changed(tb_change_cnt)
1083 int tb_change_cnt; /* old value of typebuf.tb_change_cnt */
1085 return (tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt
1086 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1087 || typebuf_was_filled
1088 #endif
1093 * Return TRUE if there are no characters in the typeahead buffer that have
1094 * not been typed (result from a mapping or come from ":normal").
1097 typebuf_typed()
1099 return typebuf.tb_maplen == 0;
1102 #if defined(FEAT_VISUAL) || defined(PROTO)
1104 * Return the number of characters that are mapped (or not typed).
1107 typebuf_maplen()
1109 return typebuf.tb_maplen;
1111 #endif
1114 * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
1116 void
1117 del_typebuf(len, offset)
1118 int len;
1119 int offset;
1121 int i;
1123 if (len == 0)
1124 return; /* nothing to do */
1126 typebuf.tb_len -= len;
1129 * Easy case: Just increase typebuf.tb_off.
1131 if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
1132 >= 3 * MAXMAPLEN + 3)
1133 typebuf.tb_off += len;
1135 * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
1137 else
1139 i = typebuf.tb_off + offset;
1141 * Leave some extra room at the end to avoid reallocation.
1143 if (typebuf.tb_off > MAXMAPLEN)
1145 mch_memmove(typebuf.tb_buf + MAXMAPLEN,
1146 typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
1147 mch_memmove(typebuf.tb_noremap + MAXMAPLEN,
1148 typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
1149 typebuf.tb_off = MAXMAPLEN;
1151 /* adjust typebuf.tb_buf (include the NUL at the end) */
1152 mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset,
1153 typebuf.tb_buf + i + len,
1154 (size_t)(typebuf.tb_len - offset + 1));
1155 /* adjust typebuf.tb_noremap[] */
1156 mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
1157 typebuf.tb_noremap + i + len,
1158 (size_t)(typebuf.tb_len - offset));
1161 if (typebuf.tb_maplen > offset) /* adjust tb_maplen */
1163 if (typebuf.tb_maplen < offset + len)
1164 typebuf.tb_maplen = offset;
1165 else
1166 typebuf.tb_maplen -= len;
1168 if (typebuf.tb_silent > offset) /* adjust tb_silent */
1170 if (typebuf.tb_silent < offset + len)
1171 typebuf.tb_silent = offset;
1172 else
1173 typebuf.tb_silent -= len;
1175 if (typebuf.tb_no_abbr_cnt > offset) /* adjust tb_no_abbr_cnt */
1177 if (typebuf.tb_no_abbr_cnt < offset + len)
1178 typebuf.tb_no_abbr_cnt = offset;
1179 else
1180 typebuf.tb_no_abbr_cnt -= len;
1183 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1184 /* Reset the flag that text received from a client or from feedkeys()
1185 * was inserted in the typeahead buffer. */
1186 typebuf_was_filled = FALSE;
1187 #endif
1188 if (++typebuf.tb_change_cnt == 0)
1189 typebuf.tb_change_cnt = 1;
1193 * Write typed characters to script file.
1194 * If recording is on put the character in the recordbuffer.
1196 static void
1197 gotchars(chars, len)
1198 char_u *chars;
1199 int len;
1201 char_u *s = chars;
1202 int c;
1203 char_u buf[2];
1204 int todo = len;
1206 /* remember how many chars were last recorded */
1207 if (Recording)
1208 last_recorded_len += len;
1210 buf[1] = NUL;
1211 while (todo--)
1213 /* Handle one byte at a time; no translation to be done. */
1214 c = *s++;
1215 updatescript(c);
1217 if (Recording)
1219 buf[0] = c;
1220 add_buff(&recordbuff, buf, 1L);
1223 may_sync_undo();
1225 #ifdef FEAT_EVAL
1226 /* output "debug mode" message next time in debug mode */
1227 debug_did_msg = FALSE;
1228 #endif
1230 /* Since characters have been typed, consider the following to be in
1231 * another mapping. Search string will be kept in history. */
1232 ++maptick;
1236 * Sync undo. Called when typed characters are obtained from the typeahead
1237 * buffer, or when a menu is used.
1238 * Do not sync:
1239 * - In Insert mode, unless cursor key has been used.
1240 * - While reading a script file.
1241 * - When no_u_sync is non-zero.
1243 static void
1244 may_sync_undo()
1246 if ((!(State & (INSERT + CMDLINE)) || arrow_used)
1247 && scriptin[curscript] == NULL)
1248 u_sync(FALSE);
1252 * Make "typebuf" empty and allocate new buffers.
1253 * Returns FAIL when out of memory.
1256 alloc_typebuf()
1258 typebuf.tb_buf = alloc(TYPELEN_INIT);
1259 typebuf.tb_noremap = alloc(TYPELEN_INIT);
1260 if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL)
1262 free_typebuf();
1263 return FAIL;
1265 typebuf.tb_buflen = TYPELEN_INIT;
1266 typebuf.tb_off = 0;
1267 typebuf.tb_len = 0;
1268 typebuf.tb_maplen = 0;
1269 typebuf.tb_silent = 0;
1270 typebuf.tb_no_abbr_cnt = 0;
1271 if (++typebuf.tb_change_cnt == 0)
1272 typebuf.tb_change_cnt = 1;
1273 return OK;
1277 * Free the buffers of "typebuf".
1279 void
1280 free_typebuf()
1282 if (typebuf.tb_buf == typebuf_init)
1283 EMSG2(_(e_intern2), "Free typebuf 1");
1284 else
1285 vim_free(typebuf.tb_buf);
1286 if (typebuf.tb_noremap == noremapbuf_init)
1287 EMSG2(_(e_intern2), "Free typebuf 2");
1288 else
1289 vim_free(typebuf.tb_noremap);
1293 * When doing ":so! file", the current typeahead needs to be saved, and
1294 * restored when "file" has been read completely.
1296 static typebuf_T saved_typebuf[NSCRIPT];
1299 save_typebuf()
1301 init_typebuf();
1302 saved_typebuf[curscript] = typebuf;
1303 /* If out of memory: restore typebuf and close file. */
1304 if (alloc_typebuf() == FAIL)
1306 closescript();
1307 return FAIL;
1309 return OK;
1312 static int old_char = -1; /* character put back by vungetc() */
1313 static int old_mod_mask; /* mod_mask for ungotten character */
1315 #if defined(FEAT_EVAL) || defined(FEAT_EX_EXTRA) || defined(PROTO)
1318 * Save all three kinds of typeahead, so that the user must type at a prompt.
1320 void
1321 save_typeahead(tp)
1322 tasave_T *tp;
1324 tp->save_typebuf = typebuf;
1325 tp->typebuf_valid = (alloc_typebuf() == OK);
1326 if (!tp->typebuf_valid)
1327 typebuf = tp->save_typebuf;
1329 tp->old_char = old_char;
1330 tp->old_mod_mask = old_mod_mask;
1331 old_char = -1;
1333 tp->save_stuffbuff = stuffbuff;
1334 stuffbuff.bh_first.b_next = NULL;
1335 # ifdef USE_INPUT_BUF
1336 tp->save_inputbuf = get_input_buf();
1337 # endif
1341 * Restore the typeahead to what it was before calling save_typeahead().
1342 * The allocated memory is freed, can only be called once!
1344 void
1345 restore_typeahead(tp)
1346 tasave_T *tp;
1348 if (tp->typebuf_valid)
1350 free_typebuf();
1351 typebuf = tp->save_typebuf;
1354 old_char = tp->old_char;
1355 old_mod_mask = tp->old_mod_mask;
1357 free_buff(&stuffbuff);
1358 stuffbuff = tp->save_stuffbuff;
1359 # ifdef USE_INPUT_BUF
1360 set_input_buf(tp->save_inputbuf);
1361 # endif
1363 #endif
1366 * Open a new script file for the ":source!" command.
1368 void
1369 openscript(name, directly)
1370 char_u *name;
1371 int directly; /* when TRUE execute directly */
1373 if (curscript + 1 == NSCRIPT)
1375 EMSG(_(e_nesting));
1376 return;
1378 #ifdef FEAT_EVAL
1379 if (ignore_script)
1380 /* Not reading from script, also don't open one. Warning message? */
1381 return;
1382 #endif
1384 if (scriptin[curscript] != NULL) /* already reading script */
1385 ++curscript;
1386 /* use NameBuff for expanded name */
1387 expand_env(name, NameBuff, MAXPATHL);
1388 if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
1390 EMSG2(_(e_notopen), name);
1391 if (curscript)
1392 --curscript;
1393 return;
1395 if (save_typebuf() == FAIL)
1396 return;
1399 * Execute the commands from the file right now when using ":source!"
1400 * after ":global" or ":argdo" or in a loop. Also when another command
1401 * follows. This means the display won't be updated. Don't do this
1402 * always, "make test" would fail.
1404 if (directly)
1406 oparg_T oa;
1407 int oldcurscript;
1408 int save_State = State;
1409 int save_restart_edit = restart_edit;
1410 int save_insertmode = p_im;
1411 int save_finish_op = finish_op;
1412 int save_msg_scroll = msg_scroll;
1414 State = NORMAL;
1415 msg_scroll = FALSE; /* no msg scrolling in Normal mode */
1416 restart_edit = 0; /* don't go to Insert mode */
1417 p_im = FALSE; /* don't use 'insertmode' */
1418 clear_oparg(&oa);
1419 finish_op = FALSE;
1421 oldcurscript = curscript;
1424 update_topline_cursor(); /* update cursor position and topline */
1425 normal_cmd(&oa, FALSE); /* execute one command */
1426 vpeekc(); /* check for end of file */
1428 while (scriptin[oldcurscript] != NULL);
1430 State = save_State;
1431 msg_scroll = save_msg_scroll;
1432 restart_edit = save_restart_edit;
1433 p_im = save_insertmode;
1434 finish_op = save_finish_op;
1439 * Close the currently active input script.
1441 static void
1442 closescript()
1444 free_typebuf();
1445 typebuf = saved_typebuf[curscript];
1447 fclose(scriptin[curscript]);
1448 scriptin[curscript] = NULL;
1449 if (curscript > 0)
1450 --curscript;
1453 #if defined(EXITFREE) || defined(PROTO)
1454 void
1455 close_all_scripts()
1457 while (scriptin[0] != NULL)
1458 closescript();
1460 #endif
1462 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1464 * Return TRUE when reading keys from a script file.
1467 using_script()
1469 return scriptin[curscript] != NULL;
1471 #endif
1474 * This function is called just before doing a blocking wait. Thus after
1475 * waiting 'updatetime' for a character to arrive.
1477 void
1478 before_blocking()
1480 updatescript(0);
1481 #ifdef FEAT_EVAL
1482 if (may_garbage_collect)
1483 garbage_collect();
1484 #endif
1488 * updatescipt() is called when a character can be written into the script file
1489 * or when we have waited some time for a character (c == 0)
1491 * All the changed memfiles are synced if c == 0 or when the number of typed
1492 * characters reaches 'updatecount' and 'updatecount' is non-zero.
1494 void
1495 updatescript(c)
1496 int c;
1498 static int count = 0;
1500 if (c && scriptout)
1501 putc(c, scriptout);
1502 if (c == 0 || (p_uc > 0 && ++count >= p_uc))
1504 ml_sync_all(c == 0, TRUE);
1505 count = 0;
1509 #define KL_PART_KEY -1 /* keylen value for incomplete key-code */
1510 #define KL_PART_MAP -2 /* keylen value for incomplete mapping */
1513 * Get the next input character.
1514 * Can return a special key or a multi-byte character.
1515 * Can return NUL when called recursively, use safe_vgetc() if that's not
1516 * wanted.
1517 * This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
1518 * Collects the bytes of a multibyte character into the whole character.
1519 * Returns the modifiers in the global "mod_mask".
1522 vgetc()
1524 int c, c2;
1525 #ifdef FEAT_MBYTE
1526 int n;
1527 char_u buf[MB_MAXBYTES];
1528 int i;
1529 #endif
1531 #ifdef FEAT_EVAL
1532 /* Do garbage collection when garbagecollect() was called previously and
1533 * we are now at the toplevel. */
1534 if (may_garbage_collect && want_garbage_collect)
1535 garbage_collect();
1536 #endif
1539 * If a character was put back with vungetc, it was already processed.
1540 * Return it directly.
1542 if (old_char != -1)
1544 c = old_char;
1545 old_char = -1;
1546 mod_mask = old_mod_mask;
1548 else
1550 mod_mask = 0x0;
1551 last_recorded_len = 0;
1552 for (;;) /* this is done twice if there are modifiers */
1554 if (mod_mask) /* no mapping after modifier has been read */
1556 ++no_mapping;
1557 ++allow_keys;
1559 c = vgetorpeek(TRUE);
1560 if (mod_mask)
1562 --no_mapping;
1563 --allow_keys;
1566 /* Get two extra bytes for special keys */
1567 if (c == K_SPECIAL
1568 #ifdef FEAT_GUI
1569 || c == CSI
1570 #endif
1573 int save_allow_keys = allow_keys;
1575 ++no_mapping;
1576 allow_keys = 0; /* make sure BS is not found */
1577 c2 = vgetorpeek(TRUE); /* no mapping for these chars */
1578 c = vgetorpeek(TRUE);
1579 --no_mapping;
1580 allow_keys = save_allow_keys;
1581 if (c2 == KS_MODIFIER)
1583 mod_mask = c;
1584 continue;
1586 c = TO_SPECIAL(c2, c);
1588 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
1589 /* Handle K_TEAROFF here, the caller of vgetc() doesn't need to
1590 * know that a menu was torn off */
1591 if (c == K_TEAROFF)
1593 char_u name[200];
1594 int i;
1596 /* get menu path, it ends with a <CR> */
1597 for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; )
1599 name[i] = c;
1600 if (i < 199)
1601 ++i;
1603 name[i] = NUL;
1604 gui_make_tearoff(name);
1605 continue;
1607 #endif
1608 #if defined(FEAT_GUI) && defined(HAVE_GTK2) && defined(FEAT_MENU)
1609 /* GTK: <F10> normally selects the menu, but it's passed until
1610 * here to allow mapping it. Intercept and invoke the GTK
1611 * behavior if it's not mapped. */
1612 if (c == K_F10 && gui.menubar != NULL)
1614 gtk_menu_shell_select_first(GTK_MENU_SHELL(gui.menubar), FALSE);
1615 continue;
1617 #endif
1618 #ifdef FEAT_GUI
1619 /* Handle focus event here, so that the caller doesn't need to
1620 * know about it. Return K_IGNORE so that we loop once (needed if
1621 * 'lazyredraw' is set). */
1622 if (c == K_FOCUSGAINED || c == K_FOCUSLOST)
1624 ui_focus_change(c == K_FOCUSGAINED);
1625 c = K_IGNORE;
1628 /* Handle redraw event here, this is used by CodeCheck.*/
1629 if (c == K_REDRAW) {
1630 /* gui_update_screen() does not work because of
1631 * update_screen(0) inside it. */
1632 update_topline();
1633 validate_cursor();
1634 update_screen(SOME_VALID);
1635 setcursor();
1636 cursor_on();
1637 out_flush();
1639 c = K_IGNORE;
1642 /* Translate K_CSI to CSI. The special key is only used to avoid
1643 * it being recognized as the start of a special key. */
1644 if (c == K_CSI)
1645 c = CSI;
1646 #endif
1648 #ifdef MSDOS
1650 * If K_NUL was typed, it is replaced by K_NUL, 3 in mch_inchar().
1651 * Delete the 3 here.
1653 else if (c == K_NUL && vpeekc() == 3)
1654 (void)vgetorpeek(TRUE);
1655 #endif
1657 /* a keypad or special function key was not mapped, use it like
1658 * its ASCII equivalent */
1659 switch (c)
1661 case K_KPLUS: c = '+'; break;
1662 case K_KMINUS: c = '-'; break;
1663 case K_KDIVIDE: c = '/'; break;
1664 case K_KMULTIPLY: c = '*'; break;
1665 case K_KENTER: c = CAR; break;
1666 case K_KPOINT:
1667 #ifdef WIN32
1668 /* Can be either '.' or a ',', *
1669 * depending on the type of keypad. */
1670 c = MapVirtualKey(VK_DECIMAL, 2); break;
1671 #else
1672 c = '.'; break;
1673 #endif
1674 case K_K0: c = '0'; break;
1675 case K_K1: c = '1'; break;
1676 case K_K2: c = '2'; break;
1677 case K_K3: c = '3'; break;
1678 case K_K4: c = '4'; break;
1679 case K_K5: c = '5'; break;
1680 case K_K6: c = '6'; break;
1681 case K_K7: c = '7'; break;
1682 case K_K8: c = '8'; break;
1683 case K_K9: c = '9'; break;
1685 case K_XHOME:
1686 case K_ZHOME: if (mod_mask == MOD_MASK_SHIFT)
1688 c = K_S_HOME;
1689 mod_mask = 0;
1691 else if (mod_mask == MOD_MASK_CTRL)
1693 c = K_C_HOME;
1694 mod_mask = 0;
1696 else
1697 c = K_HOME;
1698 break;
1699 case K_XEND:
1700 case K_ZEND: if (mod_mask == MOD_MASK_SHIFT)
1702 c = K_S_END;
1703 mod_mask = 0;
1705 else if (mod_mask == MOD_MASK_CTRL)
1707 c = K_C_END;
1708 mod_mask = 0;
1710 else
1711 c = K_END;
1712 break;
1714 case K_XUP: c = K_UP; break;
1715 case K_XDOWN: c = K_DOWN; break;
1716 case K_XLEFT: c = K_LEFT; break;
1717 case K_XRIGHT: c = K_RIGHT; break;
1720 #ifdef FEAT_MBYTE
1721 /* For a multi-byte character get all the bytes and return the
1722 * converted character.
1723 * Note: This will loop until enough bytes are received!
1725 if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1)
1727 ++no_mapping;
1728 buf[0] = c;
1729 for (i = 1; i < n; ++i)
1731 buf[i] = vgetorpeek(TRUE);
1732 if (buf[i] == K_SPECIAL
1733 #ifdef FEAT_GUI
1734 || buf[i] == CSI
1735 #endif
1738 /* Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence,
1739 * which represents a K_SPECIAL (0x80),
1740 * or a CSI - KS_EXTRA - KE_CSI sequence, which represents
1741 * a CSI (0x9B),
1742 * of a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI too. */
1743 c = vgetorpeek(TRUE);
1744 if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA)
1745 buf[i] = CSI;
1748 --no_mapping;
1749 c = (*mb_ptr2char)(buf);
1751 #endif
1753 break;
1757 #ifdef FEAT_EVAL
1759 * In the main loop "may_garbage_collect" can be set to do garbage
1760 * collection in the first next vgetc(). It's disabled after that to
1761 * avoid internally used Lists and Dicts to be freed.
1763 may_garbage_collect = FALSE;
1764 #endif
1766 return c;
1770 * Like vgetc(), but never return a NUL when called recursively, get a key
1771 * directly from the user (ignoring typeahead).
1774 safe_vgetc()
1776 int c;
1778 c = vgetc();
1779 if (c == NUL)
1780 c = get_keystroke();
1781 return c;
1785 * Like safe_vgetc(), but loop to handle K_IGNORE.
1786 * Also ignore scrollbar events.
1789 plain_vgetc()
1791 int c;
1795 c = safe_vgetc();
1796 } while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
1797 return c;
1801 * Check if a character is available, such that vgetc() will not block.
1802 * If the next character is a special character or multi-byte, the returned
1803 * character is not valid!.
1806 vpeekc()
1808 if (old_char != -1)
1809 return old_char;
1810 return vgetorpeek(FALSE);
1813 #if defined(FEAT_TERMRESPONSE) || defined(PROTO)
1815 * Like vpeekc(), but don't allow mapping. Do allow checking for terminal
1816 * codes.
1819 vpeekc_nomap()
1821 int c;
1823 ++no_mapping;
1824 ++allow_keys;
1825 c = vpeekc();
1826 --no_mapping;
1827 --allow_keys;
1828 return c;
1830 #endif
1832 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1834 * Check if any character is available, also half an escape sequence.
1835 * Trick: when no typeahead found, but there is something in the typeahead
1836 * buffer, it must be an ESC that is recognized as the start of a key code.
1839 vpeekc_any()
1841 int c;
1843 c = vpeekc();
1844 if (c == NUL && typebuf.tb_len > 0)
1845 c = ESC;
1846 return c;
1848 #endif
1851 * Call vpeekc() without causing anything to be mapped.
1852 * Return TRUE if a character is available, FALSE otherwise.
1855 char_avail()
1857 int retval;
1859 ++no_mapping;
1860 retval = vpeekc();
1861 --no_mapping;
1862 return (retval != NUL);
1865 void
1866 vungetc(c) /* unget one character (can only be done once!) */
1867 int c;
1869 old_char = c;
1870 old_mod_mask = mod_mask;
1874 * get a character:
1875 * 1. from the stuffbuffer
1876 * This is used for abbreviated commands like "D" -> "d$".
1877 * Also used to redo a command for ".".
1878 * 2. from the typeahead buffer
1879 * Stores text obtained previously but not used yet.
1880 * Also stores the result of mappings.
1881 * Also used for the ":normal" command.
1882 * 3. from the user
1883 * This may do a blocking wait if "advance" is TRUE.
1885 * if "advance" is TRUE (vgetc()):
1886 * really get the character.
1887 * KeyTyped is set to TRUE in the case the user typed the key.
1888 * KeyStuffed is TRUE if the character comes from the stuff buffer.
1889 * if "advance" is FALSE (vpeekc()):
1890 * just look whether there is a character available.
1892 * When "no_mapping" is zero, checks for mappings in the current mode.
1893 * Only returns one byte (of a multi-byte character).
1894 * K_SPECIAL and CSI may be escaped, need to get two more bytes then.
1896 static int
1897 vgetorpeek(advance)
1898 int advance;
1900 int c, c1;
1901 int keylen;
1902 char_u *s;
1903 mapblock_T *mp;
1904 #ifdef FEAT_LOCALMAP
1905 mapblock_T *mp2;
1906 #endif
1907 mapblock_T *mp_match;
1908 int mp_match_len = 0;
1909 int timedout = FALSE; /* waited for more than 1 second
1910 for mapping to complete */
1911 int mapdepth = 0; /* check for recursive mapping */
1912 int mode_deleted = FALSE; /* set when mode has been deleted */
1913 int local_State;
1914 int mlen;
1915 int max_mlen;
1916 int i;
1917 #ifdef FEAT_CMDL_INFO
1918 int new_wcol, new_wrow;
1919 #endif
1920 #ifdef FEAT_GUI
1921 # ifdef FEAT_MENU
1922 int idx;
1923 # endif
1924 int shape_changed = FALSE; /* adjusted cursor shape */
1925 #endif
1926 int n;
1927 #ifdef FEAT_LANGMAP
1928 int nolmaplen;
1929 #endif
1930 int old_wcol, old_wrow;
1931 int wait_tb_len;
1934 * This function doesn't work very well when called recursively. This may
1935 * happen though, because of:
1936 * 1. The call to add_to_showcmd(). char_avail() is then used to check if
1937 * there is a character available, which calls this function. In that
1938 * case we must return NUL, to indicate no character is available.
1939 * 2. A GUI callback function writes to the screen, causing a
1940 * wait_return().
1941 * Using ":normal" can also do this, but it saves the typeahead buffer,
1942 * thus it should be OK. But don't get a key from the user then.
1944 if (vgetc_busy > 0
1945 #ifdef FEAT_EX_EXTRA
1946 && ex_normal_busy == 0
1947 #endif
1949 return NUL;
1951 local_State = get_real_state();
1953 ++vgetc_busy;
1955 if (advance)
1956 KeyStuffed = FALSE;
1958 init_typebuf();
1959 start_stuff();
1960 if (advance && typebuf.tb_maplen == 0)
1961 Exec_reg = FALSE;
1965 * get a character: 1. from the stuffbuffer
1967 if (typeahead_char != 0)
1969 c = typeahead_char;
1970 if (advance)
1971 typeahead_char = 0;
1973 else
1974 c = read_stuff(advance);
1975 if (c != NUL && !got_int)
1977 if (advance)
1979 /* KeyTyped = FALSE; When the command that stuffed something
1980 * was typed, behave like the stuffed command was typed.
1981 * needed for CTRL-W CTRl-] to open a fold, for example. */
1982 KeyStuffed = TRUE;
1984 if (typebuf.tb_no_abbr_cnt == 0)
1985 typebuf.tb_no_abbr_cnt = 1; /* no abbreviations now */
1987 else
1990 * Loop until we either find a matching mapped key, or we
1991 * are sure that it is not a mapped key.
1992 * If a mapped key sequence is found we go back to the start to
1993 * try re-mapping.
1995 for (;;)
1998 * ui_breakcheck() is slow, don't use it too often when
1999 * inside a mapping. But call it each time for typed
2000 * characters.
2002 if (typebuf.tb_maplen)
2003 line_breakcheck();
2004 else
2005 ui_breakcheck(); /* check for CTRL-C */
2006 keylen = 0;
2007 if (got_int)
2009 /* flush all input */
2010 c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L,
2011 typebuf.tb_change_cnt);
2013 * If inchar() returns TRUE (script file was active) or we
2014 * are inside a mapping, get out of insert mode.
2015 * Otherwise we behave like having gotten a CTRL-C.
2016 * As a result typing CTRL-C in insert mode will
2017 * really insert a CTRL-C.
2019 if ((c || typebuf.tb_maplen)
2020 && (State & (INSERT + CMDLINE)))
2021 c = ESC;
2022 else
2023 c = Ctrl_C;
2024 flush_buffers(TRUE); /* flush all typeahead */
2026 if (advance)
2028 /* Also record this character, it might be needed to
2029 * get out of Insert mode. */
2030 *typebuf.tb_buf = c;
2031 gotchars(typebuf.tb_buf, 1);
2033 cmd_silent = FALSE;
2035 break;
2037 else if (typebuf.tb_len > 0)
2040 * Check for a mappable key sequence.
2041 * Walk through one maphash[] list until we find an
2042 * entry that matches.
2044 * Don't look for mappings if:
2045 * - no_mapping set: mapping disabled (e.g. for CTRL-V)
2046 * - maphash_valid not set: no mappings present.
2047 * - typebuf.tb_buf[typebuf.tb_off] should not be remapped
2048 * - in insert or cmdline mode and 'paste' option set
2049 * - waiting for "hit return to continue" and CR or SPACE
2050 * typed
2051 * - waiting for a char with --more--
2052 * - in Ctrl-X mode, and we get a valid char for that mode
2054 mp = NULL;
2055 max_mlen = 0;
2056 c1 = typebuf.tb_buf[typebuf.tb_off];
2057 if (no_mapping == 0 && maphash_valid
2058 && (no_zero_mapping == 0 || c1 != '0')
2059 && (typebuf.tb_maplen == 0
2060 || (p_remap
2061 && (typebuf.tb_noremap[typebuf.tb_off]
2062 & (RM_NONE|RM_ABBR)) == 0))
2063 && !(p_paste && (State & (INSERT + CMDLINE)))
2064 && !(State == HITRETURN && (c1 == CAR || c1 == ' '))
2065 && State != ASKMORE
2066 && State != CONFIRM
2067 #ifdef FEAT_INS_EXPAND
2068 && !((ctrl_x_mode != 0 && vim_is_ctrl_x_key(c1))
2069 || ((compl_cont_status & CONT_LOCAL)
2070 && (c1 == Ctrl_N || c1 == Ctrl_P)))
2071 #endif
2074 #ifdef FEAT_LANGMAP
2075 if (c1 == K_SPECIAL)
2076 nolmaplen = 2;
2077 else
2079 LANGMAP_ADJUST(c1, TRUE);
2080 nolmaplen = 0;
2082 #endif
2083 #ifdef FEAT_LOCALMAP
2084 /* First try buffer-local mappings. */
2085 mp = curbuf->b_maphash[MAP_HASH(local_State, c1)];
2086 mp2 = maphash[MAP_HASH(local_State, c1)];
2087 if (mp == NULL)
2089 mp = mp2;
2090 mp2 = NULL;
2092 #else
2093 mp = maphash[MAP_HASH(local_State, c1)];
2094 #endif
2096 * Loop until a partly matching mapping is found or
2097 * all (local) mappings have been checked.
2098 * The longest full match is remembered in "mp_match".
2099 * A full match is only accepted if there is no partly
2100 * match, so "aa" and "aaa" can both be mapped.
2102 mp_match = NULL;
2103 mp_match_len = 0;
2104 for ( ; mp != NULL;
2105 #ifdef FEAT_LOCALMAP
2106 mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
2107 #endif
2108 (mp = mp->m_next))
2111 * Only consider an entry if the first character
2112 * matches and it is for the current state.
2113 * Skip ":lmap" mappings if keys were mapped.
2115 if (mp->m_keys[0] == c1
2116 && (mp->m_mode & local_State)
2117 && ((mp->m_mode & LANGMAP) == 0
2118 || typebuf.tb_maplen == 0))
2120 #ifdef FEAT_LANGMAP
2121 int nomap = nolmaplen;
2122 int c2;
2123 #endif
2124 /* find the match length of this mapping */
2125 for (mlen = 1; mlen < typebuf.tb_len; ++mlen)
2127 #ifdef FEAT_LANGMAP
2128 c2 = typebuf.tb_buf[typebuf.tb_off + mlen];
2129 if (nomap > 0)
2130 --nomap;
2131 else if (c2 == K_SPECIAL)
2132 nomap = 2;
2133 else
2134 LANGMAP_ADJUST(c2, TRUE);
2135 if (mp->m_keys[mlen] != c2)
2136 #else
2137 if (mp->m_keys[mlen] !=
2138 typebuf.tb_buf[typebuf.tb_off + mlen])
2139 #endif
2140 break;
2143 #ifdef FEAT_MBYTE
2144 /* Don't allow mapping the first byte(s) of a
2145 * multi-byte char. Happens when mapping
2146 * <M-a> and then changing 'encoding'. */
2147 if (has_mbyte && MB_BYTE2LEN(c1)
2148 > (*mb_ptr2len)(mp->m_keys))
2149 mlen = 0;
2150 #endif
2152 * Check an entry whether it matches.
2153 * - Full match: mlen == keylen
2154 * - Partly match: mlen == typebuf.tb_len
2156 keylen = mp->m_keylen;
2157 if (mlen == keylen
2158 || (mlen == typebuf.tb_len
2159 && typebuf.tb_len < keylen))
2162 * If only script-local mappings are
2163 * allowed, check if the mapping starts
2164 * with K_SNR.
2166 s = typebuf.tb_noremap + typebuf.tb_off;
2167 if (*s == RM_SCRIPT
2168 && (mp->m_keys[0] != K_SPECIAL
2169 || mp->m_keys[1] != KS_EXTRA
2170 || mp->m_keys[2]
2171 != (int)KE_SNR))
2172 continue;
2174 * If one of the typed keys cannot be
2175 * remapped, skip the entry.
2177 for (n = mlen; --n >= 0; )
2178 if (*s++ & (RM_NONE|RM_ABBR))
2179 break;
2180 if (n >= 0)
2181 continue;
2183 if (keylen > typebuf.tb_len)
2185 if (!timedout)
2187 /* break at a partly match */
2188 keylen = KL_PART_MAP;
2189 break;
2192 else if (keylen > mp_match_len)
2194 /* found a longer match */
2195 mp_match = mp;
2196 mp_match_len = keylen;
2199 else
2200 /* No match; may have to check for
2201 * termcode at next character. */
2202 if (max_mlen < mlen)
2203 max_mlen = mlen;
2207 /* If no partly match found, use the longest full
2208 * match. */
2209 if (keylen != KL_PART_MAP)
2211 mp = mp_match;
2212 keylen = mp_match_len;
2216 /* Check for match with 'pastetoggle' */
2217 if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL)))
2219 for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen];
2220 ++mlen)
2221 if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off
2222 + mlen])
2223 break;
2224 if (p_pt[mlen] == NUL) /* match */
2226 /* write chars to script file(s) */
2227 if (mlen > typebuf.tb_maplen)
2228 gotchars(typebuf.tb_buf + typebuf.tb_off
2229 + typebuf.tb_maplen,
2230 mlen - typebuf.tb_maplen);
2232 del_typebuf(mlen, 0); /* remove the chars */
2233 set_option_value((char_u *)"paste",
2234 (long)!p_paste, NULL, 0);
2235 if (!(State & INSERT))
2237 msg_col = 0;
2238 msg_row = Rows - 1;
2239 msg_clr_eos(); /* clear ruler */
2241 showmode();
2242 setcursor();
2243 continue;
2245 /* Need more chars for partly match. */
2246 if (mlen == typebuf.tb_len)
2247 keylen = KL_PART_KEY;
2248 else if (max_mlen < mlen)
2249 /* no match, may have to check for termcode at
2250 * next character */
2251 max_mlen = mlen + 1;
2254 if ((mp == NULL || max_mlen >= mp_match_len)
2255 && keylen != KL_PART_MAP)
2257 int save_keylen = keylen;
2260 * When no matching mapping found or found a
2261 * non-matching mapping that matches at least what the
2262 * matching mapping matched:
2263 * Check if we have a terminal code, when:
2264 * mapping is allowed,
2265 * keys have not been mapped,
2266 * and not an ESC sequence, not in insert mode or
2267 * p_ek is on,
2268 * and when not timed out,
2270 if ((no_mapping == 0 || allow_keys != 0)
2271 && (typebuf.tb_maplen == 0
2272 || (p_remap && typebuf.tb_noremap[
2273 typebuf.tb_off] == RM_YES))
2274 && !timedout)
2276 keylen = check_termcode(max_mlen + 1, NULL, 0);
2278 /* If no termcode matched but 'pastetoggle'
2279 * matched partially it's like an incomplete key
2280 * sequence. */
2281 if (keylen == 0 && save_keylen == KL_PART_KEY)
2282 keylen = KL_PART_KEY;
2285 * When getting a partial match, but the last
2286 * characters were not typed, don't wait for a
2287 * typed character to complete the termcode.
2288 * This helps a lot when a ":normal" command ends
2289 * in an ESC.
2291 if (keylen < 0
2292 && typebuf.tb_len == typebuf.tb_maplen)
2293 keylen = 0;
2295 else
2296 keylen = 0;
2297 if (keylen == 0) /* no matching terminal code */
2299 #ifdef AMIGA /* check for window bounds report */
2300 if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[
2301 typebuf.tb_off] & 0xff) == CSI)
2303 for (s = typebuf.tb_buf + typebuf.tb_off + 1;
2304 s < typebuf.tb_buf + typebuf.tb_off
2305 + typebuf.tb_len
2306 && (VIM_ISDIGIT(*s) || *s == ';'
2307 || *s == ' ');
2308 ++s)
2310 if (*s == 'r' || *s == '|') /* found one */
2312 del_typebuf((int)(s + 1 -
2313 (typebuf.tb_buf + typebuf.tb_off)), 0);
2314 /* get size and redraw screen */
2315 shell_resized();
2316 continue;
2318 if (*s == NUL) /* need more characters */
2319 keylen = KL_PART_KEY;
2321 if (keylen >= 0)
2322 #endif
2323 /* When there was a matching mapping and no
2324 * termcode could be replaced after another one,
2325 * use that mapping (loop around). If there was
2326 * no mapping use the character from the
2327 * typeahead buffer right here. */
2328 if (mp == NULL)
2331 * get a character: 2. from the typeahead buffer
2333 c = typebuf.tb_buf[typebuf.tb_off] & 255;
2334 if (advance) /* remove chars from tb_buf */
2336 cmd_silent = (typebuf.tb_silent > 0);
2337 if (typebuf.tb_maplen > 0)
2338 KeyTyped = FALSE;
2339 else
2341 KeyTyped = TRUE;
2342 /* write char to script file(s) */
2343 gotchars(typebuf.tb_buf
2344 + typebuf.tb_off, 1);
2346 KeyNoremap = typebuf.tb_noremap[
2347 typebuf.tb_off];
2348 del_typebuf(1, 0);
2350 break; /* got character, break for loop */
2353 if (keylen > 0) /* full matching terminal code */
2355 #if defined(FEAT_GUI) && defined(FEAT_MENU)
2356 if (typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
2357 && typebuf.tb_buf[typebuf.tb_off + 1]
2358 == KS_MENU)
2361 * Using a menu may cause a break in undo!
2362 * It's like using gotchars(), but without
2363 * recording or writing to a script file.
2365 may_sync_undo();
2366 del_typebuf(3, 0);
2367 idx = get_menu_index(current_menu, local_State);
2368 if (idx != MENU_INDEX_INVALID)
2370 # ifdef FEAT_VISUAL
2372 * In Select mode and a Visual mode menu
2373 * is used: Switch to Visual mode
2374 * temporarily. Append K_SELECT to switch
2375 * back to Select mode.
2377 if (VIsual_active && VIsual_select
2378 && (current_menu->modes & VISUAL))
2380 VIsual_select = FALSE;
2381 (void)ins_typebuf(K_SELECT_STRING,
2382 REMAP_NONE, 0, TRUE, FALSE);
2384 # endif
2385 ins_typebuf(current_menu->strings[idx],
2386 current_menu->noremap[idx],
2387 0, TRUE,
2388 current_menu->silent[idx]);
2391 #endif /* FEAT_GUI && FEAT_MENU */
2392 continue; /* try mapping again */
2395 /* Partial match: get some more characters. When a
2396 * matching mapping was found use that one. */
2397 if (mp == NULL || keylen < 0)
2398 keylen = KL_PART_KEY;
2399 else
2400 keylen = mp_match_len;
2403 /* complete match */
2404 if (keylen >= 0 && keylen <= typebuf.tb_len)
2406 /* write chars to script file(s) */
2407 if (keylen > typebuf.tb_maplen)
2408 gotchars(typebuf.tb_buf + typebuf.tb_off
2409 + typebuf.tb_maplen,
2410 keylen - typebuf.tb_maplen);
2412 cmd_silent = (typebuf.tb_silent > 0);
2413 del_typebuf(keylen, 0); /* remove the mapped keys */
2416 * Put the replacement string in front of mapstr.
2417 * The depth check catches ":map x y" and ":map y x".
2419 if (++mapdepth >= p_mmd)
2421 EMSG(_("E223: recursive mapping"));
2422 if (State & CMDLINE)
2423 redrawcmdline();
2424 else
2425 setcursor();
2426 flush_buffers(FALSE);
2427 mapdepth = 0; /* for next one */
2428 c = -1;
2429 break;
2432 #ifdef FEAT_VISUAL
2434 * In Select mode and a Visual mode mapping is used:
2435 * Switch to Visual mode temporarily. Append K_SELECT
2436 * to switch back to Select mode.
2438 if (VIsual_active && VIsual_select
2439 && (mp->m_mode & VISUAL))
2441 VIsual_select = FALSE;
2442 (void)ins_typebuf(K_SELECT_STRING, REMAP_NONE,
2443 0, TRUE, FALSE);
2445 #endif
2447 #ifdef FEAT_EVAL
2449 * Handle ":map <expr>": evaluate the {rhs} as an
2450 * expression. Save and restore the typeahead so that
2451 * getchar() can be used. Also save and restore the
2452 * command line for "normal :".
2454 if (mp->m_expr)
2456 tasave_T tabuf;
2457 int save_vgetc_busy = vgetc_busy;
2459 save_typeahead(&tabuf);
2460 if (tabuf.typebuf_valid)
2462 vgetc_busy = 0;
2463 s = eval_map_expr(mp->m_str, NUL);
2464 vgetc_busy = save_vgetc_busy;
2466 else
2467 s = NULL;
2468 restore_typeahead(&tabuf);
2470 else
2471 #endif
2472 s = mp->m_str;
2475 * Insert the 'to' part in the typebuf.tb_buf.
2476 * If 'from' field is the same as the start of the
2477 * 'to' field, don't remap the first character (but do
2478 * allow abbreviations).
2479 * If m_noremap is set, don't remap the whole 'to'
2480 * part.
2482 if (s == NULL)
2483 i = FAIL;
2484 else
2486 i = ins_typebuf(s,
2487 mp->m_noremap != REMAP_YES
2488 ? mp->m_noremap
2489 : STRNCMP(s, mp->m_keys,
2490 (size_t)keylen) != 0
2491 ? REMAP_YES : REMAP_SKIP,
2492 0, TRUE, cmd_silent || mp->m_silent);
2493 #ifdef FEAT_EVAL
2494 if (mp->m_expr)
2495 vim_free(s);
2496 #endif
2498 if (i == FAIL)
2500 c = -1;
2501 break;
2503 continue;
2508 * get a character: 3. from the user - handle <Esc> in Insert mode
2511 * special case: if we get an <ESC> in insert mode and there
2512 * are no more characters at once, we pretend to go out of
2513 * insert mode. This prevents the one second delay after
2514 * typing an <ESC>. If we get something after all, we may
2515 * have to redisplay the mode. That the cursor is in the wrong
2516 * place does not matter.
2518 c = 0;
2519 #ifdef FEAT_CMDL_INFO
2520 new_wcol = curwin->w_wcol;
2521 new_wrow = curwin->w_wrow;
2522 #endif
2523 if ( advance
2524 && typebuf.tb_len == 1
2525 && typebuf.tb_buf[typebuf.tb_off] == ESC
2526 && !no_mapping
2527 #ifdef FEAT_EX_EXTRA
2528 && ex_normal_busy == 0
2529 #endif
2530 && typebuf.tb_maplen == 0
2531 && (State & INSERT)
2532 && (p_timeout || (keylen == KL_PART_KEY && p_ttimeout))
2533 && (c = inchar(typebuf.tb_buf + typebuf.tb_off
2534 + typebuf.tb_len, 3, 25L,
2535 typebuf.tb_change_cnt)) == 0)
2537 colnr_T col = 0, vcol;
2538 char_u *ptr;
2540 if (mode_displayed)
2542 unshowmode(TRUE);
2543 mode_deleted = TRUE;
2545 #ifdef FEAT_GUI
2546 /* may show different cursor shape */
2547 if (gui.in_use)
2549 int save_State;
2551 save_State = State;
2552 State = NORMAL;
2553 gui_update_cursor(TRUE, FALSE);
2554 State = save_State;
2555 shape_changed = TRUE;
2557 #endif
2558 validate_cursor();
2559 old_wcol = curwin->w_wcol;
2560 old_wrow = curwin->w_wrow;
2562 /* move cursor left, if possible */
2563 if (curwin->w_cursor.col != 0)
2565 if (curwin->w_wcol > 0)
2567 if (did_ai)
2570 * We are expecting to truncate the trailing
2571 * white-space, so find the last non-white
2572 * character -- webb
2574 col = vcol = curwin->w_wcol = 0;
2575 ptr = ml_get_curline();
2576 while (col < curwin->w_cursor.col)
2578 if (!vim_iswhite(ptr[col]))
2579 curwin->w_wcol = vcol;
2580 vcol += lbr_chartabsize(ptr + col,
2581 (colnr_T)vcol);
2582 #ifdef FEAT_MBYTE
2583 if (has_mbyte)
2584 col += (*mb_ptr2len)(ptr + col);
2585 else
2586 #endif
2587 ++col;
2589 curwin->w_wrow = curwin->w_cline_row
2590 + curwin->w_wcol / W_WIDTH(curwin);
2591 curwin->w_wcol %= W_WIDTH(curwin);
2592 curwin->w_wcol += curwin_col_off();
2593 #ifdef FEAT_MBYTE
2594 col = 0; /* no correction needed */
2595 #endif
2597 else
2599 --curwin->w_wcol;
2600 #ifdef FEAT_MBYTE
2601 col = curwin->w_cursor.col - 1;
2602 #endif
2605 else if (curwin->w_p_wrap && curwin->w_wrow)
2607 --curwin->w_wrow;
2608 curwin->w_wcol = W_WIDTH(curwin) - 1;
2609 #ifdef FEAT_MBYTE
2610 col = curwin->w_cursor.col - 1;
2611 #endif
2613 #ifdef FEAT_MBYTE
2614 if (has_mbyte && col > 0 && curwin->w_wcol > 0)
2616 /* Correct when the cursor is on the right halve
2617 * of a double-wide character. */
2618 ptr = ml_get_curline();
2619 col -= (*mb_head_off)(ptr, ptr + col);
2620 if ((*mb_ptr2cells)(ptr + col) > 1)
2621 --curwin->w_wcol;
2623 #endif
2625 setcursor();
2626 out_flush();
2627 #ifdef FEAT_CMDL_INFO
2628 new_wcol = curwin->w_wcol;
2629 new_wrow = curwin->w_wrow;
2630 #endif
2631 curwin->w_wcol = old_wcol;
2632 curwin->w_wrow = old_wrow;
2634 if (c < 0)
2635 continue; /* end of input script reached */
2636 typebuf.tb_len += c;
2638 /* buffer full, don't map */
2639 if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN)
2641 timedout = TRUE;
2642 continue;
2645 #ifdef FEAT_EX_EXTRA
2646 if (ex_normal_busy > 0)
2648 # ifdef FEAT_CMDWIN
2649 static int tc = 0;
2650 # endif
2652 /* No typeahead left and inside ":normal". Must return
2653 * something to avoid getting stuck. When an incomplete
2654 * mapping is present, behave like it timed out. */
2655 if (typebuf.tb_len > 0)
2657 timedout = TRUE;
2658 continue;
2660 /* When 'insertmode' is set, ESC just beeps in Insert
2661 * mode. Use CTRL-L to make edit() return.
2662 * For the command line only CTRL-C always breaks it.
2663 * For the cmdline window: Alternate between ESC and
2664 * CTRL-C: ESC for most situations and CTRL-C to close the
2665 * cmdline window. */
2666 if (p_im && (State & INSERT))
2667 c = Ctrl_L;
2668 else if ((State & CMDLINE)
2669 # ifdef FEAT_CMDWIN
2670 || (cmdwin_type > 0 && tc == ESC)
2671 # endif
2673 c = Ctrl_C;
2674 else
2675 c = ESC;
2676 # ifdef FEAT_CMDWIN
2677 tc = c;
2678 # endif
2679 break;
2681 #endif
2684 * get a character: 3. from the user - update display
2686 /* In insert mode a screen update is skipped when characters
2687 * are still available. But when those available characters
2688 * are part of a mapping, and we are going to do a blocking
2689 * wait here. Need to update the screen to display the
2690 * changed text so far. */
2691 if ((State & INSERT) && advance && must_redraw != 0)
2693 update_screen(0);
2694 setcursor(); /* put cursor back where it belongs */
2698 * If we have a partial match (and are going to wait for more
2699 * input from the user), show the partially matched characters
2700 * to the user with showcmd.
2702 #ifdef FEAT_CMDL_INFO
2703 i = 0;
2704 #endif
2705 c1 = 0;
2706 if (typebuf.tb_len > 0 && advance && !exmode_active)
2708 if (((State & (NORMAL | INSERT)) || State == LANGMAP)
2709 && State != HITRETURN)
2711 /* this looks nice when typing a dead character map */
2712 if (State & INSERT
2713 && ptr2cells(typebuf.tb_buf + typebuf.tb_off
2714 + typebuf.tb_len - 1) == 1)
2716 edit_putchar(typebuf.tb_buf[typebuf.tb_off
2717 + typebuf.tb_len - 1], FALSE);
2718 setcursor(); /* put cursor back where it belongs */
2719 c1 = 1;
2721 #ifdef FEAT_CMDL_INFO
2722 /* need to use the col and row from above here */
2723 old_wcol = curwin->w_wcol;
2724 old_wrow = curwin->w_wrow;
2725 curwin->w_wcol = new_wcol;
2726 curwin->w_wrow = new_wrow;
2727 push_showcmd();
2728 if (typebuf.tb_len > SHOWCMD_COLS)
2729 i = typebuf.tb_len - SHOWCMD_COLS;
2730 while (i < typebuf.tb_len)
2731 (void)add_to_showcmd(typebuf.tb_buf[typebuf.tb_off
2732 + i++]);
2733 curwin->w_wcol = old_wcol;
2734 curwin->w_wrow = old_wrow;
2735 #endif
2738 /* this looks nice when typing a dead character map */
2739 if ((State & CMDLINE)
2740 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
2741 && cmdline_star == 0
2742 #endif
2743 && ptr2cells(typebuf.tb_buf + typebuf.tb_off
2744 + typebuf.tb_len - 1) == 1)
2746 putcmdline(typebuf.tb_buf[typebuf.tb_off
2747 + typebuf.tb_len - 1], FALSE);
2748 c1 = 1;
2753 * get a character: 3. from the user - get it
2755 wait_tb_len = typebuf.tb_len;
2756 c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
2757 typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
2758 !advance
2760 : ((typebuf.tb_len == 0
2761 || !(p_timeout || (p_ttimeout
2762 && keylen == KL_PART_KEY)))
2763 ? -1L
2764 : ((keylen == KL_PART_KEY && p_ttm >= 0)
2765 ? p_ttm
2766 : p_tm)), typebuf.tb_change_cnt);
2768 #ifdef FEAT_CMDL_INFO
2769 if (i != 0)
2770 pop_showcmd();
2771 #endif
2772 if (c1 == 1)
2774 if (State & INSERT)
2775 edit_unputchar();
2776 if (State & CMDLINE)
2777 unputcmdline();
2778 setcursor(); /* put cursor back where it belongs */
2781 if (c < 0)
2782 continue; /* end of input script reached */
2783 if (c == NUL) /* no character available */
2785 if (!advance)
2786 break;
2787 if (wait_tb_len > 0) /* timed out */
2789 timedout = TRUE;
2790 continue;
2793 else
2794 { /* allow mapping for just typed characters */
2795 while (typebuf.tb_buf[typebuf.tb_off
2796 + typebuf.tb_len] != NUL)
2797 typebuf.tb_noremap[typebuf.tb_off
2798 + typebuf.tb_len++] = RM_YES;
2799 #ifdef USE_IM_CONTROL
2800 /* Get IM status right after getting keys, not after the
2801 * timeout for a mapping (focus may be lost by then). */
2802 vgetc_im_active = im_get_status();
2803 #endif
2805 } /* for (;;) */
2806 } /* if (!character from stuffbuf) */
2808 /* if advance is FALSE don't loop on NULs */
2809 } while (c < 0 || (advance && c == NUL));
2812 * The "INSERT" message is taken care of here:
2813 * if we return an ESC to exit insert mode, the message is deleted
2814 * if we don't return an ESC but deleted the message before, redisplay it
2816 if (advance && p_smd && msg_silent == 0 && (State & INSERT))
2818 if (c == ESC && !mode_deleted && !no_mapping && mode_displayed)
2820 if (typebuf.tb_len && !KeyTyped)
2821 redraw_cmdline = TRUE; /* delete mode later */
2822 else
2823 unshowmode(FALSE);
2825 else if (c != ESC && mode_deleted)
2827 if (typebuf.tb_len && !KeyTyped)
2828 redraw_cmdline = TRUE; /* show mode later */
2829 else
2830 showmode();
2833 #ifdef FEAT_GUI
2834 /* may unshow different cursor shape */
2835 if (gui.in_use && shape_changed)
2836 gui_update_cursor(TRUE, FALSE);
2837 #endif
2839 --vgetc_busy;
2841 return c;
2845 * inchar() - get one character from
2846 * 1. a scriptfile
2847 * 2. the keyboard
2849 * As much characters as we can get (upto 'maxlen') are put in "buf" and
2850 * NUL terminated (buffer length must be 'maxlen' + 1).
2851 * Minimum for "maxlen" is 3!!!!
2853 * "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into
2854 * it. When typebuf.tb_change_cnt changes (e.g., when a message is received
2855 * from a remote client) "buf" can no longer be used. "tb_change_cnt" is 0
2856 * otherwise.
2858 * If we got an interrupt all input is read until none is available.
2860 * If wait_time == 0 there is no waiting for the char.
2861 * If wait_time == n we wait for n msec for a character to arrive.
2862 * If wait_time == -1 we wait forever for a character to arrive.
2864 * Return the number of obtained characters.
2865 * Return -1 when end of input script reached.
2868 inchar(buf, maxlen, wait_time, tb_change_cnt)
2869 char_u *buf;
2870 int maxlen;
2871 long wait_time; /* milli seconds */
2872 int tb_change_cnt;
2874 int len = 0; /* init for GCC */
2875 int retesc = FALSE; /* return ESC with gotint */
2876 int script_char;
2878 if (wait_time == -1L || wait_time > 100L) /* flush output before waiting */
2880 cursor_on();
2881 out_flush();
2882 #ifdef FEAT_GUI
2883 if (gui.in_use)
2885 gui_update_cursor(FALSE, FALSE);
2886 # ifdef FEAT_MOUSESHAPE
2887 if (postponed_mouseshape)
2888 update_mouseshape(-1);
2889 # endif
2891 #endif
2895 * Don't reset these when at the hit-return prompt, otherwise a endless
2896 * recursive loop may result (write error in swapfile, hit-return, timeout
2897 * on char wait, flush swapfile, write error....).
2899 if (State != HITRETURN)
2901 did_outofmem_msg = FALSE; /* display out of memory message (again) */
2902 did_swapwrite_msg = FALSE; /* display swap file write error again */
2904 undo_off = FALSE; /* restart undo now */
2907 * Get a character from a script file if there is one.
2908 * If interrupted: Stop reading script files, close them all.
2910 script_char = -1;
2911 while (scriptin[curscript] != NULL && script_char < 0
2912 #ifdef FEAT_EVAL
2913 && !ignore_script
2914 #endif
2918 #if defined(FEAT_NETBEANS_INTG)
2919 /* Process the queued netbeans messages. */
2920 netbeans_parse_messages();
2921 #endif
2923 if (got_int || (script_char = getc(scriptin[curscript])) < 0)
2925 /* Reached EOF.
2926 * Careful: closescript() frees typebuf.tb_buf[] and buf[] may
2927 * point inside typebuf.tb_buf[]. Don't use buf[] after this! */
2928 closescript();
2930 * When reading script file is interrupted, return an ESC to get
2931 * back to normal mode.
2932 * Otherwise return -1, because typebuf.tb_buf[] has changed.
2934 if (got_int)
2935 retesc = TRUE;
2936 else
2937 return -1;
2939 else
2941 buf[0] = script_char;
2942 len = 1;
2946 if (script_char < 0) /* did not get a character from script */
2949 * If we got an interrupt, skip all previously typed characters and
2950 * return TRUE if quit reading script file.
2951 * Stop reading typeahead when a single CTRL-C was read,
2952 * fill_input_buf() returns this when not able to read from stdin.
2953 * Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
2954 * and buf may be pointing inside typebuf.tb_buf[].
2956 if (got_int)
2958 #define DUM_LEN MAXMAPLEN * 3 + 3
2959 char_u dum[DUM_LEN + 1];
2961 for (;;)
2963 len = ui_inchar(dum, DUM_LEN, 0L, 0);
2964 if (len == 0 || (len == 1 && dum[0] == 3))
2965 break;
2967 return retesc;
2971 * Always flush the output characters when getting input characters
2972 * from the user.
2974 out_flush();
2977 * Fill up to a third of the buffer, because each character may be
2978 * tripled below.
2980 len = ui_inchar(buf, maxlen / 3, wait_time, tb_change_cnt);
2983 if (typebuf_changed(tb_change_cnt))
2984 return 0;
2986 return fix_input_buffer(buf, len, script_char >= 0);
2990 * Fix typed characters for use by vgetc() and check_termcode().
2991 * buf[] must have room to triple the number of bytes!
2992 * Returns the new length.
2995 fix_input_buffer(buf, len, script)
2996 char_u *buf;
2997 int len;
2998 int script; /* TRUE when reading from a script */
3000 int i;
3001 char_u *p = buf;
3004 * Two characters are special: NUL and K_SPECIAL.
3005 * When compiled With the GUI CSI is also special.
3006 * Replace NUL by K_SPECIAL KS_ZERO KE_FILLER
3007 * Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
3008 * Replace CSI by K_SPECIAL KS_EXTRA KE_CSI
3009 * Don't replace K_SPECIAL when reading a script file.
3011 for (i = len; --i >= 0; ++p)
3013 #ifdef FEAT_GUI
3014 /* When the GUI is used any character can come after a CSI, don't
3015 * escape it. */
3016 if (gui.in_use && p[0] == CSI && i >= 2)
3018 p += 2;
3019 i -= 2;
3021 /* When the GUI is not used CSI needs to be escaped. */
3022 else if (!gui.in_use && p[0] == CSI)
3024 mch_memmove(p + 3, p + 1, (size_t)i);
3025 *p++ = K_SPECIAL;
3026 *p++ = KS_EXTRA;
3027 *p = (int)KE_CSI;
3028 len += 2;
3030 else
3031 #endif
3032 if (p[0] == NUL || (p[0] == K_SPECIAL && !script
3033 #ifdef FEAT_AUTOCMD
3034 /* timeout may generate K_CURSORHOLD */
3035 && (i < 2 || p[1] != KS_EXTRA || p[2] != (int)KE_CURSORHOLD)
3036 #endif
3037 #if defined(WIN3264) && !defined(FEAT_GUI)
3038 /* Win32 console passes modifiers */
3039 && (i < 2 || p[1] != KS_MODIFIER)
3040 #endif
3043 mch_memmove(p + 3, p + 1, (size_t)i);
3044 p[2] = K_THIRD(p[0]);
3045 p[1] = K_SECOND(p[0]);
3046 p[0] = K_SPECIAL;
3047 p += 2;
3048 len += 2;
3051 *p = NUL; /* add trailing NUL */
3052 return len;
3055 #if defined(USE_INPUT_BUF) || defined(PROTO)
3057 * Return TRUE when bytes are in the input buffer or in the typeahead buffer.
3058 * Normally the input buffer would be sufficient, but the server_to_input_buf()
3059 * or feedkeys() may insert characters in the typeahead buffer while we are
3060 * waiting for input to arrive.
3063 input_available()
3065 return (!vim_is_input_buf_empty()
3066 # if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
3067 || typebuf_was_filled
3068 # endif
3071 #endif
3074 * map[!] : show all key mappings
3075 * map[!] {lhs} : show key mapping for {lhs}
3076 * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
3077 * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
3078 * unmap[!] {lhs} : remove key mapping for {lhs}
3079 * abbr : show all abbreviations
3080 * abbr {lhs} : show abbreviations for {lhs}
3081 * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
3082 * noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
3083 * unabbr {lhs} : remove abbreviation for {lhs}
3085 * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
3087 * arg is pointer to any arguments. Note: arg cannot be a read-only string,
3088 * it will be modified.
3090 * for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
3091 * for :map! mode is INSERT + CMDLINE
3092 * for :cmap mode is CMDLINE
3093 * for :imap mode is INSERT
3094 * for :lmap mode is LANGMAP
3095 * for :nmap mode is NORMAL
3096 * for :vmap mode is VISUAL + SELECTMODE
3097 * for :xmap mode is VISUAL
3098 * for :smap mode is SELECTMODE
3099 * for :omap mode is OP_PENDING
3101 * for :abbr mode is INSERT + CMDLINE
3102 * for :iabbr mode is INSERT
3103 * for :cabbr mode is CMDLINE
3105 * Return 0 for success
3106 * 1 for invalid arguments
3107 * 2 for no match
3108 * 4 for out of mem
3109 * 5 for entry not unique
3112 do_map(maptype, arg, mode, abbrev)
3113 int maptype;
3114 char_u *arg;
3115 int mode;
3116 int abbrev; /* not a mapping but an abbreviation */
3118 char_u *keys;
3119 mapblock_T *mp, **mpp;
3120 char_u *rhs;
3121 char_u *p;
3122 int n;
3123 int len = 0; /* init for GCC */
3124 char_u *newstr;
3125 int hasarg;
3126 int haskey;
3127 int did_it = FALSE;
3128 #ifdef FEAT_LOCALMAP
3129 int did_local = FALSE;
3130 #endif
3131 int round;
3132 char_u *keys_buf = NULL;
3133 char_u *arg_buf = NULL;
3134 int retval = 0;
3135 int do_backslash;
3136 int hash;
3137 int new_hash;
3138 mapblock_T **abbr_table;
3139 mapblock_T **map_table;
3140 int unique = FALSE;
3141 int silent = FALSE;
3142 int special = FALSE;
3143 #ifdef FEAT_EVAL
3144 int expr = FALSE;
3145 #endif
3146 int noremap;
3148 keys = arg;
3149 map_table = maphash;
3150 abbr_table = &first_abbr;
3152 /* For ":noremap" don't remap, otherwise do remap. */
3153 if (maptype == 2)
3154 noremap = REMAP_NONE;
3155 else
3156 noremap = REMAP_YES;
3158 /* Accept <buffer>, <silent>, <expr> <script> and <unique> in any order. */
3159 for (;;)
3161 #ifdef FEAT_LOCALMAP
3163 * Check for "<buffer>": mapping local to buffer.
3165 if (STRNCMP(keys, "<buffer>", 8) == 0)
3167 keys = skipwhite(keys + 8);
3168 map_table = curbuf->b_maphash;
3169 abbr_table = &curbuf->b_first_abbr;
3170 continue;
3172 #endif
3175 * Check for "<silent>": don't echo commands.
3177 if (STRNCMP(keys, "<silent>", 8) == 0)
3179 keys = skipwhite(keys + 8);
3180 silent = TRUE;
3181 continue;
3185 * Check for "<special>": accept special keys in <>
3187 if (STRNCMP(keys, "<special>", 9) == 0)
3189 keys = skipwhite(keys + 9);
3190 special = TRUE;
3191 continue;
3194 #ifdef FEAT_EVAL
3196 * Check for "<script>": remap script-local mappings only
3198 if (STRNCMP(keys, "<script>", 8) == 0)
3200 keys = skipwhite(keys + 8);
3201 noremap = REMAP_SCRIPT;
3202 continue;
3206 * Check for "<expr>": {rhs} is an expression.
3208 if (STRNCMP(keys, "<expr>", 6) == 0)
3210 keys = skipwhite(keys + 6);
3211 expr = TRUE;
3212 continue;
3214 #endif
3216 * Check for "<unique>": don't overwrite an existing mapping.
3218 if (STRNCMP(keys, "<unique>", 8) == 0)
3220 keys = skipwhite(keys + 8);
3221 unique = TRUE;
3222 continue;
3224 break;
3227 validate_maphash();
3230 * find end of keys and skip CTRL-Vs (and backslashes) in it
3231 * Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
3232 * with :unmap white space is included in the keys, no argument possible
3234 p = keys;
3235 do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
3236 while (*p && (maptype == 1 || !vim_iswhite(*p)))
3238 if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
3239 p[1] != NUL)
3240 ++p; /* skip CTRL-V or backslash */
3241 ++p;
3243 if (*p != NUL)
3244 *p++ = NUL;
3245 p = skipwhite(p);
3246 rhs = p;
3247 hasarg = (*rhs != NUL);
3248 haskey = (*keys != NUL);
3250 /* check for :unmap without argument */
3251 if (maptype == 1 && !haskey)
3253 retval = 1;
3254 goto theend;
3258 * If mapping has been given as ^V<C_UP> say, then replace the term codes
3259 * with the appropriate two bytes. If it is a shifted special key, unshift
3260 * it too, giving another two bytes.
3261 * replace_termcodes() may move the result to allocated memory, which
3262 * needs to be freed later (*keys_buf and *arg_buf).
3263 * replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
3265 if (haskey)
3266 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, special);
3267 if (hasarg)
3269 if (STRICMP(rhs, "<nop>") == 0) /* "<Nop>" means nothing */
3270 rhs = (char_u *)"";
3271 else
3272 rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE, special);
3275 #ifdef FEAT_FKMAP
3277 * when in right-to-left mode and alternate keymap option set,
3278 * reverse the character flow in the rhs in Farsi.
3280 if (p_altkeymap && curwin->w_p_rl)
3281 lrswap(rhs);
3282 #endif
3285 * check arguments and translate function keys
3287 if (haskey)
3289 len = (int)STRLEN(keys);
3290 if (len > MAXMAPLEN) /* maximum length of MAXMAPLEN chars */
3292 retval = 1;
3293 goto theend;
3296 if (abbrev && maptype != 1)
3299 * If an abbreviation ends in a keyword character, the
3300 * rest must be all keyword-char or all non-keyword-char.
3301 * Otherwise we won't be able to find the start of it in a
3302 * vi-compatible way.
3304 #ifdef FEAT_MBYTE
3305 if (has_mbyte)
3307 int first, last;
3308 int same = -1;
3310 first = vim_iswordp(keys);
3311 last = first;
3312 p = keys + (*mb_ptr2len)(keys);
3313 n = 1;
3314 while (p < keys + len)
3316 ++n; /* nr of (multi-byte) chars */
3317 last = vim_iswordp(p); /* type of last char */
3318 if (same == -1 && last != first)
3319 same = n - 1; /* count of same char type */
3320 p += (*mb_ptr2len)(p);
3322 if (last && n > 2 && same >= 0 && same < n - 1)
3324 retval = 1;
3325 goto theend;
3328 else
3329 #endif
3330 if (vim_iswordc(keys[len - 1])) /* ends in keyword char */
3331 for (n = 0; n < len - 2; ++n)
3332 if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
3334 retval = 1;
3335 goto theend;
3337 /* An abbreviation cannot contain white space. */
3338 for (n = 0; n < len; ++n)
3339 if (vim_iswhite(keys[n]))
3341 retval = 1;
3342 goto theend;
3347 if (haskey && hasarg && abbrev) /* if we will add an abbreviation */
3348 no_abbr = FALSE; /* reset flag that indicates there are
3349 no abbreviations */
3351 if (!haskey || (maptype != 1 && !hasarg))
3352 msg_start();
3354 #ifdef FEAT_LOCALMAP
3356 * Check if a new local mapping wasn't already defined globally.
3358 if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1)
3360 /* need to loop over all global hash lists */
3361 for (hash = 0; hash < 256 && !got_int; ++hash)
3363 if (abbrev)
3365 if (hash != 0) /* there is only one abbreviation list */
3366 break;
3367 mp = first_abbr;
3369 else
3370 mp = maphash[hash];
3371 for ( ; mp != NULL && !got_int; mp = mp->m_next)
3373 /* check entries with the same mode */
3374 if ((mp->m_mode & mode) != 0
3375 && mp->m_keylen == len
3376 && unique
3377 && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
3379 if (abbrev)
3380 EMSG2(_("E224: global abbreviation already exists for %s"),
3381 mp->m_keys);
3382 else
3383 EMSG2(_("E225: global mapping already exists for %s"),
3384 mp->m_keys);
3385 retval = 5;
3386 goto theend;
3393 * When listing global mappings, also list buffer-local ones here.
3395 if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
3397 /* need to loop over all global hash lists */
3398 for (hash = 0; hash < 256 && !got_int; ++hash)
3400 if (abbrev)
3402 if (hash != 0) /* there is only one abbreviation list */
3403 break;
3404 mp = curbuf->b_first_abbr;
3406 else
3407 mp = curbuf->b_maphash[hash];
3408 for ( ; mp != NULL && !got_int; mp = mp->m_next)
3410 /* check entries with the same mode */
3411 if ((mp->m_mode & mode) != 0)
3413 if (!haskey) /* show all entries */
3415 showmap(mp, TRUE);
3416 did_local = TRUE;
3418 else
3420 n = mp->m_keylen;
3421 if (STRNCMP(mp->m_keys, keys,
3422 (size_t)(n < len ? n : len)) == 0)
3424 showmap(mp, TRUE);
3425 did_local = TRUE;
3432 #endif
3435 * Find an entry in the maphash[] list that matches.
3436 * For :unmap we may loop two times: once to try to unmap an entry with a
3437 * matching 'from' part, a second time, if the first fails, to unmap an
3438 * entry with a matching 'to' part. This was done to allow ":ab foo bar"
3439 * to be unmapped by typing ":unab foo", where "foo" will be replaced by
3440 * "bar" because of the abbreviation.
3442 for (round = 0; (round == 0 || maptype == 1) && round <= 1
3443 && !did_it && !got_int; ++round)
3445 /* need to loop over all hash lists */
3446 for (hash = 0; hash < 256 && !got_int; ++hash)
3448 if (abbrev)
3450 if (hash > 0) /* there is only one abbreviation list */
3451 break;
3452 mpp = abbr_table;
3454 else
3455 mpp = &(map_table[hash]);
3456 for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
3459 if (!(mp->m_mode & mode)) /* skip entries with wrong mode */
3461 mpp = &(mp->m_next);
3462 continue;
3464 if (!haskey) /* show all entries */
3466 showmap(mp, map_table != maphash);
3467 did_it = TRUE;
3469 else /* do we have a match? */
3471 if (round) /* second round: Try unmap "rhs" string */
3473 n = (int)STRLEN(mp->m_str);
3474 p = mp->m_str;
3476 else
3478 n = mp->m_keylen;
3479 p = mp->m_keys;
3481 if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
3483 if (maptype == 1) /* delete entry */
3485 /* Only accept a full match. For abbreviations we
3486 * ignore trailing space when matching with the
3487 * "lhs", since an abbreviation can't have
3488 * trailing space. */
3489 if (n != len && (!abbrev || round || n > len
3490 || *skipwhite(keys + n) != NUL))
3492 mpp = &(mp->m_next);
3493 continue;
3496 * We reset the indicated mode bits. If nothing is
3497 * left the entry is deleted below.
3499 mp->m_mode &= ~mode;
3500 did_it = TRUE; /* remember we did something */
3502 else if (!hasarg) /* show matching entry */
3504 showmap(mp, map_table != maphash);
3505 did_it = TRUE;
3507 else if (n != len) /* new entry is ambiguous */
3509 mpp = &(mp->m_next);
3510 continue;
3512 else if (unique)
3514 if (abbrev)
3515 EMSG2(_("E226: abbreviation already exists for %s"),
3517 else
3518 EMSG2(_("E227: mapping already exists for %s"), p);
3519 retval = 5;
3520 goto theend;
3522 else /* new rhs for existing entry */
3524 mp->m_mode &= ~mode; /* remove mode bits */
3525 if (mp->m_mode == 0 && !did_it) /* reuse entry */
3527 newstr = vim_strsave(rhs);
3528 if (newstr == NULL)
3530 retval = 4; /* no mem */
3531 goto theend;
3533 vim_free(mp->m_str);
3534 mp->m_str = newstr;
3535 mp->m_noremap = noremap;
3536 mp->m_silent = silent;
3537 mp->m_mode = mode;
3538 #ifdef FEAT_EVAL
3539 mp->m_expr = expr;
3540 mp->m_script_ID = current_SID;
3541 #endif
3542 did_it = TRUE;
3545 if (mp->m_mode == 0) /* entry can be deleted */
3547 map_free(mpp);
3548 continue; /* continue with *mpp */
3552 * May need to put this entry into another hash list.
3554 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
3555 if (!abbrev && new_hash != hash)
3557 *mpp = mp->m_next;
3558 mp->m_next = map_table[new_hash];
3559 map_table[new_hash] = mp;
3561 continue; /* continue with *mpp */
3565 mpp = &(mp->m_next);
3570 if (maptype == 1) /* delete entry */
3572 if (!did_it)
3573 retval = 2; /* no match */
3574 goto theend;
3577 if (!haskey || !hasarg) /* print entries */
3579 if (!did_it
3580 #ifdef FEAT_LOCALMAP
3581 && !did_local
3582 #endif
3585 if (abbrev)
3586 MSG(_("No abbreviation found"));
3587 else
3588 MSG(_("No mapping found"));
3590 goto theend; /* listing finished */
3593 if (did_it) /* have added the new entry already */
3594 goto theend;
3597 * Get here when adding a new entry to the maphash[] list or abbrlist.
3599 mp = (mapblock_T *)alloc((unsigned)sizeof(mapblock_T));
3600 if (mp == NULL)
3602 retval = 4; /* no mem */
3603 goto theend;
3606 /* If CTRL-C has been mapped, don't always use it for Interrupting */
3607 if (*keys == Ctrl_C)
3608 mapped_ctrl_c = TRUE;
3610 mp->m_keys = vim_strsave(keys);
3611 mp->m_str = vim_strsave(rhs);
3612 if (mp->m_keys == NULL || mp->m_str == NULL)
3614 vim_free(mp->m_keys);
3615 vim_free(mp->m_str);
3616 vim_free(mp);
3617 retval = 4; /* no mem */
3618 goto theend;
3620 mp->m_keylen = (int)STRLEN(mp->m_keys);
3621 mp->m_noremap = noremap;
3622 mp->m_silent = silent;
3623 mp->m_mode = mode;
3624 #ifdef FEAT_EVAL
3625 mp->m_expr = expr;
3626 mp->m_script_ID = current_SID;
3627 #endif
3629 /* add the new entry in front of the abbrlist or maphash[] list */
3630 if (abbrev)
3632 mp->m_next = *abbr_table;
3633 *abbr_table = mp;
3635 else
3637 n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
3638 mp->m_next = map_table[n];
3639 map_table[n] = mp;
3642 theend:
3643 vim_free(keys_buf);
3644 vim_free(arg_buf);
3645 return retval;
3649 * Delete one entry from the abbrlist or maphash[].
3650 * "mpp" is a pointer to the m_next field of the PREVIOUS entry!
3652 static void
3653 map_free(mpp)
3654 mapblock_T **mpp;
3656 mapblock_T *mp;
3658 mp = *mpp;
3659 vim_free(mp->m_keys);
3660 vim_free(mp->m_str);
3661 *mpp = mp->m_next;
3662 vim_free(mp);
3666 * Initialize maphash[] for first use.
3668 static void
3669 validate_maphash()
3671 if (!maphash_valid)
3673 vim_memset(maphash, 0, sizeof(maphash));
3674 maphash_valid = TRUE;
3679 * Get the mapping mode from the command name.
3682 get_map_mode(cmdp, forceit)
3683 char_u **cmdp;
3684 int forceit;
3686 char_u *p;
3687 int modec;
3688 int mode;
3690 p = *cmdp;
3691 modec = *p++;
3692 if (modec == 'i')
3693 mode = INSERT; /* :imap */
3694 else if (modec == 'l')
3695 mode = LANGMAP; /* :lmap */
3696 else if (modec == 'c')
3697 mode = CMDLINE; /* :cmap */
3698 else if (modec == 'n' && *p != 'o') /* avoid :noremap */
3699 mode = NORMAL; /* :nmap */
3700 else if (modec == 'v')
3701 mode = VISUAL + SELECTMODE; /* :vmap */
3702 else if (modec == 'x')
3703 mode = VISUAL; /* :xmap */
3704 else if (modec == 's')
3705 mode = SELECTMODE; /* :smap */
3706 else if (modec == 'o')
3707 mode = OP_PENDING; /* :omap */
3708 else
3710 --p;
3711 if (forceit)
3712 mode = INSERT + CMDLINE; /* :map ! */
3713 else
3714 mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;/* :map */
3717 *cmdp = p;
3718 return mode;
3722 * Clear all mappings or abbreviations.
3723 * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
3725 void
3726 map_clear(cmdp, arg, forceit, abbr)
3727 char_u *cmdp;
3728 char_u *arg UNUSED;
3729 int forceit;
3730 int abbr;
3732 int mode;
3733 #ifdef FEAT_LOCALMAP
3734 int local;
3736 local = (STRCMP(arg, "<buffer>") == 0);
3737 if (!local && *arg != NUL)
3739 EMSG(_(e_invarg));
3740 return;
3742 #endif
3744 mode = get_map_mode(&cmdp, forceit);
3745 map_clear_int(curbuf, mode,
3746 #ifdef FEAT_LOCALMAP
3747 local,
3748 #else
3749 FALSE,
3750 #endif
3751 abbr);
3755 * Clear all mappings in "mode".
3757 void
3758 map_clear_int(buf, mode, local, abbr)
3759 buf_T *buf UNUSED; /* buffer for local mappings */
3760 int mode; /* mode in which to delete */
3761 int local UNUSED; /* TRUE for buffer-local mappings */
3762 int abbr; /* TRUE for abbreviations */
3764 mapblock_T *mp, **mpp;
3765 int hash;
3766 int new_hash;
3768 validate_maphash();
3770 for (hash = 0; hash < 256; ++hash)
3772 if (abbr)
3774 if (hash > 0) /* there is only one abbrlist */
3775 break;
3776 #ifdef FEAT_LOCALMAP
3777 if (local)
3778 mpp = &buf->b_first_abbr;
3779 else
3780 #endif
3781 mpp = &first_abbr;
3783 else
3785 #ifdef FEAT_LOCALMAP
3786 if (local)
3787 mpp = &buf->b_maphash[hash];
3788 else
3789 #endif
3790 mpp = &maphash[hash];
3792 while (*mpp != NULL)
3794 mp = *mpp;
3795 if (mp->m_mode & mode)
3797 mp->m_mode &= ~mode;
3798 if (mp->m_mode == 0) /* entry can be deleted */
3800 map_free(mpp);
3801 continue;
3804 * May need to put this entry into another hash list.
3806 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
3807 if (!abbr && new_hash != hash)
3809 *mpp = mp->m_next;
3810 #ifdef FEAT_LOCALMAP
3811 if (local)
3813 mp->m_next = buf->b_maphash[new_hash];
3814 buf->b_maphash[new_hash] = mp;
3816 else
3817 #endif
3819 mp->m_next = maphash[new_hash];
3820 maphash[new_hash] = mp;
3822 continue; /* continue with *mpp */
3825 mpp = &(mp->m_next);
3830 static void
3831 showmap(mp, local)
3832 mapblock_T *mp;
3833 int local; /* TRUE for buffer-local map */
3835 int len = 1;
3837 if (msg_didout || msg_silent != 0)
3839 msg_putchar('\n');
3840 if (got_int) /* 'q' typed at MORE prompt */
3841 return;
3843 if ((mp->m_mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
3844 msg_putchar('!'); /* :map! */
3845 else if (mp->m_mode & INSERT)
3846 msg_putchar('i'); /* :imap */
3847 else if (mp->m_mode & LANGMAP)
3848 msg_putchar('l'); /* :lmap */
3849 else if (mp->m_mode & CMDLINE)
3850 msg_putchar('c'); /* :cmap */
3851 else if ((mp->m_mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING))
3852 == NORMAL + VISUAL + SELECTMODE + OP_PENDING)
3853 msg_putchar(' '); /* :map */
3854 else
3856 len = 0;
3857 if (mp->m_mode & NORMAL)
3859 msg_putchar('n'); /* :nmap */
3860 ++len;
3862 if (mp->m_mode & OP_PENDING)
3864 msg_putchar('o'); /* :omap */
3865 ++len;
3867 if ((mp->m_mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE)
3869 msg_putchar('v'); /* :vmap */
3870 ++len;
3872 else
3874 if (mp->m_mode & VISUAL)
3876 msg_putchar('x'); /* :xmap */
3877 ++len;
3879 if (mp->m_mode & SELECTMODE)
3881 msg_putchar('s'); /* :smap */
3882 ++len;
3886 while (++len <= 3)
3887 msg_putchar(' ');
3889 /* Display the LHS. Get length of what we write. */
3890 len = msg_outtrans_special(mp->m_keys, TRUE);
3893 msg_putchar(' '); /* padd with blanks */
3894 ++len;
3895 } while (len < 12);
3897 if (mp->m_noremap == REMAP_NONE)
3898 msg_puts_attr((char_u *)"*", hl_attr(HLF_8));
3899 else if (mp->m_noremap == REMAP_SCRIPT)
3900 msg_puts_attr((char_u *)"&", hl_attr(HLF_8));
3901 else
3902 msg_putchar(' ');
3904 if (local)
3905 msg_putchar('@');
3906 else
3907 msg_putchar(' ');
3909 /* Use FALSE below if we only want things like <Up> to show up as such on
3910 * the rhs, and not M-x etc, TRUE gets both -- webb
3912 if (*mp->m_str == NUL)
3913 msg_puts_attr((char_u *)"<Nop>", hl_attr(HLF_8));
3914 else
3915 msg_outtrans_special(mp->m_str, FALSE);
3916 #ifdef FEAT_EVAL
3917 if (p_verbose > 0)
3918 last_set_msg(mp->m_script_ID);
3919 #endif
3920 out_flush(); /* show one line at a time */
3923 #if defined(FEAT_EVAL) || defined(PROTO)
3925 * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
3926 * Recognize termcap codes in "str".
3927 * Also checks mappings local to the current buffer.
3930 map_to_exists(str, modechars, abbr)
3931 char_u *str;
3932 char_u *modechars;
3933 int abbr;
3935 int mode = 0;
3936 char_u *rhs;
3937 char_u *buf;
3938 int retval;
3940 rhs = replace_termcodes(str, &buf, FALSE, TRUE, FALSE);
3942 if (vim_strchr(modechars, 'n') != NULL)
3943 mode |= NORMAL;
3944 if (vim_strchr(modechars, 'v') != NULL)
3945 mode |= VISUAL + SELECTMODE;
3946 if (vim_strchr(modechars, 'x') != NULL)
3947 mode |= VISUAL;
3948 if (vim_strchr(modechars, 's') != NULL)
3949 mode |= SELECTMODE;
3950 if (vim_strchr(modechars, 'o') != NULL)
3951 mode |= OP_PENDING;
3952 if (vim_strchr(modechars, 'i') != NULL)
3953 mode |= INSERT;
3954 if (vim_strchr(modechars, 'l') != NULL)
3955 mode |= LANGMAP;
3956 if (vim_strchr(modechars, 'c') != NULL)
3957 mode |= CMDLINE;
3959 retval = map_to_exists_mode(rhs, mode, abbr);
3960 vim_free(buf);
3962 return retval;
3964 #endif
3967 * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
3968 * Also checks mappings local to the current buffer.
3971 map_to_exists_mode(rhs, mode, abbr)
3972 char_u *rhs;
3973 int mode;
3974 int abbr;
3976 mapblock_T *mp;
3977 int hash;
3978 # ifdef FEAT_LOCALMAP
3979 int expand_buffer = FALSE;
3981 validate_maphash();
3983 /* Do it twice: once for global maps and once for local maps. */
3984 for (;;)
3986 # endif
3987 for (hash = 0; hash < 256; ++hash)
3989 if (abbr)
3991 if (hash > 0) /* there is only one abbr list */
3992 break;
3993 #ifdef FEAT_LOCALMAP
3994 if (expand_buffer)
3995 mp = curbuf->b_first_abbr;
3996 else
3997 #endif
3998 mp = first_abbr;
4000 # ifdef FEAT_LOCALMAP
4001 else if (expand_buffer)
4002 mp = curbuf->b_maphash[hash];
4003 # endif
4004 else
4005 mp = maphash[hash];
4006 for (; mp; mp = mp->m_next)
4008 if ((mp->m_mode & mode)
4009 && strstr((char *)mp->m_str, (char *)rhs) != NULL)
4010 return TRUE;
4013 # ifdef FEAT_LOCALMAP
4014 if (expand_buffer)
4015 break;
4016 expand_buffer = TRUE;
4018 # endif
4020 return FALSE;
4023 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4025 * Used below when expanding mapping/abbreviation names.
4027 static int expand_mapmodes = 0;
4028 static int expand_isabbrev = 0;
4029 #ifdef FEAT_LOCALMAP
4030 static int expand_buffer = FALSE;
4031 #endif
4034 * Work out what to complete when doing command line completion of mapping
4035 * or abbreviation names.
4037 char_u *
4038 set_context_in_map_cmd(xp, cmd, arg, forceit, isabbrev, isunmap, cmdidx)
4039 expand_T *xp;
4040 char_u *cmd;
4041 char_u *arg;
4042 int forceit; /* TRUE if '!' given */
4043 int isabbrev; /* TRUE if abbreviation */
4044 int isunmap; /* TRUE if unmap/unabbrev command */
4045 cmdidx_T cmdidx;
4047 if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
4048 xp->xp_context = EXPAND_NOTHING;
4049 else
4051 if (isunmap)
4052 expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
4053 else
4055 expand_mapmodes = INSERT + CMDLINE;
4056 if (!isabbrev)
4057 expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
4059 expand_isabbrev = isabbrev;
4060 xp->xp_context = EXPAND_MAPPINGS;
4061 #ifdef FEAT_LOCALMAP
4062 expand_buffer = FALSE;
4063 #endif
4064 for (;;)
4066 #ifdef FEAT_LOCALMAP
4067 if (STRNCMP(arg, "<buffer>", 8) == 0)
4069 expand_buffer = TRUE;
4070 arg = skipwhite(arg + 8);
4071 continue;
4073 #endif
4074 if (STRNCMP(arg, "<unique>", 8) == 0)
4076 arg = skipwhite(arg + 8);
4077 continue;
4079 if (STRNCMP(arg, "<silent>", 8) == 0)
4081 arg = skipwhite(arg + 8);
4082 continue;
4084 #ifdef FEAT_EVAL
4085 if (STRNCMP(arg, "<script>", 8) == 0)
4087 arg = skipwhite(arg + 8);
4088 continue;
4090 if (STRNCMP(arg, "<expr>", 6) == 0)
4092 arg = skipwhite(arg + 6);
4093 continue;
4095 #endif
4096 break;
4098 xp->xp_pattern = arg;
4101 return NULL;
4105 * Find all mapping/abbreviation names that match regexp 'prog'.
4106 * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
4107 * Return OK if matches found, FAIL otherwise.
4110 ExpandMappings(regmatch, num_file, file)
4111 regmatch_T *regmatch;
4112 int *num_file;
4113 char_u ***file;
4115 mapblock_T *mp;
4116 int hash;
4117 int count;
4118 int round;
4119 char_u *p;
4120 int i;
4122 validate_maphash();
4124 *num_file = 0; /* return values in case of FAIL */
4125 *file = NULL;
4128 * round == 1: Count the matches.
4129 * round == 2: Build the array to keep the matches.
4131 for (round = 1; round <= 2; ++round)
4133 count = 0;
4135 for (i = 0; i < 5; ++i)
4137 if (i == 0)
4138 p = (char_u *)"<silent>";
4139 else if (i == 1)
4140 p = (char_u *)"<unique>";
4141 #ifdef FEAT_EVAL
4142 else if (i == 2)
4143 p = (char_u *)"<script>";
4144 else if (i == 3)
4145 p = (char_u *)"<expr>";
4146 #endif
4147 #ifdef FEAT_LOCALMAP
4148 else if (i == 4 && !expand_buffer)
4149 p = (char_u *)"<buffer>";
4150 #endif
4151 else
4152 continue;
4154 if (vim_regexec(regmatch, p, (colnr_T)0))
4156 if (round == 1)
4157 ++count;
4158 else
4159 (*file)[count++] = vim_strsave(p);
4163 for (hash = 0; hash < 256; ++hash)
4165 if (expand_isabbrev)
4167 if (hash > 0) /* only one abbrev list */
4168 break; /* for (hash) */
4169 mp = first_abbr;
4171 #ifdef FEAT_LOCALMAP
4172 else if (expand_buffer)
4173 mp = curbuf->b_maphash[hash];
4174 #endif
4175 else
4176 mp = maphash[hash];
4177 for (; mp; mp = mp->m_next)
4179 if (mp->m_mode & expand_mapmodes)
4181 p = translate_mapping(mp->m_keys, TRUE);
4182 if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
4184 if (round == 1)
4185 ++count;
4186 else
4188 (*file)[count++] = p;
4189 p = NULL;
4192 vim_free(p);
4194 } /* for (mp) */
4195 } /* for (hash) */
4197 if (count == 0) /* no match found */
4198 break; /* for (round) */
4200 if (round == 1)
4202 *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
4203 if (*file == NULL)
4204 return FAIL;
4206 } /* for (round) */
4208 if (count > 1)
4210 char_u **ptr1;
4211 char_u **ptr2;
4212 char_u **ptr3;
4214 /* Sort the matches */
4215 sort_strings(*file, count);
4217 /* Remove multiple entries */
4218 ptr1 = *file;
4219 ptr2 = ptr1 + 1;
4220 ptr3 = ptr1 + count;
4222 while (ptr2 < ptr3)
4224 if (STRCMP(*ptr1, *ptr2))
4225 *++ptr1 = *ptr2++;
4226 else
4228 vim_free(*ptr2++);
4229 count--;
4234 *num_file = count;
4235 return (count == 0 ? FAIL : OK);
4237 #endif /* FEAT_CMDL_COMPL */
4240 * Check for an abbreviation.
4241 * Cursor is at ptr[col]. When inserting, mincol is where insert started.
4242 * "c" is the character typed before check_abbr was called. It may have
4243 * ABBR_OFF added to avoid prepending a CTRL-V to it.
4245 * Historic vi practice: The last character of an abbreviation must be an id
4246 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
4247 * characters or all non-id characters. This allows for abbr. "#i" to
4248 * "#include".
4250 * Vim addition: Allow for abbreviations that end in a non-keyword character.
4251 * Then there must be white space before the abbr.
4253 * return TRUE if there is an abbreviation, FALSE if not
4256 check_abbr(c, ptr, col, mincol)
4257 int c;
4258 char_u *ptr;
4259 int col;
4260 int mincol;
4262 int len;
4263 int scol; /* starting column of the abbr. */
4264 int j;
4265 char_u *s;
4266 #ifdef FEAT_MBYTE
4267 char_u tb[MB_MAXBYTES + 4];
4268 #else
4269 char_u tb[4];
4270 #endif
4271 mapblock_T *mp;
4272 #ifdef FEAT_LOCALMAP
4273 mapblock_T *mp2;
4274 #endif
4275 #ifdef FEAT_MBYTE
4276 int clen = 0; /* length in characters */
4277 #endif
4278 int is_id = TRUE;
4279 int vim_abbr;
4281 if (typebuf.tb_no_abbr_cnt) /* abbrev. are not recursive */
4282 return FALSE;
4283 if ((KeyNoremap & (RM_NONE|RM_SCRIPT)) != 0)
4284 /* no remapping implies no abbreviation */
4285 return FALSE;
4288 * Check for word before the cursor: If it ends in a keyword char all
4289 * chars before it must be keyword chars or non-keyword chars, but not
4290 * white space. If it ends in a non-keyword char we accept any characters
4291 * before it except white space.
4293 if (col == 0) /* cannot be an abbr. */
4294 return FALSE;
4296 #ifdef FEAT_MBYTE
4297 if (has_mbyte)
4299 char_u *p;
4301 p = mb_prevptr(ptr, ptr + col);
4302 if (!vim_iswordp(p))
4303 vim_abbr = TRUE; /* Vim added abbr. */
4304 else
4306 vim_abbr = FALSE; /* vi compatible abbr. */
4307 if (p > ptr)
4308 is_id = vim_iswordp(mb_prevptr(ptr, p));
4310 clen = 1;
4311 while (p > ptr + mincol)
4313 p = mb_prevptr(ptr, p);
4314 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
4316 p += (*mb_ptr2len)(p);
4317 break;
4319 ++clen;
4321 scol = (int)(p - ptr);
4323 else
4324 #endif
4326 if (!vim_iswordc(ptr[col - 1]))
4327 vim_abbr = TRUE; /* Vim added abbr. */
4328 else
4330 vim_abbr = FALSE; /* vi compatible abbr. */
4331 if (col > 1)
4332 is_id = vim_iswordc(ptr[col - 2]);
4334 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
4335 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
4339 if (scol < mincol)
4340 scol = mincol;
4341 if (scol < col) /* there is a word in front of the cursor */
4343 ptr += scol;
4344 len = col - scol;
4345 #ifdef FEAT_LOCALMAP
4346 mp = curbuf->b_first_abbr;
4347 mp2 = first_abbr;
4348 if (mp == NULL)
4350 mp = mp2;
4351 mp2 = NULL;
4353 #else
4354 mp = first_abbr;
4355 #endif
4356 for ( ; mp;
4357 #ifdef FEAT_LOCALMAP
4358 mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
4359 #endif
4360 (mp = mp->m_next))
4362 /* find entries with right mode and keys */
4363 if ( (mp->m_mode & State)
4364 && mp->m_keylen == len
4365 && !STRNCMP(mp->m_keys, ptr, (size_t)len))
4366 break;
4368 if (mp != NULL)
4371 * Found a match:
4372 * Insert the rest of the abbreviation in typebuf.tb_buf[].
4373 * This goes from end to start.
4375 * Characters 0x000 - 0x100: normal chars, may need CTRL-V,
4376 * except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
4377 * Characters where IS_SPECIAL() == TRUE: key codes, need
4378 * K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
4380 * Character CTRL-] is treated specially - it completes the
4381 * abbreviation, but is not inserted into the input stream.
4383 j = 0;
4384 if (c != Ctrl_RSB)
4386 /* special key code, split up */
4387 if (IS_SPECIAL(c) || c == K_SPECIAL)
4389 tb[j++] = K_SPECIAL;
4390 tb[j++] = K_SECOND(c);
4391 tb[j++] = K_THIRD(c);
4393 else
4395 if (c < ABBR_OFF && (c < ' ' || c > '~'))
4396 tb[j++] = Ctrl_V; /* special char needs CTRL-V */
4397 #ifdef FEAT_MBYTE
4398 if (has_mbyte)
4400 /* if ABBR_OFF has been added, remove it here */
4401 if (c >= ABBR_OFF)
4402 c -= ABBR_OFF;
4403 j += (*mb_char2bytes)(c, tb + j);
4405 else
4406 #endif
4407 tb[j++] = c;
4409 tb[j] = NUL;
4410 /* insert the last typed char */
4411 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
4413 #ifdef FEAT_EVAL
4414 if (mp->m_expr)
4415 s = eval_map_expr(mp->m_str, c);
4416 else
4417 #endif
4418 s = mp->m_str;
4419 if (s != NULL)
4421 /* insert the to string */
4422 (void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
4423 /* no abbrev. for these chars */
4424 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
4425 #ifdef FEAT_EVAL
4426 if (mp->m_expr)
4427 vim_free(s);
4428 #endif
4431 tb[0] = Ctrl_H;
4432 tb[1] = NUL;
4433 #ifdef FEAT_MBYTE
4434 if (has_mbyte)
4435 len = clen; /* Delete characters instead of bytes */
4436 #endif
4437 while (len-- > 0) /* delete the from string */
4438 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
4439 return TRUE;
4442 return FALSE;
4445 #ifdef FEAT_EVAL
4447 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
4448 * special characters.
4450 static char_u *
4451 eval_map_expr(str, c)
4452 char_u *str;
4453 int c; /* NUL or typed character for abbreviation */
4455 char_u *res;
4456 char_u *p;
4457 char_u *save_cmd;
4458 pos_T save_cursor;
4460 save_cmd = save_cmdline_alloc();
4461 if (save_cmd == NULL)
4462 return NULL;
4464 /* Forbid changing text or using ":normal" to avoid most of the bad side
4465 * effects. Also restore the cursor position. */
4466 ++textlock;
4467 #ifdef FEAT_EX_EXTRA
4468 ++ex_normal_lock;
4469 #endif
4470 set_vim_var_char(c); /* set v:char to the typed character */
4471 save_cursor = curwin->w_cursor;
4472 p = eval_to_string(str, NULL, FALSE);
4473 --textlock;
4474 #ifdef FEAT_EX_EXTRA
4475 --ex_normal_lock;
4476 #endif
4477 curwin->w_cursor = save_cursor;
4479 restore_cmdline_alloc(save_cmd);
4480 if (p == NULL)
4481 return NULL;
4482 res = vim_strsave_escape_csi(p);
4483 vim_free(p);
4485 return res;
4487 #endif
4490 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
4491 * can be put in the typeahead buffer.
4492 * Returns NULL when out of memory.
4494 char_u *
4495 vim_strsave_escape_csi(p)
4496 char_u *p;
4498 char_u *res;
4499 char_u *s, *d;
4501 /* Need a buffer to hold up to three times as much. */
4502 res = alloc((unsigned)(STRLEN(p) * 3) + 1);
4503 if (res != NULL)
4505 d = res;
4506 for (s = p; *s != NUL; )
4508 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
4510 /* Copy special key unmodified. */
4511 *d++ = *s++;
4512 *d++ = *s++;
4513 *d++ = *s++;
4515 else
4517 /* Add character, possibly multi-byte to destination, escaping
4518 * CSI and K_SPECIAL. */
4519 d = add_char2buf(PTR2CHAR(s), d);
4520 mb_ptr_adv(s);
4523 *d = NUL;
4525 return res;
4529 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
4530 * vim_strsave_escape_csi(). Works in-place.
4532 void
4533 vim_unescape_csi(p)
4534 char_u *p;
4536 char_u *s = p, *d = p;
4538 while (*s != NUL)
4540 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
4542 *d++ = K_SPECIAL;
4543 s += 3;
4545 else if ((s[0] == K_SPECIAL || s[0] == CSI)
4546 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
4548 *d++ = CSI;
4549 s += 3;
4551 else
4552 *d++ = *s++;
4554 *d = NUL;
4558 * Write map commands for the current mappings to an .exrc file.
4559 * Return FAIL on error, OK otherwise.
4562 makemap(fd, buf)
4563 FILE *fd;
4564 buf_T *buf; /* buffer for local mappings or NULL */
4566 mapblock_T *mp;
4567 char_u c1, c2, c3;
4568 char_u *p;
4569 char *cmd;
4570 int abbr;
4571 int hash;
4572 int did_cpo = FALSE;
4573 int i;
4575 validate_maphash();
4578 * Do the loop twice: Once for mappings, once for abbreviations.
4579 * Then loop over all map hash lists.
4581 for (abbr = 0; abbr < 2; ++abbr)
4582 for (hash = 0; hash < 256; ++hash)
4584 if (abbr)
4586 if (hash > 0) /* there is only one abbr list */
4587 break;
4588 #ifdef FEAT_LOCALMAP
4589 if (buf != NULL)
4590 mp = buf->b_first_abbr;
4591 else
4592 #endif
4593 mp = first_abbr;
4595 else
4597 #ifdef FEAT_LOCALMAP
4598 if (buf != NULL)
4599 mp = buf->b_maphash[hash];
4600 else
4601 #endif
4602 mp = maphash[hash];
4605 for ( ; mp; mp = mp->m_next)
4607 /* skip script-local mappings */
4608 if (mp->m_noremap == REMAP_SCRIPT)
4609 continue;
4611 /* skip mappings that contain a <SNR> (script-local thing),
4612 * they probably don't work when loaded again */
4613 for (p = mp->m_str; *p != NUL; ++p)
4614 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
4615 && p[2] == (int)KE_SNR)
4616 break;
4617 if (*p != NUL)
4618 continue;
4620 /* It's possible to create a mapping and then ":unmap" certain
4621 * modes. We recreate this here by mapping the individual
4622 * modes, which requires up to three of them. */
4623 c1 = NUL;
4624 c2 = NUL;
4625 c3 = NUL;
4626 if (abbr)
4627 cmd = "abbr";
4628 else
4629 cmd = "map";
4630 switch (mp->m_mode)
4632 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
4633 break;
4634 case NORMAL:
4635 c1 = 'n';
4636 break;
4637 case VISUAL:
4638 c1 = 'x';
4639 break;
4640 case SELECTMODE:
4641 c1 = 's';
4642 break;
4643 case OP_PENDING:
4644 c1 = 'o';
4645 break;
4646 case NORMAL + VISUAL:
4647 c1 = 'n';
4648 c2 = 'x';
4649 break;
4650 case NORMAL + SELECTMODE:
4651 c1 = 'n';
4652 c2 = 's';
4653 break;
4654 case NORMAL + OP_PENDING:
4655 c1 = 'n';
4656 c2 = 'o';
4657 break;
4658 case VISUAL + SELECTMODE:
4659 c1 = 'v';
4660 break;
4661 case VISUAL + OP_PENDING:
4662 c1 = 'x';
4663 c2 = 'o';
4664 break;
4665 case SELECTMODE + OP_PENDING:
4666 c1 = 's';
4667 c2 = 'o';
4668 break;
4669 case NORMAL + VISUAL + SELECTMODE:
4670 c1 = 'n';
4671 c2 = 'v';
4672 break;
4673 case NORMAL + VISUAL + OP_PENDING:
4674 c1 = 'n';
4675 c2 = 'x';
4676 c3 = 'o';
4677 break;
4678 case NORMAL + SELECTMODE + OP_PENDING:
4679 c1 = 'n';
4680 c2 = 's';
4681 c3 = 'o';
4682 break;
4683 case VISUAL + SELECTMODE + OP_PENDING:
4684 c1 = 'v';
4685 c2 = 'o';
4686 break;
4687 case CMDLINE + INSERT:
4688 if (!abbr)
4689 cmd = "map!";
4690 break;
4691 case CMDLINE:
4692 c1 = 'c';
4693 break;
4694 case INSERT:
4695 c1 = 'i';
4696 break;
4697 case LANGMAP:
4698 c1 = 'l';
4699 break;
4700 default:
4701 EMSG(_("E228: makemap: Illegal mode"));
4702 return FAIL;
4704 do /* do this twice if c2 is set, 3 times with c3 */
4706 /* When outputting <> form, need to make sure that 'cpo'
4707 * is set to the Vim default. */
4708 if (!did_cpo)
4710 if (*mp->m_str == NUL) /* will use <Nop> */
4711 did_cpo = TRUE;
4712 else
4713 for (i = 0; i < 2; ++i)
4714 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
4715 if (*p == K_SPECIAL || *p == NL)
4716 did_cpo = TRUE;
4717 if (did_cpo)
4719 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
4720 || put_eol(fd) < 0
4721 || fprintf(fd, "set cpo&vim") < 0
4722 || put_eol(fd) < 0)
4723 return FAIL;
4726 if (c1 && putc(c1, fd) < 0)
4727 return FAIL;
4728 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
4729 return FAIL;
4730 if (fputs(cmd, fd) < 0)
4731 return FAIL;
4732 if (buf != NULL && fputs(" <buffer>", fd) < 0)
4733 return FAIL;
4734 if (mp->m_silent && fputs(" <silent>", fd) < 0)
4735 return FAIL;
4736 #ifdef FEAT_EVAL
4737 if (mp->m_noremap == REMAP_SCRIPT
4738 && fputs("<script>", fd) < 0)
4739 return FAIL;
4740 if (mp->m_expr && fputs(" <expr>", fd) < 0)
4741 return FAIL;
4742 #endif
4744 if ( putc(' ', fd) < 0
4745 || put_escstr(fd, mp->m_keys, 0) == FAIL
4746 || putc(' ', fd) < 0
4747 || put_escstr(fd, mp->m_str, 1) == FAIL
4748 || put_eol(fd) < 0)
4749 return FAIL;
4750 c1 = c2;
4751 c2 = c3;
4752 c3 = NUL;
4753 } while (c1 != NUL);
4757 if (did_cpo)
4758 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
4759 || put_eol(fd) < 0
4760 || fprintf(fd, "unlet s:cpo_save") < 0
4761 || put_eol(fd) < 0)
4762 return FAIL;
4763 return OK;
4767 * write escape string to file
4768 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
4770 * return FAIL for failure, OK otherwise
4773 put_escstr(fd, strstart, what)
4774 FILE *fd;
4775 char_u *strstart;
4776 int what;
4778 char_u *str = strstart;
4779 int c;
4780 int modifiers;
4782 /* :map xx <Nop> */
4783 if (*str == NUL && what == 1)
4785 if (fprintf(fd, "<Nop>") < 0)
4786 return FAIL;
4787 return OK;
4790 for ( ; *str != NUL; ++str)
4792 #ifdef FEAT_MBYTE
4793 char_u *p;
4795 /* Check for a multi-byte character, which may contain escaped
4796 * K_SPECIAL and CSI bytes */
4797 p = mb_unescape(&str);
4798 if (p != NULL)
4800 while (*p != NUL)
4801 if (fputc(*p++, fd) < 0)
4802 return FAIL;
4803 --str;
4804 continue;
4806 #endif
4808 c = *str;
4810 * Special key codes have to be translated to be able to make sense
4811 * when they are read back.
4813 if (c == K_SPECIAL && what != 2)
4815 modifiers = 0x0;
4816 if (str[1] == KS_MODIFIER)
4818 modifiers = str[2];
4819 str += 3;
4820 c = *str;
4822 if (c == K_SPECIAL)
4824 c = TO_SPECIAL(str[1], str[2]);
4825 str += 2;
4827 if (IS_SPECIAL(c) || modifiers) /* special key */
4829 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
4830 return FAIL;
4831 continue;
4836 * A '\n' in a map command should be written as <NL>.
4837 * A '\n' in a set command should be written as \^V^J.
4839 if (c == NL)
4841 if (what == 2)
4843 if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
4844 return FAIL;
4846 else
4848 if (fprintf(fd, "<NL>") < 0)
4849 return FAIL;
4851 continue;
4855 * Some characters have to be escaped with CTRL-V to
4856 * prevent them from misinterpreted in DoOneCmd().
4857 * A space, Tab and '"' has to be escaped with a backslash to
4858 * prevent it to be misinterpreted in do_set().
4859 * A space has to be escaped with a CTRL-V when it's at the start of a
4860 * ":map" rhs.
4861 * A '<' has to be escaped with a CTRL-V to prevent it being
4862 * interpreted as the start of a special key name.
4863 * A space in the lhs of a :map needs a CTRL-V.
4865 if (what == 2 && (vim_iswhite(c) || c == '"' || c == '\\'))
4867 if (putc('\\', fd) < 0)
4868 return FAIL;
4870 else if (c < ' ' || c > '~' || c == '|'
4871 || (what == 0 && c == ' ')
4872 || (what == 1 && str == strstart && c == ' ')
4873 || (what != 2 && c == '<'))
4875 if (putc(Ctrl_V, fd) < 0)
4876 return FAIL;
4878 if (putc(c, fd) < 0)
4879 return FAIL;
4881 return OK;
4885 * Check all mappings for the presence of special key codes.
4886 * Used after ":set term=xxx".
4888 void
4889 check_map_keycodes()
4891 mapblock_T *mp;
4892 char_u *p;
4893 int i;
4894 char_u buf[3];
4895 char_u *save_name;
4896 int abbr;
4897 int hash;
4898 #ifdef FEAT_LOCALMAP
4899 buf_T *bp;
4900 #endif
4902 validate_maphash();
4903 save_name = sourcing_name;
4904 sourcing_name = (char_u *)"mappings"; /* avoids giving error messages */
4906 #ifdef FEAT_LOCALMAP
4907 /* This this once for each buffer, and then once for global
4908 * mappings/abbreviations with bp == NULL */
4909 for (bp = firstbuf; ; bp = bp->b_next)
4911 #endif
4913 * Do the loop twice: Once for mappings, once for abbreviations.
4914 * Then loop over all map hash lists.
4916 for (abbr = 0; abbr <= 1; ++abbr)
4917 for (hash = 0; hash < 256; ++hash)
4919 if (abbr)
4921 if (hash) /* there is only one abbr list */
4922 break;
4923 #ifdef FEAT_LOCALMAP
4924 if (bp != NULL)
4925 mp = bp->b_first_abbr;
4926 else
4927 #endif
4928 mp = first_abbr;
4930 else
4932 #ifdef FEAT_LOCALMAP
4933 if (bp != NULL)
4934 mp = bp->b_maphash[hash];
4935 else
4936 #endif
4937 mp = maphash[hash];
4939 for ( ; mp != NULL; mp = mp->m_next)
4941 for (i = 0; i <= 1; ++i) /* do this twice */
4943 if (i == 0)
4944 p = mp->m_keys; /* once for the "from" part */
4945 else
4946 p = mp->m_str; /* and once for the "to" part */
4947 while (*p)
4949 if (*p == K_SPECIAL)
4951 ++p;
4952 if (*p < 128) /* for "normal" tcap entries */
4954 buf[0] = p[0];
4955 buf[1] = p[1];
4956 buf[2] = NUL;
4957 (void)add_termcap_entry(buf, FALSE);
4959 ++p;
4961 ++p;
4966 #ifdef FEAT_LOCALMAP
4967 if (bp == NULL)
4968 break;
4970 #endif
4971 sourcing_name = save_name;
4974 #ifdef FEAT_EVAL
4976 * Check the string "keys" against the lhs of all mappings
4977 * Return pointer to rhs of mapping (mapblock->m_str)
4978 * NULL otherwise
4980 char_u *
4981 check_map(keys, mode, exact, ign_mod, abbr)
4982 char_u *keys;
4983 int mode;
4984 int exact; /* require exact match */
4985 int ign_mod; /* ignore preceding modifier */
4986 int abbr; /* do abbreviations */
4988 int hash;
4989 int len, minlen;
4990 mapblock_T *mp;
4991 char_u *s;
4992 #ifdef FEAT_LOCALMAP
4993 int local;
4994 #endif
4996 validate_maphash();
4998 len = (int)STRLEN(keys);
4999 #ifdef FEAT_LOCALMAP
5000 for (local = 1; local >= 0; --local)
5001 #endif
5002 /* loop over all hash lists */
5003 for (hash = 0; hash < 256; ++hash)
5005 if (abbr)
5007 if (hash > 0) /* there is only one list. */
5008 break;
5009 #ifdef FEAT_LOCALMAP
5010 if (local)
5011 mp = curbuf->b_first_abbr;
5012 else
5013 #endif
5014 mp = first_abbr;
5016 #ifdef FEAT_LOCALMAP
5017 else if (local)
5018 mp = curbuf->b_maphash[hash];
5019 #endif
5020 else
5021 mp = maphash[hash];
5022 for ( ; mp != NULL; mp = mp->m_next)
5024 /* skip entries with wrong mode, wrong length and not matching
5025 * ones */
5026 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
5028 if (len > mp->m_keylen)
5029 minlen = mp->m_keylen;
5030 else
5031 minlen = len;
5032 s = mp->m_keys;
5033 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
5034 && s[2] != NUL)
5036 s += 3;
5037 if (len > mp->m_keylen - 3)
5038 minlen = mp->m_keylen - 3;
5040 if (STRNCMP(s, keys, minlen) == 0)
5041 return mp->m_str;
5046 return NULL;
5048 #endif
5050 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(MACOS)
5052 #define VIS_SEL (VISUAL+SELECTMODE) /* abbreviation */
5055 * Default mappings for some often used keys.
5057 static struct initmap
5059 char_u *arg;
5060 int mode;
5061 } initmappings[] =
5063 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5064 /* Use the Windows (CUA) keybindings. */
5065 # ifdef FEAT_GUI
5066 # if 0 /* These are now used to move tab pages */
5067 {(char_u *)"<C-PageUp> H", NORMAL+VIS_SEL},
5068 {(char_u *)"<C-PageUp> <C-O>H",INSERT},
5069 {(char_u *)"<C-PageDown> L$", NORMAL+VIS_SEL},
5070 {(char_u *)"<C-PageDown> <C-O>L<C-O>$", INSERT},
5071 # endif
5073 /* paste, copy and cut */
5074 {(char_u *)"<S-Insert> \"*P", NORMAL},
5075 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
5076 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
5077 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
5078 {(char_u *)"<S-Del> \"*d", VIS_SEL},
5079 {(char_u *)"<C-Del> \"*d", VIS_SEL},
5080 {(char_u *)"<C-X> \"*d", VIS_SEL},
5081 /* Missing: CTRL-C (cancel) and CTRL-V (block selection) */
5082 # else
5083 # if 0 /* These are now used to move tab pages */
5084 {(char_u *)"\316\204 H", NORMAL+VIS_SEL}, /* CTRL-PageUp is "H" */
5085 {(char_u *)"\316\204 \017H",INSERT}, /* CTRL-PageUp is "^OH"*/
5086 {(char_u *)"\316v L$", NORMAL+VIS_SEL}, /* CTRL-PageDown is "L$" */
5087 {(char_u *)"\316v \017L\017$", INSERT}, /* CTRL-PageDown ="^OL^O$"*/
5088 # endif
5089 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
5090 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
5091 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
5092 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
5094 /* paste, copy and cut */
5095 # ifdef FEAT_CLIPBOARD
5096 # ifdef DJGPP
5097 {(char_u *)"\316\122 \"*P", NORMAL}, /* SHIFT-Insert is "*P */
5098 {(char_u *)"\316\122 \"-d\"*P", VIS_SEL}, /* SHIFT-Insert is "-d"*P */
5099 {(char_u *)"\316\122 \022\017*", INSERT}, /* SHIFT-Insert is ^R^O* */
5100 {(char_u *)"\316\222 \"*y", VIS_SEL}, /* CTRL-Insert is "*y */
5101 # if 0 /* Shift-Del produces the same code as Del */
5102 {(char_u *)"\316\123 \"*d", VIS_SEL}, /* SHIFT-Del is "*d */
5103 # endif
5104 {(char_u *)"\316\223 \"*d", VIS_SEL}, /* CTRL-Del is "*d */
5105 {(char_u *)"\030 \"-d", VIS_SEL}, /* CTRL-X is "-d */
5106 # else
5107 {(char_u *)"\316\324 \"*P", NORMAL}, /* SHIFT-Insert is "*P */
5108 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, /* SHIFT-Insert is "-d"*P */
5109 {(char_u *)"\316\324 \022\017*", INSERT}, /* SHIFT-Insert is ^R^O* */
5110 {(char_u *)"\316\325 \"*y", VIS_SEL}, /* CTRL-Insert is "*y */
5111 {(char_u *)"\316\327 \"*d", VIS_SEL}, /* SHIFT-Del is "*d */
5112 {(char_u *)"\316\330 \"*d", VIS_SEL}, /* CTRL-Del is "*d */
5113 {(char_u *)"\030 \"-d", VIS_SEL}, /* CTRL-X is "-d */
5114 # endif
5115 # else
5116 {(char_u *)"\316\324 P", NORMAL}, /* SHIFT-Insert is P */
5117 {(char_u *)"\316\324 \"-dP", VIS_SEL}, /* SHIFT-Insert is "-dP */
5118 {(char_u *)"\316\324 \022\017\"", INSERT}, /* SHIFT-Insert is ^R^O" */
5119 {(char_u *)"\316\325 y", VIS_SEL}, /* CTRL-Insert is y */
5120 {(char_u *)"\316\327 d", VIS_SEL}, /* SHIFT-Del is d */
5121 {(char_u *)"\316\330 d", VIS_SEL}, /* CTRL-Del is d */
5122 # endif
5123 # endif
5124 #endif
5126 #if defined(MACOS)
5127 /* Use the Standard MacOS binding. */
5128 /* paste, copy and cut */
5129 {(char_u *)"<D-v> \"*P", NORMAL},
5130 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
5131 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
5132 {(char_u *)"<D-c> \"*y", VIS_SEL},
5133 {(char_u *)"<D-x> \"*d", VIS_SEL},
5134 {(char_u *)"<Backspace> \"-d", VIS_SEL},
5135 #endif
5138 # undef VIS_SEL
5139 #endif
5142 * Set up default mappings.
5144 void
5145 init_mappings()
5147 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(MACOS)
5148 int i;
5150 for (i = 0; i < sizeof(initmappings) / sizeof(struct initmap); ++i)
5151 add_map(initmappings[i].arg, initmappings[i].mode);
5152 #endif
5155 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) \
5156 || defined(FEAT_CMDWIN) || defined(MACOS) || defined(PROTO)
5158 * Add a mapping "map" for mode "mode".
5159 * Need to put string in allocated memory, because do_map() will modify it.
5161 void
5162 add_map(map, mode)
5163 char_u *map;
5164 int mode;
5166 char_u *s;
5167 char_u *cpo_save = p_cpo;
5169 p_cpo = (char_u *)""; /* Allow <> notation */
5170 s = vim_strsave(map);
5171 if (s != NULL)
5173 (void)do_map(0, s, mode, FALSE);
5174 vim_free(s);
5176 p_cpo = cpo_save;
5178 #endif