diff --git a/contrib/uncrustify.cfg b/contrib/uncrustify.cfg index d984484391..93b64a30a5 100644 --- a/contrib/uncrustify.cfg +++ b/contrib/uncrustify.cfg @@ -184,7 +184,7 @@ sp_paren_brace = ignore # ignore/add/remove/force/not_defined sp_brace_brace = ignore # ignore/add/remove/force/not_defined # Add or remove space before pointer star '*'. -sp_before_ptr_star = ignore # ignore/add/remove/force/not_defined +sp_before_ptr_star = force # ignore/add/remove/force/not_defined # Add or remove space before pointer star '*' that isn't followed by a # variable name. If set to ignore, sp_before_ptr_star is used instead. @@ -3279,5 +3279,5 @@ set PREPROC REAL_FATTR_CONST set PREPROC REAL_FATTR_NONNULL_ALL set PREPROC REAL_FATTR_PURE set PREPROC REAL_FATTR_WARN_UNUSED_RESULT -# option(s) with 'not default' value: 58 +# option(s) with 'not default' value: 59 # diff --git a/src/nvim/edit.c b/src/nvim/edit.c index ffe60ab043..8216987635 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -6,60 +6,60 @@ */ #include -#include #include #include +#include -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/edit.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" #include "nvim/digraph.h" +#include "nvim/edit.h" #include "nvim/eval.h" #include "nvim/eval/typval.h" +#include "nvim/event/loop.h" #include "nvim/ex_docmd.h" #include "nvim/ex_getln.h" +#include "nvim/extmark.h" #include "nvim/fileio.h" #include "nvim/fold.h" #include "nvim/getchar.h" #include "nvim/indent.h" #include "nvim/indent_c.h" +#include "nvim/keymap.h" #include "nvim/main.h" -#include "nvim/extmark.h" +#include "nvim/mark.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/keymap.h" +#include "nvim/mouse.h" #include "nvim/move.h" #include "nvim/normal.h" #include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/time.h" #include "nvim/path.h" -#include "nvim/popupmnu.h" #include "nvim/plines.h" +#include "nvim/popupmnu.h" #include "nvim/quickfix.h" #include "nvim/regexp.h" #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/spell.h" -#include "nvim/strings.h" #include "nvim/state.h" +#include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/tag.h" -#include "nvim/ui.h" -#include "nvim/mouse.h" #include "nvim/terminal.h" +#include "nvim/ui.h" #include "nvim/undo.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/event/loop.h" -#include "nvim/mark.h" -#include "nvim/os/input.h" -#include "nvim/os/time.h" // Definitions used for CTRL-X submode. // Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] @@ -140,13 +140,13 @@ static char e_compldel[] = N_("E840: Completion function deleted text"); */ typedef struct compl_S compl_T; struct compl_S { - compl_T *cp_next; - compl_T *cp_prev; - char_u *cp_str; // matched text - char_u *(cp_text[CPT_COUNT]); // text for the menu + compl_T *cp_next; + compl_T *cp_prev; + char_u *cp_str; // matched text + char_u *(cp_text[CPT_COUNT]); // text for the menu typval_T cp_user_data; - char_u *cp_fname; // file containing the match, allocated when - // cp_flags has CP_FREE_FNAME + char_u *cp_fname; // file containing the match, allocated when + // cp_flags has CP_FREE_FNAME int cp_flags; // CP_ values int cp_number; // sequence number }; @@ -158,10 +158,10 @@ struct compl_S { * "compl_shown_match" is different from compl_curr_match during * ins_compl_get_exp(). */ -static compl_T *compl_first_match = NULL; -static compl_T *compl_curr_match = NULL; -static compl_T *compl_shown_match = NULL; -static compl_T *compl_old_match = NULL; +static compl_T *compl_first_match = NULL; +static compl_T *compl_curr_match = NULL; +static compl_T *compl_shown_match = NULL; +static compl_T *compl_old_match = NULL; /* After using a cursor key selects a match in the popup menu, * otherwise it inserts a line break. */ @@ -169,7 +169,7 @@ static int compl_enter_selects = FALSE; /* When "compl_leader" is not NULL only matches that start with this string * are used. */ -static char_u *compl_leader = NULL; +static char_u *compl_leader = NULL; static int compl_get_longest = FALSE; /* put longest common string in compl_leader */ @@ -196,15 +196,15 @@ static bool compl_started = false; static int ctrl_x_mode = CTRL_X_NORMAL; static int compl_matches = 0; -static char_u *compl_pattern = NULL; +static char_u *compl_pattern = NULL; static Direction compl_direction = FORWARD; static Direction compl_shows_dir = FORWARD; static int compl_pending = 0; // > 1 for postponed CTRL-N static pos_T compl_startpos; static colnr_T compl_col = 0; /* column where the text starts * that is being completed */ -static char_u *compl_orig_text = NULL; /* text as it was before - * completion started */ +static char_u *compl_orig_text = NULL; /* text as it was before + * completion started */ static int compl_cont_mode = 0; static expand_T compl_xp; @@ -257,8 +257,8 @@ static colnr_T Insstart_textlen; // length of line when insert started static colnr_T Insstart_blank_vcol; // vcol for first inserted blank static bool update_Insstart_orig = true; // set Insstart_orig to Insstart -static char_u *last_insert = NULL; // the text of the previous insert, - // K_SPECIAL and CSI are escaped +static char_u *last_insert = NULL; // the text of the previous insert, + // K_SPECIAL and CSI are escaped static int last_insert_skip; // nr of chars in front of previous insert static int new_insert_skip; // nr of chars in front of current insert static int did_restart_edit; // "restart_edit" when calling edit() @@ -310,7 +310,7 @@ static void insert_enter(InsertState *s) s->ptr = (char_u *)"i"; } - set_vim_var_string(VV_INSERTMODE, (char *) s->ptr, 1); + set_vim_var_string(VV_INSERTMODE, (char *)s->ptr, 1); set_vim_var_string(VV_CHAR, NULL, -1); ins_apply_autocmds(EVENT_INSERTENTER); @@ -791,15 +791,22 @@ static int insert_execute(VimState *state, int key) } } - if (curwin->w_p_rl) + if (curwin->w_p_rl) { switch (s->c) { - case K_LEFT: s->c = K_RIGHT; break; - case K_S_LEFT: s->c = K_S_RIGHT; break; - case K_C_LEFT: s->c = K_C_RIGHT; break; - case K_RIGHT: s->c = K_LEFT; break; - case K_S_RIGHT: s->c = K_S_LEFT; break; - case K_C_RIGHT: s->c = K_C_LEFT; break; + case K_LEFT: + s->c = K_RIGHT; break; + case K_S_LEFT: + s->c = K_S_RIGHT; break; + case K_C_LEFT: + s->c = K_C_RIGHT; break; + case K_RIGHT: + s->c = K_LEFT; break; + case K_S_RIGHT: + s->c = K_S_LEFT; break; + case K_C_RIGHT: + s->c = K_C_LEFT; break; } + } // If 'keymodel' contains "startsel", may start selection. If it // does, a CTRL-O and c will be stuffed, we need to get these @@ -1288,8 +1295,9 @@ normalchar: // If the new value is already inserted or an empty string // then don't insert any character. - if (s->c == NUL) + if (s->c == NUL) { break; + } } // Try to perform smart-indenting. ins_try_si(s->c); @@ -1309,8 +1317,8 @@ normalchar: // special character. Let CTRL-] expand abbreviations without // inserting it. if (vim_iswordc(s->c) - // Add ABBR_OFF for characters above 0x100, this is - // what check_abbr() expects. + // Add ABBR_OFF for characters above 0x100, this is + // what check_abbr() expects. || (!echeck_abbr((s->c >= 0x100) ? (s->c + ABBR_OFF) : s->c) && s->c != Ctrl_RSB)) { insert_special(s->c, false, false); @@ -1415,21 +1423,20 @@ bool edit(int cmdchar, bool startln, long count) return s->c == Ctrl_O; } -/* - * Redraw for Insert mode. - * This is postponed until getting the next character to make '$' in the 'cpo' - * option work correctly. - * Only redraw when there are no characters available. This speeds up - * inserting sequences of characters (e.g., for CTRL-R). - */ -static void ins_redraw( - bool ready // not busy with something -) +/// Redraw for Insert mode. +/// This is postponed until getting the next character to make '$' in the 'cpo' +/// option work correctly. +/// Only redraw when there are no characters available. This speeds up +/// inserting sequences of characters (e.g., for CTRL-R). +/// +/// @param ready not busy with something +static void ins_redraw(bool ready) { bool conceal_cursor_moved = false; - if (char_avail()) + if (char_avail()) { return; + } // Trigger CursorMoved if the cursor moved. Not when the popup menu is // visible, the command might delete it. @@ -1655,8 +1662,8 @@ static void init_prompt(int cmdchar_todo) /// @return true if the cursor is in the editable position of the prompt line. bool prompt_curpos_editable(void) { - return curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count - && curwin->w_cursor.col >= (int)STRLEN(prompt_text()); + return curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count + && curwin->w_cursor.col >= (int)STRLEN(prompt_text()); } /* @@ -1685,8 +1692,9 @@ void display_dollar(colnr_T col) { colnr_T save_col; - if (!redrawing()) + if (!redrawing()) { return; + } save_col = curwin->w_cursor.col; curwin->w_cursor.col = col; @@ -1714,34 +1722,28 @@ static void undisplay_dollar(void) } } -/* - * Insert an indent (for or CTRL-T) or delete an indent (for CTRL-D). - * Keep the cursor on the same character. - * type == INDENT_INC increase indent (for CTRL-T or ) - * type == INDENT_DEC decrease indent (for CTRL-D) - * type == INDENT_SET set indent to "amount" - * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec). - */ -void -change_indent ( - int type, - int amount, - int round, - int replaced, // replaced character, put on replace stack - int call_changed_bytes // call changed_bytes() -) +/// Insert an indent (for or CTRL-T) or delete an indent (for CTRL-D). +/// Keep the cursor on the same character. +/// type == INDENT_INC increase indent (for CTRL-T or ) +/// type == INDENT_DEC decrease indent (for CTRL-D) +/// type == INDENT_SET set indent to "amount" +/// +/// @param round if TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec). +/// @param replaced replaced character, put on replace stack +/// @param call_changed_bytes call changed_bytes() +void change_indent(int type, int amount, int round, int replaced, int call_changed_bytes) { int vcol; int last_vcol; int insstart_less; // reduction for Insstart.col int new_cursor_col; int i; - char_u *ptr; + char_u *ptr; int save_p_list; int start_col; colnr_T vc; colnr_T orig_col = 0; // init for GCC - char_u *new_line, *orig_line = NULL; // init for GCC + char_u *new_line, *orig_line = NULL; // init for GCC // VREPLACE mode needs to know what the line was like before changing if (State & VREPLACE_FLAG) { @@ -1773,8 +1775,9 @@ change_indent ( * If the cursor is in the indent, compute how many screen columns the * cursor is to the left of the first non-blank. */ - if (new_cursor_col < 0) + if (new_cursor_col < 0) { vcol = get_indent() - vcol; + } if (new_cursor_col > 0) { // can't fix replace stack start_col = -1; @@ -1783,9 +1786,9 @@ change_indent ( /* * Set the new indent. The cursor will be put on the first non-blank. */ - if (type == INDENT_SET) + if (type == INDENT_SET) { (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); - else { + } else { int save_State = State; // Avoid being called recursively. @@ -1811,12 +1814,13 @@ change_indent ( * When changing the indent while the cursor is touching it, reset * Insstart_col to 0. */ - if (new_cursor_col == 0) + if (new_cursor_col == 0) { insstart_less = MAXCOL; + } new_cursor_col += curwin->w_cursor.col; - } else if (!(State & INSERT)) + } else if (!(State & INSERT)) { new_cursor_col = curwin->w_cursor.col; - else { + } else { /* * Compute the screen column where the cursor should be. */ @@ -1863,10 +1867,11 @@ change_indent ( curwin->w_p_list = save_p_list; - if (new_cursor_col <= 0) + if (new_cursor_col <= 0) { curwin->w_cursor.col = 0; - else + } else { curwin->w_cursor.col = (colnr_T)new_cursor_col; + } curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); @@ -1875,15 +1880,17 @@ change_indent ( */ if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { - if ((int)Insstart.col <= insstart_less) + if ((int)Insstart.col <= insstart_less) { Insstart.col = 0; - else + } else { Insstart.col -= insstart_less; + } } - if ((int)ai_col <= insstart_less) + if ((int)ai_col <= insstart_less) { ai_col = 0; - else + } else { ai_col -= insstart_less; + } } /* @@ -1975,10 +1982,11 @@ void backspace_until_column(int col) { while ((int)curwin->w_cursor.col > col) { curwin->w_cursor.col--; - if (State & REPLACE_FLAG) + if (State & REPLACE_FLAG) { replace_do_bs(col); - else if (!del_char_after_col(col)) + } else if (!del_char_after_col(col)) { break; + } } } @@ -2025,10 +2033,11 @@ static void ins_ctrl_x(void) if (ctrl_x_mode != CTRL_X_CMDLINE) { /* if the next ^X<> won't ADD nothing, then reset * compl_cont_status */ - if (compl_cont_status & CONT_N_ADDS) + if (compl_cont_status & CONT_N_ADDS) { compl_cont_status |= CONT_INTRPT; - else + } else { compl_cont_status = 0; + } // We're not sure which CTRL-X mode it will be yet ctrl_x_mode = CTRL_X_NOT_DEFINED_YET; edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); @@ -2172,8 +2181,8 @@ static bool ins_compl_accept_char(int c) /// the rest of the word to be in -- webb /// /// @param[in] cont_s_ipos next ^X<> will set initial_pos -int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, - Direction dir, bool cont_s_ipos) +int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, Direction dir, + bool cont_s_ipos) FUNC_ATTR_NONNULL_ARG(1) { char_u *str = str_arg; @@ -2316,15 +2325,12 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, /// @return NOTDONE if the given string is already in the list of completions, /// otherwise it is added to the list and OK is returned. FAIL will be /// returned in case of error. -static int ins_compl_add(char_u *const str, int len, - char_u *const fname, - char_u *const *const cptext, - const bool cptext_allocated, - typval_T *user_data, - const Direction cdir, int flags_arg, const bool adup) +static int ins_compl_add(char_u *const str, int len, char_u *const fname, + char_u *const *const cptext, const bool cptext_allocated, + typval_T *user_data, const Direction cdir, int flags_arg, const bool adup) FUNC_ATTR_NONNULL_ARG(1) { - compl_T *match; + compl_T *match; const Direction dir = (cdir == kDirectionNotSet ? compl_direction : cdir); int flags = flags_arg; @@ -2420,9 +2426,9 @@ static int ins_compl_add(char_u *const str, int len, /* * Link the new match structure in the list of matches. */ - if (compl_first_match == NULL) + if (compl_first_match == NULL) { match->cp_next = match->cp_prev = NULL; - else if (dir == FORWARD) { + } else if (dir == FORWARD) { match->cp_next = compl_curr_match->cp_next; match->cp_prev = compl_curr_match; } else { // BACKWARD @@ -2472,7 +2478,7 @@ static bool ins_compl_equal(compl_T *match, char_u *str, size_t len) */ static void ins_compl_longest_match(compl_T *match) { - char_u *p, *s; + char_u *p, *s; int c1, c2; int had_match; @@ -2486,8 +2492,9 @@ static void ins_compl_longest_match(compl_T *match) /* When the match isn't there (to avoid matching itself) remove it * again after redrawing. */ - if (!had_match) + if (!had_match) { ins_compl_delete(); + } compl_used_match = false; } else { // Reduce the text if this match differs from compl_leader. @@ -2516,8 +2523,9 @@ static void ins_compl_longest_match(compl_T *match) /* When the match isn't there (to avoid matching itself) remove it * again after redrawing. */ - if (!had_match) + if (!had_match) { ins_compl_delete(); + } } compl_used_match = false; @@ -2601,8 +2609,9 @@ void set_completion(colnr_T startcol, list_T *list) ins_compl_free(); compl_direction = FORWARD; - if (startcol > curwin->w_cursor.col) + if (startcol > curwin->w_cursor.col) { startcol = curwin->w_cursor.col; + } compl_col = startcol; compl_length = (int)curwin->w_cursor.col - (int)startcol; // compl_pattern doesn't need to be set @@ -2725,8 +2734,8 @@ static void trigger_complete_changed_event(int cur) /// Also adjusts "compl_shown_match" to an entry that is actually displayed. void ins_compl_show_pum(void) { - compl_T *compl; - compl_T *shown_compl = NULL; + compl_T *compl; + compl_T *shown_compl = NULL; bool did_find_shown_match = false; bool shown_match_ok = false; int i; @@ -2735,8 +2744,9 @@ void ins_compl_show_pum(void) int lead_len = 0; bool array_changed = false; - if (!pum_wanted() || !pum_enough_matches()) + if (!pum_wanted() || !pum_enough_matches()) { return; + } // Dirty hard-coded hack: remove any matchparen highlighting. do_cmdline_cmd("if exists('g:loaded_matchparen')|3match none|endif"); @@ -2767,8 +2777,9 @@ void ins_compl_show_pum(void) } compl = compl->cp_next; } while (compl != NULL && compl != compl_first_match); - if (compl_match_arraysize == 0) + if (compl_match_arraysize == 0) { return; + } assert(compl_match_arraysize >= 0); compl_match_array = xcalloc(compl_match_arraysize, sizeof(pumitem_T)); @@ -2799,18 +2810,20 @@ void ins_compl_show_pum(void) cur = i; } - if (compl->cp_text[CPT_ABBR] != NULL) + if (compl->cp_text[CPT_ABBR] != NULL) { compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR]; - else + } else { compl_match_array[i].pum_text = compl->cp_str; + } compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND]; compl_match_array[i].pum_info = compl->cp_text[CPT_INFO]; - if (compl->cp_text[CPT_MENU] != NULL) + if (compl->cp_text[CPT_MENU] != NULL) { compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU]; - else + } else { compl_match_array[i++].pum_extra = compl->cp_fname; + } } if (compl == compl_shown_match) { @@ -2867,23 +2880,18 @@ void ins_compl_show_pum(void) #define DICT_FIRST (1) // use just first element in "dict" #define DICT_EXACT (2) // "dict" is the exact name of a file -/* - * Add any identifiers that match the given pattern in the list of dictionary - * files "dict_start" to the list of completions. - */ -static void -ins_compl_dictionaries ( - char_u *dict_start, - char_u *pat, - int flags, // DICT_FIRST and/or DICT_EXACT - int thesaurus // Thesaurus completion -) +/// Add any identifiers that match the given pattern in the list of dictionary +/// files "dict_start" to the list of completions. +/// +/// @param flags DICT_FIRST and/or DICT_EXACT +/// @param thesaurus Thesaurus completion +static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, int thesaurus) { - char_u *dict = dict_start; - char_u *ptr; - char_u *buf; + char_u *dict = dict_start; + char_u *ptr; + char_u *buf; regmatch_T regmatch; - char_u **files; + char_u **files; int count; int save_p_scs; Direction dir = compl_direction; @@ -2891,10 +2899,11 @@ ins_compl_dictionaries ( if (*dict == NUL) { /* When 'dictionary' is empty and spell checking is enabled use * "spell". */ - if (!thesaurus && curwin->w_p_spell) + if (!thesaurus && curwin->w_p_spell) { dict = (char_u *)"spell"; - else + } else { return; + } } buf = xmalloc(LSIZE); @@ -2902,8 +2911,9 @@ ins_compl_dictionaries ( // If 'infercase' is set, don't use 'smartcase' here save_p_scs = p_scs; - if (curbuf->b_p_inf) + if (curbuf->b_p_inf) { p_scs = FALSE; + } /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern * to only match at the start of a line. Otherwise just match the @@ -2919,8 +2929,9 @@ ins_compl_dictionaries ( xfree(ptr); } else { regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); - if (regmatch.regprog == NULL) + if (regmatch.regprog == NULL) { goto theend; + } } // ignore case depends on 'ignorecase', 'smartcase' and "pat" @@ -2935,30 +2946,34 @@ ins_compl_dictionaries ( * backticks (for security, the 'dict' option may have been set in * a modeline). */ copy_option_part(&dict, buf, LSIZE, ","); - if (!thesaurus && STRCMP(buf, "spell") == 0) + if (!thesaurus && STRCMP(buf, "spell") == 0) { count = -1; - else if (vim_strchr(buf, '`') != NULL - || expand_wildcards(1, &buf, &count, &files, - EW_FILE|EW_SILENT) != OK) + } else if (vim_strchr(buf, '`') != NULL + || expand_wildcards(1, &buf, &count, &files, + EW_FILE|EW_SILENT) != OK) { count = 0; + } } if (count == -1) { /* Complete from active spelling. Skip "\<" in the pattern, we * don't use it as a RE. */ - if (pat[0] == '\\' && pat[1] == '<') + if (pat[0] == '\\' && pat[1] == '<') { ptr = pat + 2; - else + } else { ptr = pat; + } spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0); } else if (count > 0) { // avoid warning for using "files" uninit ins_compl_files(count, files, thesaurus, flags, - ®match, buf, &dir); - if (flags != DICT_EXACT) + ®match, buf, &dir); + if (flags != DICT_EXACT) { FreeWild(count, files); + } } - if (flags != 0) + if (flags != 0) { break; + } } theend: @@ -2967,14 +2982,13 @@ theend: xfree(buf); } -static void ins_compl_files(int count, char_u **files, int thesaurus, - int flags, regmatch_T *regmatch, char_u *buf, - Direction *dir) +static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, + regmatch_T *regmatch, char_u *buf, Direction *dir) FUNC_ATTR_NONNULL_ARG(2, 7) { - char_u *ptr; + char_u *ptr; int i; - FILE *fp; + FILE *fp; int add_r; for (i = 0; i < count && !got_int && !compl_interrupted; i++) { @@ -3017,8 +3031,9 @@ static void ins_compl_files(int count, char_u **files, int thesaurus, /* Find start of the next word. Skip white * space and punctuation. */ ptr = find_word_start(ptr); - if (*ptr == NUL || *ptr == NL) + if (*ptr == NUL || *ptr == NL) { break; + } wstart = ptr; // Find end of the word. @@ -3096,11 +3111,12 @@ char_u *find_word_end(char_u *ptr) */ static char_u *find_line_end(char_u *ptr) { - char_u *s; + char_u *s; s = ptr + STRLEN(ptr); - while (s > ptr && (s[-1] == CAR || s[-1] == NL)) + while (s > ptr && (s[-1] == CAR || s[-1] == NL)) { --s; + } return s; } @@ -3114,8 +3130,9 @@ static void ins_compl_free(void) XFREE_CLEAR(compl_pattern); XFREE_CLEAR(compl_leader); - if (compl_first_match == NULL) + if (compl_first_match == NULL) { return; + } ins_compl_del_pum(); pum_clear(); @@ -3277,9 +3294,9 @@ void get_complete_info(list_T *what_list, dict_T *retdict) tv_dict_add_str(di, S_LEN("info"), (char *)EMPTY_IF_NULL(match->cp_text[CPT_INFO])); if (match->cp_user_data.v_type == VAR_UNKNOWN) { - tv_dict_add_str(di, S_LEN("user_data"), ""); + tv_dict_add_str(di, S_LEN("user_data"), ""); } else { - tv_dict_add_tv(di, S_LEN("user_data"), &match->cp_user_data); + tv_dict_add_tv(di, S_LEN("user_data"), &match->cp_user_data); } } match = match->cp_next; @@ -3319,8 +3336,8 @@ static char_u * ins_compl_mode(void) */ static int ins_compl_bs(void) { - char_u *line; - char_u *p; + char_u *line; + char_u *p; line = get_cursor_line_ptr(); p = line + curwin->w_cursor.col; @@ -3340,8 +3357,9 @@ static int ins_compl_bs(void) /* Deleted more than what was used to find matches or didn't finish * finding all matches: need to look for matches all over again. */ if (curwin->w_cursor.col <= compl_col + compl_length - || ins_compl_need_restart()) + || ins_compl_need_restart()) { ins_compl_restart(); + } xfree(compl_leader); compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col); @@ -3398,8 +3416,9 @@ static void ins_compl_new_leader(void) /* Don't let Enter select the original text when there is no popup menu. * Don't let Enter select when use user function and refresh_always is set */ - if (compl_match_array == NULL || ins_compl_need_restart()) + if (compl_match_array == NULL || ins_compl_need_restart()) { compl_enter_selects = FALSE; + } } /* @@ -3410,8 +3429,9 @@ static int ins_compl_len(void) { int off = (int)curwin->w_cursor.col - (int)compl_col; - if (off < 0) + if (off < 0) { return 0; + } return off; } @@ -3424,7 +3444,7 @@ static void ins_compl_addleader(int c) int cc; if (stop_arrow() == FAIL) { - return; + return; } if ((cc = utf_char2len(c)) > 1) { char_u buf[MB_MAXBYTES + 1]; @@ -3489,10 +3509,10 @@ static void ins_compl_set_original_text(char_u *str) */ static void ins_compl_addfrommatch(void) { - char_u *p; + char_u *p; int len = (int)curwin->w_cursor.col - (int)compl_col; int c; - compl_T *cp; + compl_T *cp; assert(compl_shown_match != NULL); p = compl_shown_match->cp_str; if ((int)STRLEN(p) <= len) { // the match is too short @@ -3504,15 +3524,17 @@ static void ins_compl_addfrommatch(void) && cp != compl_first_match; cp = cp->cp_next) { if (compl_leader == NULL || ins_compl_equal(cp, compl_leader, - (int)STRLEN(compl_leader))) { + (int)STRLEN(compl_leader))) { p = cp->cp_str; break; } } - if (p == NULL || (int)STRLEN(p) <= len) + if (p == NULL || (int)STRLEN(p) <= len) { return; - } else + } + } else { return; + } } p += len; c = PTR2CHAR(p); @@ -3534,8 +3556,9 @@ static bool ins_compl_prep(int c) /* Forget any previous 'special' messages if this is actually * a ^X mode key - bar ^R, in which case we wait to see what it gives us. */ - if (c != Ctrl_R && vim_is_ctrl_x_key(c)) + if (c != Ctrl_R && vim_is_ctrl_x_key(c)) { edit_submode_extra = NULL; + } // Ignore end of Select mode mapping and mouse scroll buttons. if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP @@ -3560,10 +3583,11 @@ static bool ins_compl_prep(int c) case Ctrl_E: case Ctrl_Y: ctrl_x_mode = CTRL_X_SCROLL; - if (!(State & REPLACE_FLAG)) + if (!(State & REPLACE_FLAG)) { edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)"); - else + } else { edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)"); + } edit_submode_pre = NULL; showmode(); break; @@ -3618,10 +3642,11 @@ static bool ins_compl_prep(int c) * ^X^F^X^P or ^P^X^X^P, see below) * nothing changes if interrupting mode 0, (eg, the flag * doesn't change when going to ADDING mode -- Acevedo */ - if (!(compl_cont_status & CONT_INTRPT)) + if (!(compl_cont_status & CONT_INTRPT)) { compl_cont_status |= CONT_LOCAL; - else if (compl_cont_mode != 0) + } else if (compl_cont_mode != 0) { compl_cont_status &= ~CONT_LOCAL; + } FALLTHROUGH; default: /* If we have typed at least 2 ^X's... for modes != 0, we set @@ -3635,10 +3660,11 @@ static bool ins_compl_prep(int c) * In mode 0 an extra ^X is needed since ^X^P goes to ADDING * mode -- Acevedo */ if (c == Ctrl_X) { - if (compl_cont_mode != 0) + if (compl_cont_mode != 0) { compl_cont_status = 0; - else + } else { compl_cont_mode = CTRL_X_NOT_DEFINED_YET; + } } ctrl_x_mode = CTRL_X_NORMAL; edit_submode = NULL; @@ -3681,10 +3707,11 @@ static bool ins_compl_prep(int c) * When using the longest match, edited the match or used * CTRL-E then don't use the current match. */ - if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) + if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) { ptr = compl_curr_match->cp_str; - else + } else { ptr = NULL; + } ins_compl_fixRedoBufForLeader(ptr); } @@ -3766,16 +3793,18 @@ static bool ins_compl_prep(int c) /* * Indent now if a key was typed that is in 'cinkeys'. */ - if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0))) + if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0))) { do_c_expr_indent(); + } // Trigger the CompleteDone event to give scripts a chance to act // upon the end of completion. ins_apply_autocmds(EVENT_COMPLETEDONE); } - } else if (ctrl_x_mode == CTRL_X_LOCAL_MSG) + } else if (ctrl_x_mode == CTRL_X_LOCAL_MSG) { /* Trigger the CompleteDone event to give scripts a chance to act * upon the (possibly failed) completion. */ ins_apply_autocmds(EVENT_COMPLETEDONE); + } /* reset continue_* if we left expansion-mode, if we stay they'll be * (re)set properly in ins_complete() */ @@ -3795,8 +3824,8 @@ static bool ins_compl_prep(int c) static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) { int len; - char_u *p; - char_u *ptr = ptr_arg; + char_u *p; + char_u *ptr = ptr_arg; if (ptr == NULL) { if (compl_leader != NULL) { @@ -3823,7 +3852,7 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) /* * Loops through the list of windows, loaded-buffers or non-loaded-buffers * (depending on flag) starting from buf and looking for a non-scanned - * buffer (other than curbuf). curbuf is special, if it is called with + * buffer (other than curbuf). curbuf is special, if it is called with * buf=curbuf then it has to be the first call for a given flag/expansion. * * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo @@ -3838,10 +3867,11 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) } assert(wp); while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin - && wp->w_buffer->b_scanned) + && wp->w_buffer->b_scanned) { ; + } buf = wp->w_buffer; - } else + } else { /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U' * (unlisted buffers) * When completing whole lines skip unloaded buffers. */ @@ -3850,19 +3880,19 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) ? buf->b_p_bl : (!buf->b_p_bl || (buf->b_ml.ml_mfp == NULL) != (flag == 'u'))) - || buf->b_scanned)) + || buf->b_scanned)) { ; + } + } return buf; } -// Execute user defined complete function 'completefunc' or 'omnifunc', and -// get matches in "matches". -static void -expand_by_function( - int type, // CTRL_X_OMNI or CTRL_X_FUNCTION - char_u *base -) +/// Execute user defined complete function 'completefunc' or 'omnifunc', and +/// get matches in "matches". +/// +/// @param type CTRL_X_OMNI or CTRL_X_FUNCTION +static void expand_by_function(int type, char_u *base) { list_T *matchlist = NULL; dict_T *matchdict = NULL; @@ -3920,10 +3950,11 @@ expand_by_function( goto theend; } - if (matchlist != NULL) + if (matchlist != NULL) { ins_compl_add_list(matchlist); - else if (matchdict != NULL) + } else if (matchdict != NULL) { ins_compl_add_dict(matchdict); + } theend: // Restore State, it might have been changed. @@ -3960,8 +3991,8 @@ static void ins_compl_add_list(list_T *const list) */ static void ins_compl_add_dict(dict_T *dict) { - dictitem_T *di_refresh; - dictitem_T *di_words; + dictitem_T *di_refresh; + dictitem_T *di_words; // Check for optional "refresh" item. compl_opt_refresh_always = false; @@ -4096,8 +4127,9 @@ static int ins_compl_get_exp(pos_T *ini) || CTRL_X_MODE_LINE_OR_EVAL(l_ctrl_x_mode)) && (!compl_started || found_all)) { found_all = FALSE; - while (*e_cpt == ',' || *e_cpt == ' ') + while (*e_cpt == ',' || *e_cpt == ' ') { e_cpt++; + } if (*e_cpt == '.' && !curbuf->b_scanned) { ins_buf = curbuf; first_match_pos = *ini; @@ -4118,7 +4150,7 @@ static int ins_compl_get_exp(pos_T *ini) set_match_pos = true; } else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL && (ins_buf = - ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf) { + ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf) { // Scan a buffer, but not the current one. if (ins_buf->b_ml.ml_mfp != NULL) { // loaded buffer compl_started = true; @@ -4149,10 +4181,11 @@ static int ins_compl_get_exp(pos_T *ini) if (CTRL_X_MODE_LINE_OR_EVAL(l_ctrl_x_mode)) { type = -1; } else if (*e_cpt == 'k' || *e_cpt == 's') { - if (*e_cpt == 'k') + if (*e_cpt == 'k') { type = CTRL_X_DICTIONARY; - else + } else { type = CTRL_X_THESAURUS; + } if (*++e_cpt != ',' && *e_cpt != NUL) { dict = e_cpt; dict_f = DICT_FIRST; @@ -4174,8 +4207,9 @@ static int ins_compl_get_exp(pos_T *ini) (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ","); found_all = TRUE; - if (type == -1) + if (type == -1) { continue; + } } } @@ -4201,18 +4235,17 @@ static int ins_compl_get_exp(pos_T *ini) case CTRL_X_DICTIONARY: case CTRL_X_THESAURUS: - ins_compl_dictionaries( - dict != NULL ? dict - : (type == CTRL_X_THESAURUS + ins_compl_dictionaries(dict != NULL ? dict + : (type == CTRL_X_THESAURUS ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr) - : (*curbuf->b_p_dict == NUL + : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)), - compl_pattern, - dict != NULL ? dict_f - : 0, type == CTRL_X_THESAURUS); + compl_pattern, + dict != NULL ? dict_f + : 0, type == CTRL_X_THESAURUS); dict = NULL; break; @@ -4242,7 +4275,7 @@ static int ins_compl_get_exp(pos_T *ini) #ifdef BACKSLASH_IN_FILENAME if (curbuf->b_p_csl[0] != NUL) { for (int i = 0; i < num_matches; i++) { - char_u *ptr = matches[i]; + char_u *ptr = matches[i]; while (*ptr != NUL) { if (curbuf->b_p_csl[0] == 's' && *ptr == '\\') { *ptr = '/'; @@ -4260,9 +4293,10 @@ static int ins_compl_get_exp(pos_T *ini) case CTRL_X_CMDLINE: if (expand_cmdline(&compl_xp, compl_pattern, - (int)STRLEN(compl_pattern), - &num_matches, &matches) == EXPAND_OK) + (int)STRLEN(compl_pattern), + &num_matches, &matches) == EXPAND_OK) { ins_compl_add_matches(num_matches, matches, FALSE); + } break; case CTRL_X_FUNCTION: @@ -4272,27 +4306,30 @@ static int ins_compl_get_exp(pos_T *ini) case CTRL_X_SPELL: num_matches = expand_spelling(first_match_pos.lnum, - compl_pattern, &matches); - if (num_matches > 0) + compl_pattern, &matches); + if (num_matches > 0) { ins_compl_add_matches(num_matches, matches, p_ic); + } break; default: // normal ^P/^N and ^X^L // If 'infercase' is set, don't use 'smartcase' here save_p_scs = p_scs; assert(ins_buf); - if (ins_buf->b_p_inf) + if (ins_buf->b_p_inf) { p_scs = FALSE; + } // Buffers other than curbuf are scanned from the beginning or the // end but never from the middle, thus setting nowrapscan in this // buffers is a good idea, on the other hand, we always set // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb save_p_ws = p_ws; - if (ins_buf != curbuf) + if (ins_buf != curbuf) { p_ws = false; - else if (*e_cpt == '.') + } else if (*e_cpt == '.') { p_ws = true; + } for (;; ) { bool cont_s_ipos = false; @@ -4323,8 +4360,9 @@ static int ins_compl_get_exp(pos_T *ini) found_new_match = FAIL; } if (found_new_match == FAIL) { - if (ins_buf == curbuf) + if (ins_buf == curbuf) { found_all = TRUE; + } break; } @@ -4399,13 +4437,13 @@ static int ins_compl_get_exp(pos_T *ini) IObuff[len] = NUL; ptr = IObuff; } - if (len == compl_length) + if (len == compl_length) { continue; + } } } - if (ins_compl_add_infercase( - ptr, len, p_ic, ins_buf == curbuf ? NULL : ins_buf->b_sfname, - 0, cont_s_ipos) != NOTDONE) { + if (ins_compl_add_infercase(ptr, len, p_ic, ins_buf == curbuf ? NULL : ins_buf->b_sfname, + 0, cont_s_ipos) != NOTDONE) { found_new_match = OK; break; } @@ -4425,8 +4463,9 @@ static int ins_compl_get_exp(pos_T *ini) if ((l_ctrl_x_mode != CTRL_X_NORMAL && !CTRL_X_MODE_LINE_OR_EVAL(l_ctrl_x_mode)) || found_new_match != FAIL) { - if (got_int) + if (got_int) { break; + } // Fill the popup menu as soon as possible. if (type != -1) { ins_compl_check_keys(0, false); @@ -4518,21 +4557,16 @@ static dict_T *ins_compl_dict_alloc(compl_T *match) { // { word, abbr, menu, kind, info } dict_T *dict = tv_dict_alloc_lock(VAR_FIXED); - tv_dict_add_str( - dict, S_LEN("word"), - (const char *)EMPTY_IF_NULL(match->cp_str)); - tv_dict_add_str( - dict, S_LEN("abbr"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_ABBR])); - tv_dict_add_str( - dict, S_LEN("menu"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_MENU])); - tv_dict_add_str( - dict, S_LEN("kind"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_KIND])); - tv_dict_add_str( - dict, S_LEN("info"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_INFO])); + tv_dict_add_str(dict, S_LEN("word"), + (const char *)EMPTY_IF_NULL(match->cp_str)); + tv_dict_add_str(dict, S_LEN("abbr"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_ABBR])); + tv_dict_add_str(dict, S_LEN("menu"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_MENU])); + tv_dict_add_str(dict, S_LEN("kind"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_KIND])); + tv_dict_add_str(dict, S_LEN("info"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_INFO])); if (match->cp_user_data.v_type == VAR_UNKNOWN) { tv_dict_add_str(dict, S_LEN("user_data"), ""); } else { @@ -4541,30 +4575,25 @@ static dict_T *ins_compl_dict_alloc(compl_T *match) return dict; } -/* - * Fill in the next completion in the current direction. - * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to - * get more completions. If it is FALSE, then we just do nothing when there - * are no more completions in a given direction. The latter case is used when - * we are still in the middle of finding completions, to allow browsing - * through the ones found so far. - * Return the total number of matches, or -1 if still unknown -- webb. - * - * compl_curr_match is currently being used by ins_compl_get_exp(), so we use - * compl_shown_match here. - * - * Note that this function may be called recursively once only. First with - * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn - * calls this function with "allow_get_expansion" FALSE. - */ -static int -ins_compl_next ( - int allow_get_expansion, - int count, // Repeat completion this many times; should - // be at least 1 - int insert_match, // Insert the newly selected match - int in_compl_func // Called from complete_check() -) +/// Fill in the next completion in the current direction. +/// If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to +/// get more completions. If it is FALSE, then we just do nothing when there +/// are no more completions in a given direction. The latter case is used when +/// we are still in the middle of finding completions, to allow browsing +/// through the ones found so far. +/// @return the total number of matches, or -1 if still unknown -- webb. +/// +/// compl_curr_match is currently being used by ins_compl_get_exp(), so we use +/// compl_shown_match here. +/// +/// Note that this function may be called recursively once only. First with +/// "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn +/// calls this function with "allow_get_expansion" FALSE. +/// +/// @param count Repeat completion this many times; should be at least 1 +/// @param insert_match Insert the newly selected match +/// @param in_compl_func Called from complete_check() +static int ins_compl_next(int allow_get_expansion, int count, int insert_match, int in_compl_func) { int num_matches = -1; int todo = count; @@ -4574,8 +4603,9 @@ ins_compl_next ( /* When user complete function return -1 for findstart which is next * time of 'always', compl_shown_match become NULL. */ - if (compl_shown_match == NULL) + if (compl_shown_match == NULL) { return -1; + } if (compl_leader != NULL && (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0) { @@ -4592,21 +4622,23 @@ ins_compl_next ( * backward, find the last match. */ if (compl_shows_dir == BACKWARD && !ins_compl_equal(compl_shown_match, - compl_leader, (int)STRLEN(compl_leader)) + compl_leader, (int)STRLEN(compl_leader)) && (compl_shown_match->cp_next == NULL || compl_shown_match->cp_next == compl_first_match)) { while (!ins_compl_equal(compl_shown_match, - compl_leader, (int)STRLEN(compl_leader)) + compl_leader, (int)STRLEN(compl_leader)) && compl_shown_match->cp_prev != NULL - && compl_shown_match->cp_prev != compl_first_match) + && compl_shown_match->cp_prev != compl_first_match) { compl_shown_match = compl_shown_match->cp_prev; + } } } if (allow_get_expansion && insert_match - && (!(compl_get_longest || compl_restarting) || compl_used_match)) + && (!(compl_get_longest || compl_restarting) || compl_used_match)) { // Delete old text to be replaced ins_compl_delete(); + } // When finding the longest common text we stick at the original text, // don't let CTRL-N or CTRL-P move to the first match. @@ -4634,19 +4666,21 @@ ins_compl_next ( } else { if (!allow_get_expansion) { if (advance) { - if (compl_shows_dir == BACKWARD) + if (compl_shows_dir == BACKWARD) { compl_pending -= todo + 1; - else + } else { compl_pending += todo + 1; + } } return -1; } if (!compl_no_select && advance) { - if (compl_shows_dir == BACKWARD) + if (compl_shows_dir == BACKWARD) { --compl_pending; - else + } else { ++compl_pending; + } } // Find matches. @@ -4662,8 +4696,9 @@ ins_compl_next ( if (compl_pending < 0 && compl_shown_match->cp_prev != NULL) { compl_shown_match = compl_shown_match->cp_prev; ++compl_pending; - } else + } else { break; + } } found_end = false; } @@ -4728,8 +4763,8 @@ ins_compl_next ( if (compl_shown_match->cp_fname != NULL) { char *lead = _("match in file"); int space = sc_col - vim_strsize((char_u *)lead) - 2; - char_u *s; - char_u *e; + char_u *s; + char_u *e; if (space > 0) { // We need the tail that fits. With double-byte encoding going @@ -4797,7 +4832,7 @@ void ins_compl_check_keys(int frequency, int in_compl_func) c = safe_vgetc(); // Eat the character compl_shows_dir = ins_compl_key2dir(c); (void)ins_compl_next(false, ins_compl_key2count(c), - c != K_UP && c != K_DOWN, in_compl_func); + c != K_UP && c != K_DOWN, in_compl_func); } else { /* Need to get the character to have KeyTyped set. We'll put it * back with vungetc() below. But skip K_IGNORE. */ @@ -4805,8 +4840,9 @@ void ins_compl_check_keys(int frequency, int in_compl_func) if (c != K_IGNORE) { /* Don't interrupt completion when the character wasn't typed, * e.g., when doing @q to replay keys. */ - if (c != Ctrl_R && KeyTyped) + if (c != Ctrl_R && KeyTyped) { compl_interrupted = TRUE; + } vungetc(c); } @@ -4902,7 +4938,7 @@ static bool ins_compl_use_match(int c) */ static int ins_complete(int c, bool enable_pum) { - char_u *line; + char_u *line; int startcol = 0; // column where searched text starts colnr_T curs_col; // cursor column int n; @@ -4961,9 +4997,8 @@ static int ins_complete(int c, bool enable_pum) * mode but first we need to redefine compl_startpos */ if (compl_cont_status & CONT_S_IPOS) { compl_cont_status |= CONT_SOL; - compl_startpos.col = (colnr_T)(skipwhite( - line + compl_length - + compl_startpos.col) - line); + compl_startpos.col = (colnr_T)(skipwhite(line + compl_length + + compl_startpos.col) - line); } compl_col = compl_startpos.col; } @@ -4977,14 +5012,17 @@ static int ins_complete(int c, bool enable_pum) compl_col = curwin->w_cursor.col - compl_length; } compl_cont_status |= CONT_ADDING | CONT_N_ADDS; - if (compl_length < 1) + if (compl_length < 1) { compl_cont_status &= CONT_LOCAL; + } } else if (CTRL_X_MODE_LINE_OR_EVAL(ctrl_x_mode)) { compl_cont_status = CONT_ADDING | CONT_N_ADDS; - } else + } else { compl_cont_status = 0; - } else + } + } else { compl_cont_status &= CONT_LOCAL; + } if (!(compl_cont_status & CONT_ADDING)) { // normal expansion compl_cont_mode = ctrl_x_mode; @@ -5003,27 +5041,30 @@ static int ins_complete(int c, bool enable_pum) if ((compl_cont_status & CONT_SOL) || ctrl_x_mode == CTRL_X_PATH_DEFINES) { if (!(compl_cont_status & CONT_ADDING)) { - while (--startcol >= 0 && vim_isIDc(line[startcol])) + while (--startcol >= 0 && vim_isIDc(line[startcol])) { ; + } compl_col += ++startcol; compl_length = curs_col - startcol; } - if (p_ic) + if (p_ic) { compl_pattern = str_foldcase(line + compl_col, compl_length, NULL, 0); - else + } else { compl_pattern = vim_strnsave(line + compl_col, compl_length); + } } else if (compl_cont_status & CONT_ADDING) { - char_u *prefix = (char_u *)"\\<"; + char_u *prefix = (char_u *)"\\<"; // we need up to 2 extra chars for the prefix compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, - compl_length) + 2); + compl_length) + 2); if (!vim_iswordp(line + compl_col) || (compl_col > 0 && ( - vim_iswordp(mb_prevptr(line, line + compl_col)) - ))) + vim_iswordp(mb_prevptr(line, line + compl_col)) + ))) { prefix = (char_u *)""; + } STRCPY((char *)compl_pattern, prefix); (void)quote_meta(compl_pattern + STRLEN(prefix), line + compl_col, compl_length); @@ -5058,10 +5099,10 @@ static int ins_complete(int c, bool enable_pum) STRCAT((char *)compl_pattern, "\\k"); } else { compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, - compl_length) + 2); + compl_length) + 2); STRCPY((char *)compl_pattern, "\\<"); (void)quote_meta(compl_pattern + 2, line + compl_col, - compl_length); + compl_length); } } } else if (CTRL_X_MODE_LINE_OR_EVAL(ctrl_x_mode)) { @@ -5078,7 +5119,7 @@ static int ins_complete(int c, bool enable_pum) } else if (ctrl_x_mode == CTRL_X_FILES) { // Go back to just before the first filename character. if (startcol > 0) { - char_u *p = line + startcol; + char_u *p = line + startcol; MB_PTR_BACK(line, p); while (p > line && vim_isfilec(PTR2CHAR(p))) { @@ -5113,10 +5154,10 @@ static int ins_complete(int c, bool enable_pum) * Call user defined function 'completefunc' with "a:findstart" * set to 1 to obtain the length of text to use for completion. */ - char_u *funcname; + char_u *funcname; pos_T pos; - win_T *curwin_save; - buf_T *curbuf_save; + win_T *curwin_save; + buf_T *curbuf_save; const int save_State = State; /* Call 'completefunc' or 'omnifunc' and get pattern length as a @@ -5158,8 +5199,9 @@ static int ins_complete(int c, bool enable_pum) /* Return value -2 means the user complete function wants to * cancel the complete without an error. * Return value -3 does the same as -2 and leaves CTRL-X mode.*/ - if (col == -2) + if (col == -2) { return FAIL; + } if (col == -3) { ctrl_x_mode = CTRL_X_NORMAL; edit_submode = NULL; @@ -5175,11 +5217,13 @@ static int ins_complete(int c, bool enable_pum) */ compl_opt_refresh_always = FALSE; - if (col < 0) + if (col < 0) { col = curs_col; + } compl_col = col; - if (compl_col > curs_col) + if (compl_col > curs_col) { compl_col = curs_col; + } /* Setup variables for completion. Need to obtain "line" again, * it may have become invalid. */ @@ -5190,9 +5234,9 @@ static int ins_complete(int c, bool enable_pum) if (spell_bad_len > 0) { assert(spell_bad_len <= INT_MAX); compl_col = curs_col - (int)spell_bad_len; - } - else + } else { compl_col = spell_word_start(startcol); + } if (compl_col >= (colnr_T)startcol) { compl_length = 0; compl_col = curs_col; @@ -5227,10 +5271,11 @@ static int ins_complete(int c, bool enable_pum) compl_startpos.col = compl_col; } - if (compl_cont_status & CONT_LOCAL) + if (compl_cont_status & CONT_LOCAL) { edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]); - else + } else { edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); + } /* If any of the original typed text has been changed we need to fix * the redo buffer. */ @@ -5335,14 +5380,15 @@ static int ins_complete(int c, bool enable_pum) * Translations may need more than twice that. */ static char_u match_ref[81]; - if (compl_matches > 0) + if (compl_matches > 0) { vim_snprintf((char *)match_ref, sizeof(match_ref), - _("match %d of %d"), - compl_curr_match->cp_number, compl_matches); - else + _("match %d of %d"), + compl_curr_match->cp_number, compl_matches); + } else { vim_snprintf((char *)match_ref, sizeof(match_ref), - _("match %d"), - compl_curr_match->cp_number); + _("match %d"), + compl_curr_match->cp_number); + } edit_submode_extra = match_ref; edit_submode_highl = HLF_R; if (dollar_vcol >= 0) { @@ -5394,8 +5440,9 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) case '*': case '[': if (ctrl_x_mode == CTRL_X_DICTIONARY - || ctrl_x_mode == CTRL_X_THESAURUS) + || ctrl_x_mode == CTRL_X_THESAURUS) { break; + } FALLTHROUGH; case '~': if (!p_magic) { // quote these only if magic is set @@ -5404,8 +5451,9 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) FALLTHROUGH; case '\\': if (ctrl_x_mode == CTRL_X_DICTIONARY - || ctrl_x_mode == CTRL_X_THESAURUS) + || ctrl_x_mode == CTRL_X_THESAURUS) { break; + } FALLTHROUGH; case '^': // currently it's not needed. case '$': @@ -5430,8 +5478,9 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) } } } - if (dest != NULL) + if (dest != NULL) { *dest = NUL; + } return m; } @@ -5451,8 +5500,9 @@ int get_literal(void) int octal = FALSE; int unicode = 0; - if (got_int) + if (got_int) { return Ctrl_C; + } no_mapping++; // don't map the next key hits cc = 0; @@ -5460,29 +5510,31 @@ int get_literal(void) for (;; ) { nc = plain_vgetc(); if (!(State & CMDLINE) - && MB_BYTE2LEN_CHECK(nc) == 1 - ) + && MB_BYTE2LEN_CHECK(nc) == 1) { add_to_showcmd(nc); - if (nc == 'x' || nc == 'X') + } + if (nc == 'x' || nc == 'X') { hex = TRUE; - else if (nc == 'o' || nc == 'O') + } else if (nc == 'o' || nc == 'O') { octal = TRUE; - else if (nc == 'u' || nc == 'U') + } else if (nc == 'u' || nc == 'U') { unicode = nc; - else { + } else { if (hex - || unicode != 0 - ) { - if (!ascii_isxdigit(nc)) + || unicode != 0) { + if (!ascii_isxdigit(nc)) { break; + } cc = cc * 16 + hex2nr(nc); } else if (octal) { - if (nc < '0' || nc > '7') + if (nc < '0' || nc > '7') { break; + } cc = cc * 8 + nc - '0'; } else { - if (!ascii_isdigit(nc)) + if (!ascii_isdigit(nc)) { break; + } cc = cc * 10 + nc - '0'; } @@ -5490,9 +5542,9 @@ int get_literal(void) } if (cc > 255 - && unicode == 0 - ) + && unicode == 0) { cc = 255; // limit range to 0-255 + } nc = 0; if (hex) { // hex: up to two chars @@ -5522,8 +5574,9 @@ int get_literal(void) } --no_mapping; - if (nc) + if (nc) { vungetc(nc); + } got_int = false; // CTRL-C typed after CTRL-V is not an interrupt return cc; } @@ -5533,7 +5586,7 @@ int get_literal(void) /// @param ctrlv `c` was typed after CTRL-V static void insert_special(int c, int allow_modmask, int ctrlv) { - char_u *p; + char_u *p; int len; // Special function key, translate into "". Up to the last '>' is @@ -5549,16 +5602,18 @@ static void insert_special(int c, int allow_modmask, int ctrlv) len = (int)STRLEN(p); c = p[len - 1]; if (len > 2) { - if (stop_arrow() == FAIL) + if (stop_arrow() == FAIL) { return; + } p[len - 1] = NUL; ins_str(p); AppendToRedobuffLit(p, -1); ctrlv = FALSE; } } - if (stop_arrow() == OK) + if (stop_arrow() == OK) { insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1); + } } /* @@ -5573,26 +5628,25 @@ static void insert_special(int c, int allow_modmask, int ctrlv) # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^') #define WHITECHAR(cc) ( \ - ascii_iswhite(cc) \ - && !utf_iscomposing(utf_ptr2char(get_cursor_pos_ptr() + 1))) + ascii_iswhite(cc) \ + && !utf_iscomposing(utf_ptr2char(get_cursor_pos_ptr() + 1))) -/* - * "flags": INSCHAR_FORMAT - force formatting - * INSCHAR_CTRLV - char typed just after CTRL-V - * INSCHAR_NO_FEX - don't use 'formatexpr' - * - * NOTE: passes the flags value straight through to internal_format() which, - * beside INSCHAR_FORMAT (above), is also looking for these: - * INSCHAR_DO_COM - format comments - * INSCHAR_COM_LIST - format comments with num list or 2nd line indent - */ -void insertchar( - int c, // character to insert or NUL - int flags, // INSCHAR_FORMAT, etc. - int second_indent // indent for second line if >= 0 -) +/// +/// "flags": INSCHAR_FORMAT - force formatting +/// INSCHAR_CTRLV - char typed just after CTRL-V +/// INSCHAR_NO_FEX - don't use 'formatexpr' +/// +/// NOTE: passes the flags value straight through to internal_format() which, +/// beside INSCHAR_FORMAT (above), is also looking for these: +/// INSCHAR_DO_COM - format comments +/// INSCHAR_COM_LIST - format comments with num list or 2nd line indent +/// +/// @param c character to insert or NUL +/// @param flags INSCHAR_FORMAT, etc. +/// @param second_indent indent for second line if >= 0 +void insertchar(int c, int flags, int second_indent) { - char_u *p; + char_u *p; int force_format = flags & INSCHAR_FORMAT; const int textwidth = comp_textwidth(force_format); @@ -5604,14 +5658,14 @@ void insertchar( * - Always do this when 'formatoptions' has the 'a' flag and the line * ends in white space. * - Otherwise: - * - Don't do this if inserting a blank - * - Don't do this if an existing character is being replaced, unless - * we're in VREPLACE mode. - * - Do this if the cursor is not on the line where insert started - * or - 'formatoptions' doesn't have 'l' or the line was not too long - * before the insert. - * - 'formatoptions' doesn't have 'b' or a blank was inserted at or - * before 'textwidth' + * - Don't do this if inserting a blank + * - Don't do this if an existing character is being replaced, unless + * we're in VREPLACE mode. + * - Do this if the cursor is not on the line where insert started + * or - 'formatoptions' doesn't have 'l' or the line was not too long + * before the insert. + * - 'formatoptions' doesn't have 'b' or a blank was inserted at or + * before 'textwidth' */ if (textwidth > 0 && (force_format @@ -5628,7 +5682,7 @@ void insertchar( // when 'formatexpr' isn't set or it returns non-zero. bool do_internal = true; colnr_T virtcol = get_nolist_virtcol() - + char2cells(c != NUL ? c : gchar_cursor()); + + char2cells(c != NUL ? c : gchar_cursor()); if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0 && (force_format || virtcol > (colnr_T)textwidth)) { @@ -5637,8 +5691,9 @@ void insertchar( // was called. ins_need_undo = true; } - if (do_internal) + if (do_internal) { internal_format(textwidth, second_indent, flags, c == NUL, c); + } } if (c == NUL) { // only formatting was wanted @@ -5647,7 +5702,7 @@ void insertchar( // Check whether this character should end a comment. if (did_ai && c == end_comment_pending) { - char_u *line; + char_u *line; char_u lead_end[COM_MAX_LEN]; // end-comment string int middle_len, end_len; int i; @@ -5676,8 +5731,9 @@ void insertchar( // Skip white space before the cursor i = curwin->w_cursor.col; - while (--i >= 0 && ascii_iswhite(line[i])) + while (--i >= 0 && ascii_iswhite(line[i])) { ; + } i++; // Skip to before the middle leader @@ -5754,10 +5810,12 @@ void insertchar( if (flags & INSCHAR_CTRLV) { redo_literal(*buf); i = 1; - } else + } else { i = 0; - if (buf[i] != NUL) + } + if (buf[i] != NUL) { AppendToRedobuffLit(buf + i, -1); + } } else { int cc; @@ -5779,20 +5837,13 @@ void insertchar( } } -/* - * Format text at the current insert position. - * - * If the INSCHAR_COM_LIST flag is present, then the value of second_indent - * will be the comment leader length sent to open_line(). - */ -static void -internal_format ( - int textwidth, - int second_indent, - int flags, - int format_only, - int c // character to be inserted (can be NUL) -) +/// Format text at the current insert position. +/// +/// If the INSCHAR_COM_LIST flag is present, then the value of second_indent +/// will be the comment leader length sent to open_line(). +/// +/// @param c character to be inserted (can be NUL) +static void internal_format(int textwidth, int second_indent, int flags, int format_only, int c) { int cc; int save_char = NUL; @@ -5815,8 +5866,7 @@ internal_format ( * deleted. Replace it with an 'x' temporarily. */ if (!curbuf->b_p_ai - && !(State & VREPLACE_FLAG) - ) { + && !(State & VREPLACE_FLAG)) { cc = gchar_cursor(); if (ascii_iswhite(cc)) { save_char = cc; @@ -5835,14 +5885,15 @@ internal_format ( colnr_T len; colnr_T virtcol; int orig_col = 0; - char_u *saved_text = NULL; + char_u *saved_text = NULL; colnr_T col; colnr_T end_col; virtcol = get_nolist_virtcol() + char2cells(c != NUL ? c : gchar_cursor()); - if (virtcol <= (colnr_T)textwidth) + if (virtcol <= (colnr_T)textwidth) { break; + } if (no_leader) { do_comments = false; @@ -5890,10 +5941,11 @@ internal_format ( || (flags & INSCHAR_FORMAT) || curwin->w_cursor.lnum != Insstart.lnum || curwin->w_cursor.col >= Insstart.col) { - if (curwin->w_cursor.col == startcol && c != NUL) + if (curwin->w_cursor.col == startcol && c != NUL) { cc = c; - else + } else { cc = gchar_cursor(); + } if (WHITECHAR(cc)) { // remember position of blank just before text end_col = curwin->w_cursor.col; @@ -5948,8 +6000,9 @@ internal_format ( end_foundcol = end_col + 1; foundcol = curwin->w_cursor.col; - if (curwin->w_cursor.col <= (colnr_T)wantcol) + if (curwin->w_cursor.col <= (colnr_T)wantcol) { break; + } } else if ((cc >= 0x100 || !utf_allow_break_before(cc)) && fo_multibyte) { int ncc; @@ -5970,14 +6023,16 @@ internal_format ( if (curwin->w_cursor.col != skip_pos && allow_break) { foundcol = curwin->w_cursor.col; end_foundcol = foundcol; - if (curwin->w_cursor.col <= (colnr_T)wantcol) + if (curwin->w_cursor.col <= (colnr_T)wantcol) { break; + } } curwin->w_cursor.col = col; } - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { break; + } ncc = cc; col = curwin->w_cursor.col; @@ -6039,8 +6094,9 @@ internal_format ( } } } - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { break; + } dec_cursor(); } @@ -6069,11 +6125,13 @@ internal_format ( */ curwin->w_cursor.col = foundcol; while ((cc = gchar_cursor(), WHITECHAR(cc)) - && (!fo_white_par || curwin->w_cursor.col < startcol)) + && (!fo_white_par || curwin->w_cursor.col < startcol)) { inc_cursor(); + } startcol -= curwin->w_cursor.col; - if (startcol < 0) + if (startcol < 0) { startcol = 0; + } if (State & VREPLACE_FLAG) { /* @@ -6100,12 +6158,13 @@ internal_format ( * Only insert/delete lines, but don't really redraw the window. */ open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX - + (fo_white_par ? OPENLINE_KEEPTRAIL : 0) - + (do_comments ? OPENLINE_DO_COM : 0) - + ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0) - , ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent)); - if (!(flags & INSCHAR_COM_LIST)) + + (fo_white_par ? OPENLINE_KEEPTRAIL : 0) + + (do_comments ? OPENLINE_DO_COM : 0) + + ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0) + , ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent)); + if (!(flags & INSCHAR_COM_LIST)) { old_indent = 0; + } replace_offset = 0; if (first_line) { @@ -6156,8 +6215,9 @@ internal_format ( */ curwin->w_cursor.col += startcol; len = (colnr_T)STRLEN(get_cursor_line_ptr()); - if (curwin->w_cursor.col > len) + if (curwin->w_cursor.col > len) { curwin->w_cursor.col = len; + } } haveto_redraw = true; @@ -6182,27 +6242,26 @@ internal_format ( } } -/* - * Called after inserting or deleting text: When 'formatoptions' includes the - * 'a' flag format from the current line until the end of the paragraph. - * Keep the cursor at the same position relative to the text. - * The caller must have saved the cursor line for undo, following ones will be - * saved here. - */ -void auto_format( - bool trailblank, // when true also format with trailing blank - bool prev_line // may start in previous line -) +/// Called after inserting or deleting text: When 'formatoptions' includes the +/// 'a' flag format from the current line until the end of the paragraph. +/// Keep the cursor at the same position relative to the text. +/// The caller must have saved the cursor line for undo, following ones will be +/// saved here. +/// +/// @param trailblank when true also format with trailing blank +/// @param prev_line may start in previous line +void auto_format(bool trailblank, bool prev_line) { pos_T pos; colnr_T len; - char_u *old; - char_u *new, *pnew; + char_u *old; + char_u *new, *pnew; int wasatend; int cc; - if (!has_format_option(FO_AUTO)) + if (!has_format_option(FO_AUTO)) { return; + } pos = curwin->w_cursor; old = get_cursor_line_ptr(); @@ -6220,8 +6279,9 @@ void auto_format( dec_cursor(); cc = gchar_cursor(); if (!WHITECHAR(cc) && curwin->w_cursor.col > 0 - && has_format_option(FO_ONE_LETTER)) + && has_format_option(FO_ONE_LETTER)) { dec_cursor(); + } cc = gchar_cursor(); if (WHITECHAR(cc)) { curwin->w_cursor = pos; @@ -6233,8 +6293,9 @@ void auto_format( /* With the 'c' flag in 'formatoptions' and 't' missing: only format * comments. */ if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP) - && get_leader_len(old, NULL, FALSE, TRUE) == 0) + && get_leader_len(old, NULL, FALSE, TRUE) == 0) { return; + } /* * May start formatting in a previous line, so that after "x" a word is @@ -6243,8 +6304,9 @@ void auto_format( */ if (prev_line && !paragraph_start(curwin->w_cursor.lnum)) { --curwin->w_cursor.lnum; - if (u_save_cursor() == FAIL) + if (u_save_cursor() == FAIL) { return; + } } /* @@ -6287,14 +6349,12 @@ void auto_format( check_cursor(); } -/* - * When an extra space was added to continue a paragraph for auto-formatting, - * delete it now. The space must be under the cursor, just after the insert - * position. - */ -static void check_auto_format( - bool end_insert // true when ending Insert mode -) +/// When an extra space was added to continue a paragraph for auto-formatting, +/// delete it now. The space must be under the cursor, just after the insert +/// position. +/// +/// @param end_insert true when ending Insert mode +static void check_auto_format(bool end_insert) { int c = ' '; int cc; @@ -6319,16 +6379,14 @@ static void check_auto_format( } } -/* - * Find out textwidth to be used for formatting: - * if 'textwidth' option is set, use it - * else if 'wrapmargin' option is set, use curwin->w_width_inner-'wrapmargin' - * if invalid value, use 0. - * Set default to window width (maximum 79) for "gq" operator. - */ -int comp_textwidth( - bool ff // force formatting (for "gq" command) -) +/// Find out textwidth to be used for formatting: +/// if 'textwidth' option is set, use it +/// else if 'wrapmargin' option is set, use curwin->w_width_inner-'wrapmargin' +/// if invalid value, use 0. +/// Set default to window width (maximum 79) for "gq" operator. +/// +/// @param ff force formatting (for "gq" command) +int comp_textwidth(bool ff) { int textwidth = curbuf->b_p_tw; if (textwidth == 0 && curbuf->b_p_wm) { @@ -6341,11 +6399,13 @@ int comp_textwidth( textwidth -= win_fdccol_count(curwin); textwidth -= win_signcol_count(curwin); - if (curwin->w_p_nu || curwin->w_p_rnu) + if (curwin->w_p_nu || curwin->w_p_rnu) { textwidth -= 8; + } } - if (textwidth < 0) + if (textwidth < 0) { textwidth = 0; + } if (ff && textwidth == 0) { textwidth = curwin->w_width_inner - 1; if (textwidth > 79) { @@ -6372,11 +6432,11 @@ static void redo_literal(int c) } } -// start_arrow() is called when an arrow key is used in insert mode. -// For undo/redo it resembles hitting the key. -static void start_arrow( - pos_T *end_insert_pos // can be NULL -) +/// start_arrow() is called when an arrow key is used in insert mode. +/// For undo/redo it resembles hitting the key. +/// +/// @param end_insert_pos can be NULL +static void start_arrow(pos_T *end_insert_pos) { start_arrow_common(end_insert_pos, true); } @@ -6428,8 +6488,9 @@ static void spell_back_to_badword(void) { pos_T tpos = curwin->w_cursor; spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL); - if (curwin->w_cursor.col != tpos.col) + if (curwin->w_cursor.col != tpos.col) { start_arrow(&tpos); + } } /* @@ -6472,20 +6533,16 @@ int stop_arrow(void) return arrow_used || ins_need_undo ? FAIL : OK; } -/* - * Do a few things to stop inserting. - * "end_insert_pos" is where insert ended. It is NULL when we already jumped - * to another window/buffer. - */ -static void -stop_insert ( - pos_T *end_insert_pos, - int esc, // called by ins_esc() - int nomove // , don't move cursor -) +/// Do a few things to stop inserting. +/// "end_insert_pos" is where insert ended. It is NULL when we already jumped +/// to another window/buffer. +/// +/// @param esc called by ins_esc() +/// @param nomove , don't move cursor +static void stop_insert(pos_T *end_insert_pos, int esc, int nomove) { int cc; - char_u *ptr; + char_u *ptr; stop_redo_ins(); replace_flush(); // abandon replace stack @@ -6501,8 +6558,9 @@ stop_insert ( xfree(last_insert); last_insert = ptr; last_insert_skip = new_insert_skip; - } else + } else { xfree(ptr); + } if (!arrow_used && end_insert_pos != NULL) { // Auto-format now. It may seem strange to do this when stopping an @@ -6519,21 +6577,24 @@ stop_insert ( if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL) { dec_cursor(); cc = gchar_cursor(); - if (!ascii_iswhite(cc)) + if (!ascii_iswhite(cc)) { curwin->w_cursor = tpos; + } } auto_format(true, false); if (ascii_iswhite(cc)) { - if (gchar_cursor() != NUL) + if (gchar_cursor() != NUL) { inc_cursor(); + } /* If the cursor is still at the same character, also keep * the "coladd". */ if (gchar_cursor() == NUL && curwin->w_cursor.lnum == tpos.lnum - && curwin->w_cursor.col == tpos.col) + && curwin->w_cursor.col == tpos.col) { curwin->w_cursor.coladd = tpos.coladd; + } } } @@ -6554,8 +6615,9 @@ stop_insert ( curwin->w_cursor = *end_insert_pos; check_cursor_col(); // make sure it is not past the line for (;; ) { - if (gchar_cursor() == NUL && curwin->w_cursor.col > 0) + if (gchar_cursor() == NUL && curwin->w_cursor.col > 0) { --curwin->w_cursor.col; + } cc = gchar_cursor(); if (!ascii_iswhite(cc)) { break; @@ -6607,7 +6669,7 @@ stop_insert ( */ void set_last_insert(int c) { - char_u *s; + char_u *s; xfree(last_insert); last_insert = xmalloc(MB_MAXBYTES * 3 + 5); @@ -6661,25 +6723,26 @@ char_u *add_char2buf(int c, char_u *s) /* * move cursor to start of line - * if flags & BL_WHITE move to first non-white - * if flags & BL_SOL move to first non-white if startofline is set, - * otherwise keep "curswant" column - * if flags & BL_FIX don't leave the cursor on a NUL. + * if flags & BL_WHITE move to first non-white + * if flags & BL_SOL move to first non-white if startofline is set, + * otherwise keep "curswant" column + * if flags & BL_FIX don't leave the cursor on a NUL. */ void beginline(int flags) { - if ((flags & BL_SOL) && !p_sol) + if ((flags & BL_SOL) && !p_sol) { coladvance(curwin->w_curswant); - else { + } else { curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; if (flags & (BL_WHITE | BL_SOL)) { - char_u *ptr; + char_u *ptr; for (ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr) - && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr) + && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr) { ++curwin->w_cursor.col; + } } curwin->w_set_curswant = TRUE; } @@ -6695,7 +6758,7 @@ void beginline(int flags) int oneright(void) { - char_u *ptr; + char_u *ptr; int l; if (virtual_active()) { @@ -6736,8 +6799,9 @@ int oneleft(void) int width; int v = getviscol(); - if (v == 0) + if (v == 0) { return FAIL; + } // We might get stuck on 'showbreak', skip over it. width = 1; @@ -6767,8 +6831,9 @@ int oneleft(void) return OK; } - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { return FAIL; + } curwin->w_set_curswant = TRUE; --curwin->w_cursor.col; @@ -6779,11 +6844,8 @@ int oneleft(void) return OK; } -int -cursor_up ( - long n, - int upd_topline // When TRUE: update topline -) +/// @oaram upd_topline When TRUE: update topline +int cursor_up(long n, int upd_topline) { linenr_T lnum; @@ -6794,9 +6856,9 @@ cursor_up ( if (lnum <= 1) { return FAIL; } - if (n >= lnum) + if (n >= lnum) { lnum = 1; - else if (hasAnyFolding(curwin)) { + } else if (hasAnyFolding(curwin)) { /* * Count each sequence of folded lines as one logical line. */ @@ -6816,10 +6878,12 @@ cursor_up ( (void)hasFolding(lnum, &lnum, NULL); } } - if (lnum < 1) + if (lnum < 1) { lnum = 1; - } else + } + } else { lnum -= n; + } curwin->w_cursor.lnum = lnum; } @@ -6833,14 +6897,10 @@ cursor_up ( return OK; } -/* - * Cursor down a number of logical lines. - */ -int -cursor_down ( - long n, - int upd_topline // When TRUE: update topline -) +/// Cursor down a number of logical lines. +/// +/// @param upd_topline When TRUE: update topline +int cursor_down(long n, int upd_topline) { linenr_T lnum; @@ -6853,24 +6913,28 @@ cursor_down ( if (lnum >= curbuf->b_ml.ml_line_count) { return FAIL; } - if (lnum + n >= curbuf->b_ml.ml_line_count) + if (lnum + n >= curbuf->b_ml.ml_line_count) { lnum = curbuf->b_ml.ml_line_count; - else if (hasAnyFolding(curwin)) { + } else if (hasAnyFolding(curwin)) { linenr_T last; // count each sequence of folded lines as one logical line while (n--) { - if (hasFolding(lnum, NULL, &last)) + if (hasFolding(lnum, NULL, &last)) { lnum = last + 1; - else + } else { ++lnum; - if (lnum >= curbuf->b_ml.ml_line_count) + } + if (lnum >= curbuf->b_ml.ml_line_count) { break; + } } - if (lnum > curbuf->b_ml.ml_line_count) + if (lnum > curbuf->b_ml.ml_line_count) { lnum = curbuf->b_ml.ml_line_count; - } else + } + } else { lnum += n; + } curwin->w_cursor.lnum = lnum; } @@ -6884,20 +6948,18 @@ cursor_down ( return OK; } -/* - * Stuff the last inserted text in the read buffer. - * Last_insert actually is a copy of the redo buffer, so we - * first have to remove the command. - */ -int stuff_inserted( - int c, // Command character to be inserted - long count, // Repeat this many times - int no_esc // Don't add an ESC at the end -) +/// Stuff the last inserted text in the read buffer. +/// Last_insert actually is a copy of the redo buffer, so we +/// first have to remove the command. +/// +/// @param c Command character to be inserted +/// @param count Repeat this many times +/// @param no_esc Don't add an ESC at the end +int stuff_inserted(int c, long count, int no_esc) { - char_u *esc_ptr; - char_u *ptr; - char_u *last_ptr; + char_u *esc_ptr; + char_u *ptr; + char_u *last_ptr; char_u last = NUL; ptr = get_last_insert(); @@ -6935,8 +6997,9 @@ int stuff_inserted( } } while (--count > 0); - if (last) + if (last) { *last_ptr = last; + } if (esc_ptr != NULL) { *esc_ptr = ESC; // put the ESC back @@ -6952,8 +7015,9 @@ int stuff_inserted( char_u *get_last_insert(void) { - if (last_insert == NULL) + if (last_insert == NULL) { return NULL; + } return last_insert + last_insert_skip; } @@ -6963,11 +7027,12 @@ char_u *get_last_insert(void) */ char_u *get_last_insert_save(void) { - char_u *s; + char_u *s; int len; - if (last_insert == NULL) + if (last_insert == NULL) { return NULL; + } s = vim_strsave(last_insert + last_insert_skip); len = (int)STRLEN(s); if (len > 0 && s[len - 1] == ESC) { // remove trailing ESC @@ -6995,7 +7060,7 @@ static bool echeck_abbr(int c) } return check_abbr(c, get_cursor_line_ptr(), curwin->w_cursor.col, - curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); + curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); } /* @@ -7013,7 +7078,7 @@ static bool echeck_abbr(int c) * that were deleted (always white space). */ -static char_u *replace_stack = NULL; +static char_u *replace_stack = NULL; static ssize_t replace_stack_nr = 0; // next entry in replace stack static ssize_t replace_stack_len = 0; // max. number of entries @@ -7052,8 +7117,9 @@ int replace_push_mb(char_u *p) int l = (*mb_ptr2len)(p); int j; - for (j = l - 1; j >= 0; --j) + for (j = l - 1; j >= 0; --j) { replace_push(p[j]); + } return l; } @@ -7065,23 +7131,22 @@ static int replace_pop(void) return (replace_stack_nr == 0) ? -1 : (int)replace_stack[--replace_stack_nr]; } -/* - * Join the top two items on the replace stack. This removes to "off"'th NUL - * encountered. - */ -static void replace_join( - int off // offset for which NUL to remove -) +/// Join the top two items on the replace stack. This removes to "off"'th NUL +/// encountered. +/// +/// @param off offset for which NUL to remove +static void replace_join(int off) { int i; - for (i = replace_stack_nr; --i >= 0; ) + for (i = replace_stack_nr; --i >= 0; ) { if (replace_stack[i] == NUL && off-- <= 0) { --replace_stack_nr; memmove(replace_stack + i, replace_stack + i + 1, - (size_t)(replace_stack_nr - i)); + (size_t)(replace_stack_nr - i)); return; } + } } /* @@ -7114,8 +7179,9 @@ static void mb_replace_pop_ins(int cc) if ((n = MB_BYTE2LEN(cc)) > 1) { buf[0] = cc; - for (i = 1; i < n; ++i) + for (i = 1; i < n; ++i) { buf[i] = replace_pop(); + } ins_bytes_len(buf, n); } else { ins_char(cc); @@ -7177,7 +7243,7 @@ static void replace_do_bs(int limit_col) int ins_len; int orig_vcols = 0; colnr_T start_vcol; - char_u *p; + char_u *p; int i; int vcol; const int l_State = State; @@ -7220,8 +7286,9 @@ static void replace_do_bs(int limit_col) // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col); - } else if (cc == 0) + } else if (cc == 0) { (void)del_char_after_col(limit_col); + } } /// Check that C-indenting is on. @@ -7239,23 +7306,25 @@ static bool cindent_on(void) */ void fixthisline(IndentGetter get_the_indent) { - int amount = get_the_indent(); + int amount = get_the_indent(); - if (amount >= 0) { - change_indent(INDENT_SET, amount, false, 0, true); - if (linewhite(curwin->w_cursor.lnum)) { - did_ai = true; // delete the indent if the line stays empty - } + if (amount >= 0) { + change_indent(INDENT_SET, amount, false, 0, true); + if (linewhite(curwin->w_cursor.lnum)) { + did_ai = true; // delete the indent if the line stays empty } + } } void fix_indent(void) { - if (p_paste) + if (p_paste) { return; - if (curbuf->b_p_lisp && curbuf->b_p_ai) + } + if (curbuf->b_p_lisp && curbuf->b_p_ai) { fixthisline(get_lisp_indent); - else if (cindent_on()) + } else if (cindent_on()) { do_c_expr_indent(); + } } /// Check that "cinkeys" contains the key "keytyped", @@ -7296,9 +7365,12 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) * 'when' and a '*' or '!' before the key. */ switch (when) { - case '*': try_match = (*look == '*'); break; - case '!': try_match = (*look == '!'); break; - default: try_match = (*look != '*'); break; + case '*': + try_match = (*look == '*'); break; + case '!': + try_match = (*look == '!'); break; + default: + try_match = (*look != '*'); break; } if (*look == '*' || *look == '!') { look++; @@ -7323,8 +7395,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look += 2; - // 'o' means "o" command, open forward. - // 'O' means "O" command, open backward. + // 'o' means "o" command, open forward. + // 'O' means "O" command, open backward. } else if (*look == 'o') { if (try_match && keytyped == KEY_OPEN_FORW) { return true; @@ -7336,8 +7408,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look++; - // 'e' means to check for "else" at start of line and just before the - // cursor. + // 'e' means to check for "else" at start of line and just before the + // cursor. } else if (*look == 'e') { if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4) { p = get_cursor_line_ptr(); @@ -7348,9 +7420,9 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look++; - // ':' only causes an indent if it is at the end of a label or case - // statement, or when it was before typing the ':' (to fix - // class::method for C++). + // ':' only causes an indent if it is at the end of a label or case + // statement, or when it was before typing the ':' (to fix + // class::method for C++). } else if (*look == ':') { if (try_match && keytyped == ':') { p = get_cursor_line_ptr(); @@ -7364,8 +7436,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) && p[curwin->w_cursor.col - 2] == ':') { p[curwin->w_cursor.col - 1] = ' '; const bool i = cin_iscase(p, false) - || cin_isscopedecl(p) - || cin_islabel(); + || cin_isscopedecl(p) + || cin_islabel(); p = get_cursor_line_ptr(); p[curwin->w_cursor.col - 1] = ':'; if (i) { @@ -7375,7 +7447,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look++; - // Is it a key in <>, maybe? + // Is it a key in <>, maybe? } else if (*look == '<') { if (try_match) { // make up some named keys , , , <0>, <>>, <<>, <*>, @@ -7390,10 +7462,12 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) return true; } } - while (*look && *look != '>') + while (*look && *look != '>') { look++; - while (*look == '>') + } + while (*look == '>') { look++; + } } /* * Is it a word: "=word"? @@ -7403,11 +7477,13 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) if (*look == '~') { icase = TRUE; ++look; - } else + } else { icase = FALSE; + } p = vim_strchr(look, ','); - if (p == NULL) + if (p == NULL) { p = look + STRLEN(look); + } if ((try_match || try_match_word) && curwin->w_cursor.col >= (colnr_T)(p - look)) { bool match = false; @@ -7428,8 +7504,9 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) if (s + (p - look) <= line + curwin->w_cursor.col && (icase ? mb_strnicmp(s, look, (size_t)(p - look)) - : STRNCMP(s, look, p - look)) == 0) + : STRNCMP(s, look, p - look)) == 0) { match = true; + } } else { // TODO(@brammool): multi-byte if (keytyped == (int)p[-1] @@ -7460,7 +7537,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look = p; - // Ok, it's a boring generic character. + // Ok, it's a boring generic character. } else { if (try_match && *look == keytyped) { return true; @@ -7490,15 +7567,15 @@ int hkmap(int c) PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV }; static char_u map[26] = - {(char_u)hALEF /*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/, - (char_u)DALET /*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit /*f*/, - (char_u)GIMEL /*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/, - (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/, - (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/, - (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/, - (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/, - (char_u)VAV /*v*/, (char_u)hSHIN /*w*/, (char_u)-1 /*x*/, - (char_u)AIN /*y*/, (char_u)ZADI /*z*/}; + { (char_u)hALEF /*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/, + (char_u)DALET /*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit /*f*/, + (char_u)GIMEL /*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/, + (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/, + (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/, + (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/, + (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/, + (char_u)VAV /*v*/, (char_u)hSHIN /*w*/, (char_u)-1 /*x*/, + (char_u)AIN /*y*/, (char_u)ZADI /*z*/ }; if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z') { return (int)(map[CharOrd(c)] - 1 + p_aleph); @@ -7523,24 +7600,33 @@ int hkmap(int c) } } else { switch (c) { - case '`': return ';'; - case '/': return '.'; - case '\'': return ','; - case 'q': return '/'; - case 'w': return '\''; + case '`': + return ';'; + case '/': + return '.'; + case '\'': + return ','; + case 'q': + return '/'; + case 'w': + return '\''; // Hebrew letters - set offset from 'a' - case ',': c = '{'; break; - case '.': c = 'v'; break; - case ';': c = 't'; break; + case ',': + c = '{'; break; + case '.': + c = 'v'; break; + case ';': + c = 't'; break; default: { - static char str[] = "zqbcxlsjphmkwonu ydafe rig"; + static char str[] = "zqbcxlsjphmkwonu ydafe rig"; - if (c < 'a' || c > 'z') - return c; - c = str[CharOrdLow(c)]; - break; - } + if (c < 'a' || c > 'z') { + return c; + } + c = str[CharOrdLow(c)]; + break; + } } return (int)(CharOrdLow(c) + p_aleph); @@ -7660,13 +7746,15 @@ static void ins_ctrl_g(void) // CTRL-G k and CTRL-G : cursor up to Insstart.col case K_UP: case Ctrl_K: - case 'k': ins_up(TRUE); + case 'k': + ins_up(TRUE); break; // CTRL-G j and CTRL-G : cursor down to Insstart.col case K_DOWN: case Ctrl_J: - case 'j': ins_down(TRUE); + case 'j': + ins_down(TRUE); break; // CTRL-G u: start new undoable edit @@ -7688,7 +7776,8 @@ static void ins_ctrl_g(void) break; // Unknown CTRL-G command, reserved for future expansion. - default: vim_beep(BO_CTRLG); + default: + vim_beep(BO_CTRLG); } } @@ -7746,8 +7835,9 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) */ if (*count > 0) { line_breakcheck(); - if (got_int) + if (got_int) { *count = 0; + } } if (--*count > 0) { // repeat what was typed @@ -7796,8 +7886,7 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) || (gchar_cursor() == NUL && !VIsual_active )) - && !revins_on - ) { + && !revins_on) { if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL) { oneleft(); if (restart_edit != NUL) { @@ -7836,8 +7925,9 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) static void ins_ctrl_(void) { if (revins_on && revins_chars && revins_scol >= 0) { - while (gchar_cursor() != NUL && revins_chars--) + while (gchar_cursor() != NUL && revins_chars--) { ++curwin->w_cursor.col; + } } p_ri = !p_ri; revins_on = (State == INSERT && p_ri); @@ -7846,8 +7936,9 @@ static void ins_ctrl_(void) revins_legal++; revins_chars = 0; undisplay_dollar(); - } else + } else { revins_scol = -1; + } p_hkmap = curwin->w_p_rl ^ p_ri; // be consistent! showmode(); } @@ -7870,8 +7961,9 @@ static bool ins_start_select(int c) case K_KPAGEUP: case K_PAGEDOWN: case K_KPAGEDOWN: - if (!(mod_mask & MOD_MASK_SHIFT)) + if (!(mod_mask & MOD_MASK_SHIFT)) { break; + } FALLTHROUGH; case K_S_LEFT: case K_S_RIGHT: @@ -7920,12 +8012,13 @@ static void ins_insert(int replaceState) */ static void ins_ctrl_o(void) { - if (State & VREPLACE_FLAG) + if (State & VREPLACE_FLAG) { restart_edit = 'V'; - else if (State & REPLACE_FLAG) + } else if (State & REPLACE_FLAG) { restart_edit = 'R'; - else + } else { restart_edit = 'I'; + } if (virtual_active()) { ins_at_eol = false; // cursor always keeps its column } else { @@ -7935,15 +8028,16 @@ static void ins_ctrl_o(void) /* * If the cursor is on an indent, ^T/^D insert/delete one - * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>". + * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>". * Always round the indent to 'shiftwidth', this is compatible * with vi. But vi only supports ^T and ^D after an * autoindent, we support it everywhere. */ static void ins_shift(int c, int lastc) { - if (stop_arrow() == FAIL) + if (stop_arrow() == FAIL) { return; + } AppendCharToRedobuff(c); /* @@ -7961,8 +8055,9 @@ static void ins_shift(int c, int lastc) old_indent = get_indent(); // remember curr. indent } change_indent(INDENT_SET, 0, TRUE, 0, TRUE); - } else + } else { change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE); + } if (did_ai && *skipwhite(get_cursor_line_ptr()) != NUL) { did_ai = false; @@ -8124,19 +8219,22 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) // again when auto-formatting. if (has_format_option(FO_AUTO) && has_format_option(FO_WHITE_PAR)) { - char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, true); + char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, true); int len; len = (int)STRLEN(ptr); - if (len > 0 && ptr[len - 1] == ' ') + if (len > 0 && ptr[len - 1] == ' ') { ptr[len - 1] = NUL; + } } do_join(2, FALSE, FALSE, FALSE, false); - if (temp == NUL && gchar_cursor() != NUL) + if (temp == NUL && gchar_cursor() != NUL) { inc_cursor(); - } else + } + } else { dec_cursor(); + } /* * In REPLACE mode we have to put back the text that was replaced @@ -8178,12 +8276,12 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) && (curbuf->b_p_ai || cindent_on() ) - && !revins_on - ) { + && !revins_on) { save_col = curwin->w_cursor.col; beginline(BL_WHITE); - if (curwin->w_cursor.col < save_col) + if (curwin->w_cursor.col < save_col) { mincol = curwin->w_cursor.col; + } curwin->w_cursor.col = save_col; } @@ -8239,8 +8337,9 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) ins_char(' '); } else { ins_str((char_u *)" "); - if ((State & REPLACE_FLAG)) + if ((State & REPLACE_FLAG)) { replace_push(NUL); + } } getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL); } @@ -8294,8 +8393,9 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) revins_chars--; revins_legal++; } - if (revins_on && gchar_cursor() == NUL) + if (revins_on && gchar_cursor() == NUL) { break; + } } // Just a single backspace?: if (mode == BACKSPACE_CHAR) { @@ -8349,12 +8449,12 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) static void ins_mouse(int c) { pos_T tpos; - win_T *old_curwin = curwin; + win_T *old_curwin = curwin; undisplay_dollar(); tpos = curwin->w_cursor; if (do_mouse(NULL, c, BACKWARD, 1, 0)) { - win_T *new_curwin = curwin; + win_T *new_curwin = curwin; if (curwin != old_curwin && win_valid(old_curwin)) { // Mouse took us to another window. We need to go back to the @@ -8394,21 +8494,22 @@ static void ins_mousescroll(int dir) curwin = wp; curbuf = curwin->w_buffer; } - if (curwin == old_curwin) + if (curwin == old_curwin) { undisplay_dollar(); + } // Don't scroll the window in which completion is being done. if (!pum_visible() - || curwin != old_curwin - ) { + || curwin != old_curwin) { if (dir == MSCR_DOWN || dir == MSCR_UP) { - if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) + if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { scroll_redraw(dir, - (long)(curwin->w_botline - curwin->w_topline)); - else + (long)(curwin->w_botline - curwin->w_topline)); + } else { scroll_redraw(dir, 3L); + } } else { - mouse_scroll_horiz(dir); + mouse_scroll_horiz(dir); } } @@ -8430,8 +8531,9 @@ static void ins_left(void) pos_T tpos; const bool end_change = dont_sync_undo == kFalse; // end undoable change - if ((fdo_flags & FDO_HOR) && KeyTyped) + if ((fdo_flags & FDO_HOR) && KeyTyped) { foldOpenCursor(); + } undisplay_dollar(); tpos = curwin->w_cursor; if (oneleft() == OK) { @@ -8461,12 +8563,14 @@ static void ins_home(int c) { pos_T tpos; - if ((fdo_flags & FDO_HOR) && KeyTyped) + if ((fdo_flags & FDO_HOR) && KeyTyped) { foldOpenCursor(); + } undisplay_dollar(); tpos = curwin->w_cursor; - if (c == K_C_HOME) + if (c == K_C_HOME) { curwin->w_cursor.lnum = 1; + } curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; curwin->w_curswant = 0; @@ -8477,12 +8581,14 @@ static void ins_end(int c) { pos_T tpos; - if ((fdo_flags & FDO_HOR) && KeyTyped) + if ((fdo_flags & FDO_HOR) && KeyTyped) { foldOpenCursor(); + } undisplay_dollar(); tpos = curwin->w_cursor; - if (c == K_C_END) + if (c == K_C_END) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; + } coladvance(MAXCOL); curwin->w_curswant = MAXCOL; @@ -8530,8 +8636,9 @@ static void ins_right(void) } revins_legal++; - if (revins_chars) + if (revins_chars) { revins_chars--; + } } else if (vim_strchr(p_ww, ']') != NULL && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { // if 'whichwrap' set for cursor in insert mode, may move the @@ -8567,9 +8674,8 @@ static void ins_s_right(void) dont_sync_undo = kFalse; } -static void ins_up( - bool startcol // when true move to Insstart.col -) +/// @param startcol when true move to Insstart.col +static void ins_up(bool startcol) { pos_T tpos; linenr_T old_topline = curwin->w_topline; @@ -8578,12 +8684,13 @@ static void ins_up( undisplay_dollar(); tpos = curwin->w_cursor; if (cursor_up(1L, TRUE) == OK) { - if (startcol) + if (startcol) { coladvance(getvcol_nolist(&Insstart)); + } if (old_topline != curwin->w_topline - || old_topfill != curwin->w_topfill - ) + || old_topfill != curwin->w_topfill) { redraw_later(curwin, VALID); + } start_arrow(&tpos); can_cindent = true; } else { @@ -8615,9 +8722,8 @@ static void ins_pageup(void) } } -static void ins_down( - bool startcol // when true move to Insstart.col -) +/// @param startcol when true move to Insstart.col +static void ins_down(bool startcol) { pos_T tpos; linenr_T old_topline = curwin->w_topline; @@ -8626,12 +8732,13 @@ static void ins_down( undisplay_dollar(); tpos = curwin->w_cursor; if (cursor_down(1L, TRUE) == OK) { - if (startcol) + if (startcol) { coladvance(getvcol_nolist(&Insstart)); + } if (old_topline != curwin->w_topline - || old_topfill != curwin->w_topfill - ) + || old_topfill != curwin->w_topfill) { redraw_later(curwin, VALID); + } start_arrow(&tpos); can_cindent = true; } else { @@ -8687,15 +8794,15 @@ static bool ins_tab(void) // When nothing special, insert TAB like a normal character. if (!curbuf->b_p_et && !( - p_sta - && ind - // These five lines mean 'tabstop' != 'shiftwidth' - && ((tabstop_count(curbuf->b_p_vts_array) > 1) - || (tabstop_count(curbuf->b_p_vts_array) == 1 - && tabstop_first(curbuf->b_p_vts_array) - != get_sw_value(curbuf)) - || (tabstop_count(curbuf->b_p_vts_array) == 0 - && curbuf->b_p_ts != get_sw_value(curbuf)))) + p_sta + && ind + // These five lines mean 'tabstop' != 'shiftwidth' + && ((tabstop_count(curbuf->b_p_vts_array) > 1) + || (tabstop_count(curbuf->b_p_vts_array) == 1 + && tabstop_first(curbuf->b_p_vts_array) + != get_sw_value(curbuf)) + || (tabstop_count(curbuf->b_p_vts_array) == 0 + && curbuf->b_p_ts != get_sw_value(curbuf)))) && tabstop_count(curbuf->b_p_vsts_array) == 0 && get_sts_value() == 0) { return true; } @@ -8727,7 +8834,7 @@ static bool ins_tab(void) } /* - * Insert the first space with ins_char(). It will delete one char in + * Insert the first space with ins_char(). It will delete one char in * replace mode. Insert the rest with ins_str(); it will not delete any * chars. For VREPLACE mode, we use ins_char() for all characters. */ @@ -8749,11 +8856,11 @@ static bool ins_tab(void) if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_array) > 0 || get_sts_value() > 0 || (p_sta && ind))) { - char_u *ptr; - char_u *saved_line = NULL; // init for GCC + char_u *ptr; + char_u *saved_line = NULL; // init for GCC pos_T pos; pos_T fpos; - pos_T *cursor; + pos_T *cursor; colnr_T want_vcol, vcol; int change_col = -1; int save_list = curwin->w_p_list; @@ -8800,8 +8907,9 @@ static bool ins_tab(void) // and 'linebreak' adding extra virtual columns. while (ascii_iswhite(*ptr)) { i = lbr_chartabsize(NULL, (char_u *)"\t", vcol); - if (vcol + i > want_vcol) + if (vcol + i > want_vcol) { break; + } if (*ptr != TAB) { *ptr = TAB; if (change_col < 0) { @@ -8865,12 +8973,13 @@ static bool ins_tab(void) // Insert each char in saved_line from changed_col to // ptr-cursor ins_bytes_len(saved_line + change_col, - cursor->col - change_col); + cursor->col - change_col); } } - if (State & VREPLACE_FLAG) + if (State & VREPLACE_FLAG) { xfree(saved_line); + } curwin->w_p_list = save_list; } @@ -8896,9 +9005,9 @@ static bool ins_eol(int c) * nothing to put back when the NL is deleted. */ if ((State & REPLACE_FLAG) - && !(State & VREPLACE_FLAG) - ) + && !(State & VREPLACE_FLAG)) { replace_push(NUL); + } /* * In VREPLACE mode, a NL replaces the rest of the line, and starts @@ -9008,8 +9117,8 @@ int ins_copychar(linenr_T lnum) { int c; int temp; - char_u *ptr, *prev_ptr; - char_u *line; + char_u *ptr, *prev_ptr; + char_u *line; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) { vim_beep(BO_COPY); @@ -9025,8 +9134,9 @@ int ins_copychar(linenr_T lnum) prev_ptr = ptr; temp += lbr_chartabsize_adv(line, &ptr, (colnr_T)temp); } - if ((colnr_T)temp > curwin->w_virtcol) + if ((colnr_T)temp > curwin->w_virtcol) { ptr = prev_ptr; + } c = utf_ptr2char(ptr); if (c == NUL) { @@ -9043,10 +9153,11 @@ static int ins_ctrl_ey(int tc) int c = tc; if (ctrl_x_mode == CTRL_X_SCROLL) { - if (c == Ctrl_Y) + if (c == Ctrl_Y) { scrolldown_clamp(); - else + } else { scrollup_clamp(); + } redraw_later(curwin, VALID); } else { c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1)); @@ -9079,8 +9190,8 @@ static int ins_ctrl_ey(int tc) */ static void ins_try_si(int c) { - pos_T *pos, old_pos; - char_u *ptr; + pos_T *pos, old_pos; + char_u *ptr; int i; int temp; @@ -9108,14 +9219,16 @@ static void ins_try_si(int c) } curwin->w_cursor.lnum = pos->lnum; curwin->w_cursor.col = i; - if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL) + if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL) { curwin->w_cursor = *pos; + } i = get_indent(); curwin->w_cursor = old_pos; - if (State & VREPLACE_FLAG) + if (State & VREPLACE_FLAG) { change_indent(INDENT_SET, i, FALSE, NUL, TRUE); - else + } else { (void)set_indent(i, SIN_CHANGED); + } } else if (curwin->w_cursor.col > 0) { /* * when inserting '{' after "O" reduce indent, but not @@ -9133,12 +9246,14 @@ static void ins_try_si(int c) break; } } - if (get_indent() >= i) + if (get_indent() >= i) { temp = FALSE; + } curwin->w_cursor = old_pos; } - if (temp) + if (temp) { shift_line(TRUE, FALSE, 1, TRUE); + } } } diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 8a93eafc81..bd8d3973d5 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -329,9 +329,9 @@ void ex_align(exarg_T *eap) */ static int linelen(int *has_tab) { - char_u *line; - char_u *first; - char_u *last; + char_u *line; + char_u *first; + char_u *last; int save; int len; @@ -363,8 +363,8 @@ static int linelen(int *has_tab) /* Buffer for two lines used during sorting. They are allocated to * contain the longest line being sorted. */ -static char_u *sortbuf1; -static char_u *sortbuf2; +static char_u *sortbuf1; +static char_u *sortbuf2; static int sort_lc; ///< sort using locale static int sort_ic; ///< ignore case @@ -461,9 +461,9 @@ void ex_sort(exarg_T *eap) long maxlen = 0; size_t count = (size_t)(eap->line2 - eap->line1 + 1); size_t i; - char_u *p; - char_u *s; - char_u *s2; + char_u *p; + char_u *s; + char_u *s2; char_u c; // temporary character storage bool unique = false; long deleted; @@ -738,8 +738,8 @@ void ex_retab(exarg_T *eap) long start_col = 0; // For start of white-space string long start_vcol = 0; // For start of white-space string long old_len; - char_u *ptr; - char_u *new_line = (char_u *)1; // init to non-NULL + char_u *ptr; + char_u *new_line = (char_u *)1; // init to non-NULL int did_undo; // called u_save for current line long *new_vts_array = NULL; char_u *new_ts_str; // string value of tab argument @@ -906,7 +906,7 @@ void ex_retab(exarg_T *eap) */ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) { - char_u *str; + char_u *str; linenr_T l; linenr_T extra; // Num lines added before line1 linenr_T num_lines; // Num lines moved @@ -1058,7 +1058,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) { linenr_T count; - char_u *p; + char_u *p; count = line2 - line1 + 1; curbuf->b_op_start.lnum = n + 1; @@ -1107,7 +1107,7 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) msgmore((long)count); } -static char_u *prevcmd = NULL; // the previous command +static char_u *prevcmd = NULL; // the previous command #if defined(EXITFREE) void free_prev_shellcmd(void) @@ -1130,9 +1130,9 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out linenr_T line2 = eap->line2; // end of range char_u *newcmd = NULL; // the new command bool free_newcmd = false; // need to free() newcmd - char_u *t; - char_u *p; - char_u *trailarg; + char_u *t; + char_u *p; + char_u *trailarg; int len; int scroll_save = msg_scroll; @@ -1265,13 +1265,13 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, bool do_in, bool do_out) { - char_u *itmp = NULL; - char_u *otmp = NULL; + char_u *itmp = NULL; + char_u *otmp = NULL; linenr_T linecount; linenr_T read_linecount; pos_T cursor_save; - char_u *cmd_buf; - buf_T *old_curbuf = curbuf; + char_u *cmd_buf; + buf_T *old_curbuf = curbuf; int shell_flags = 0; const int stmp = p_stmp; @@ -1684,8 +1684,8 @@ void print_line(linenr_T lnum, int use_number, int list) int rename_buffer(char_u *new_fname) { - char_u *fname, *sfname, *xfname; - buf_T *buf; + char_u *fname, *sfname, *xfname; + buf_T *buf; buf = curbuf; apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf); @@ -1795,11 +1795,11 @@ void ex_write(exarg_T *eap) int do_write(exarg_T *eap) { int other; - char_u *fname = NULL; // init to shut up gcc - char_u *ffname; + char_u *fname = NULL; // init to shut up gcc + char_u *ffname; int retval = FAIL; - char_u *free_fname = NULL; - buf_T *alt_buf = NULL; + char_u *free_fname = NULL; + buf_T *alt_buf = NULL; int name_was_missing; if (not_writing()) { // check 'write' option @@ -1879,7 +1879,7 @@ int do_write(exarg_T *eap) if (check_overwrite(eap, curbuf, fname, ffname, other) == OK) { if (eap->cmdidx == CMD_saveas && alt_buf != NULL) { - buf_T *was_curbuf = curbuf; + buf_T *was_curbuf = curbuf; apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf); @@ -1999,9 +1999,9 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int // For ":w! filename" check that no swap file exists for "filename". if (other && !emsg_silent) { - char_u *dir; - char_u *p; - char_u *swapname; + char_u *dir; + char_u *p; + char_u *swapname; /* We only try the first entry in 'directory', without checking if * it's writable. If the "." directory is not writable the write @@ -2196,7 +2196,7 @@ int getfile(int fnum, char_u *ffname_arg, char_u *sfname_arg, int setpm, linenr_ char_u *sfname = sfname_arg; int other; int retval; - char_u *free_me = NULL; + char_u *free_me = NULL; if (text_locked()) { return GETFILE_ERROR; @@ -2291,20 +2291,20 @@ int do_ecmd(int fnum, char_u *ffname, char_u *sfname, exarg_T *eap, linenr_T new int oldbuf; // TRUE if using existing buffer int auto_buf = FALSE; /* TRUE if autocommands brought us into the buffer unexpectedly */ - char_u *new_name = NULL; + char_u *new_name = NULL; int did_set_swapcommand = FALSE; - buf_T *buf; + buf_T *buf; bufref_T bufref; bufref_T old_curbuf; - char_u *free_fname = NULL; + char_u *free_fname = NULL; int retval = FAIL; long n; pos_T orig_pos; linenr_T topline = 0; int newcol = -1; int solcol = -1; - pos_T *pos; - char_u *command = NULL; + pos_T *pos; + char_u *command = NULL; int did_get_winopts = FALSE; int readfile_flags = 0; bool did_inc_redrawing_disabled = false; @@ -2911,11 +2911,11 @@ static int append_indent = 0; // autoindent for first line */ void ex_append(exarg_T *eap) { - char_u *theline; + char_u *theline; bool did_undo = false; linenr_T lnum = eap->line2; int indent = 0; - char_u *p; + char_u *p; int vcol; int empty = (curbuf->b_ml.ml_flags & ML_EMPTY); @@ -3079,9 +3079,9 @@ void ex_change(exarg_T *eap) void ex_z(exarg_T *eap) { - char_u *x; + char_u *x; int64_t bigness; - char_u *kind; + char_u *kind; int minus = 0; linenr_T start, end, curs, i; int j; @@ -3648,8 +3648,8 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle colnr_T copycol; colnr_T matchcol; colnr_T prev_matchcol = MAXCOL; - char_u *new_end, *new_start = NULL; - char_u *p1; + char_u *new_end, *new_start = NULL; + char_u *p1; int did_sub = FALSE; int lastone; long nmatch_tl = 0; // nr of lines matched below lnum @@ -3831,8 +3831,8 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle */ while (subflags.do_ask) { if (exmode_active) { - char *prompt; - char_u *resp; + char *prompt; + char_u *resp; colnr_T sc, ec; print_line_no_prefix(lnum, subflags.do_number, subflags.do_list); @@ -4513,10 +4513,10 @@ void ex_global(exarg_T *eap) linenr_T lnum; // line number according to old situation int ndone = 0; int type; // first char of cmd: 'v' or 'g' - char_u *cmd; // command argument + char_u *cmd; // command argument char_u delim; // delimiter, normally '/' - char_u *pat; + char_u *pat; regmmatch_T regmatch; int match; int which_pat; @@ -4726,20 +4726,20 @@ bool prepare_tagpreview(bool undo_sync) */ void ex_help(exarg_T *eap) { - char_u *arg; - char_u *tag; - FILE *helpfd; // file descriptor of help file + char_u *arg; + char_u *tag; + FILE *helpfd; // file descriptor of help file int n; int i; - win_T *wp; + win_T *wp; int num_matches; - char_u **matches; - char_u *p; + char_u **matches; + char_u *p; int empty_fnum = 0; int alt_fnum = 0; - buf_T *buf; + buf_T *buf; int len; - char_u *lang; + char_u *lang; const bool old_KeyTyped = KeyTyped; if (eap != NULL) { @@ -4940,7 +4940,7 @@ char_u *check_help_lang(char_u *arg) int help_heuristic(char_u *matched_string, int offset, int wrong_case) { int num_letters; - char_u *p; + char_u *p; num_letters = 0; for (p = matched_string; *p; p++) { @@ -4982,8 +4982,8 @@ int help_heuristic(char_u *matched_string, int offset, int wrong_case) */ static int help_compare(const void *s1, const void *s2) { - char *p1; - char *p2; + char *p1; + char *p2; p1 = *(char **)s1 + strlen(*(char **)s1) + 1; p2 = *(char **)s2 + strlen(*(char **)s2) + 1; @@ -5274,7 +5274,7 @@ static void prepare_help_buffer(void) void fix_help_buffer(void) { linenr_T lnum; - char_u *line; + char_u *line; bool in_example = false; // Set filetype to "help". @@ -5338,10 +5338,10 @@ void fix_help_buffer(void) if (rt != NULL && path_full_compare(rt, NameBuff, false, true) != kEqualFiles) { int fcount; - char_u **fnames; - char_u *s; + char_u **fnames; + char_u *s; vimconv_T vc; - char_u *cp; + char_u *cp; // Find all "doc/ *.txt" files in this directory. if (!add_pathsep((char *)NameBuff) @@ -5498,9 +5498,9 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, { garray_T ga; int filecount; - char_u **files; - char_u *p1, *p2; - char_u *s; + char_u **files; + char_u *p1, *p2; + char_u *s; TriState utf8 = kNone; bool mix = false; // detected mixed encodings @@ -6125,7 +6125,7 @@ char_u *skip_vimgrep_pat(char_u *p, char_u **s, int *flags) /// List v:oldfiles in a nice way. void ex_oldfiles(exarg_T *eap) { - list_T *l = get_vim_var_list(VV_OLDFILES); + list_T *l = get_vim_var_list(VV_OLDFILES); long nr = 0; if (l == NULL) { diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 1d7f83df99..779a5b471f 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -80,14 +80,14 @@ static int quitmore = 0; static bool ex_pressedreturn = false; typedef struct ucmd { - char_u *uc_name; // The command name + char_u *uc_name; // The command name uint32_t uc_argt; // The argument type - char_u *uc_rep; // The command's replacement string + char_u *uc_rep; // The command's replacement string long uc_def; // The default value for a range/count int uc_compl; // completion type cmd_addr_T uc_addr_type; // The command's address type sctx_T uc_script_ctx; // SCTX where the command was defined - char_u *uc_compl_arg; // completion argument if any + char_u *uc_compl_arg; // completion argument if any } ucmd_T; #define UC_BUFFER 1 // -buffer: local to current buffer @@ -102,7 +102,7 @@ static garray_T ucmds = { 0, 0, sizeof(ucmd_T), 4, NULL }; // Struct for storing a line inside a while/for loop typedef struct { - char_u *line; // command line + char_u *line; // command line linenr_T lnum; // sourcing_lnum of the line } wcmd_T; @@ -114,12 +114,12 @@ typedef struct { * reads more lines that may come from the while/for loop. */ struct loop_cookie { - garray_T *lines_gap; // growarray with line info + garray_T *lines_gap; // growarray with line info int current_line; // last read line from growarray int repeating; // TRUE when looping a second time // When "repeating" is FALSE use "getline" and "cookie" to get lines - char_u *(*getline)(int, void *, int, bool); - void *cookie; + char_u *(*getline)(int, void *, int, bool); + void *cookie; }; @@ -127,14 +127,14 @@ struct loop_cookie { struct dbg_stuff { int trylevel; int force_abort; - except_T *caught_stack; - char_u *vv_exception; - char_u *vv_throwpoint; + except_T *caught_stack; + char_u *vv_exception; + char_u *vv_throwpoint; int did_emsg; int got_int; int need_rethrow; int check_cstack; - except_T *current_exception; + except_T *current_exception; }; #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -309,8 +309,8 @@ int do_cmdline_cmd(const char *cmd) /// @return FAIL if cmdline could not be executed, OK otherwise int do_cmdline(char_u *cmdline, LineGetter fgetline, void *cookie, int flags) { - char_u *next_cmdline; // next cmd to execute - char_u *cmdline_copy = NULL; // copy of cmd line + char_u *next_cmdline; // next cmd to execute + char_u *cmdline_copy = NULL; // copy of cmd line bool used_getline = false; // used "fgetline" to obtain command static int recursive = 0; // recursive depth bool msg_didout_before_start = false; @@ -322,19 +322,19 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, void *cookie, int flags) }; garray_T lines_ga; // keep lines for ":while"/":for" int current_line = 0; // active line in lines_ga - char_u *fname = NULL; // function or script name + char_u *fname = NULL; // function or script name linenr_T *breakpoint = NULL; // ptr to breakpoint field in cookie - int *dbg_tick = NULL; // ptr to dbg_tick field in cookie + int *dbg_tick = NULL; // ptr to dbg_tick field in cookie struct dbg_stuff debug_saved; // saved things for debug mode int initial_trylevel; - struct msglist **saved_msg_list = NULL; - struct msglist *private_msg_list; + struct msglist **saved_msg_list = NULL; + struct msglist *private_msg_list; // "fgetline" and "cookie" passed to do_one_cmd() - char_u *(*cmd_getline)(int, void *, int, bool); - void *cmd_cookie; + char_u *(*cmd_getline)(int, void *, int, bool); + void *cmd_cookie; struct loop_cookie cmd_loop_cookie; - void *real_cookie; + void *real_cookie; int getline_is_func; static int call_depth = 0; // recursiveness @@ -964,9 +964,9 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, void *cookie, int flags) */ static char_u *get_loop_line(int c, void *cookie, int indent, bool do_concat) { - struct loop_cookie *cp = (struct loop_cookie *)cookie; - wcmd_T *wp; - char_u *line; + struct loop_cookie *cp = (struct loop_cookie *)cookie; + wcmd_T *wp; + char_u *line; if (cp->current_line + 1 >= cp->lines_gap->ga_len) { if (cp->repeating) { @@ -1251,16 +1251,16 @@ static char_u *skip_colon_white(const char_u *p, bool skipleadingwhite) static char_u * do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGetter fgetline, void *cookie) { - char_u *p; + char_u *p; linenr_T lnum; long n; - char_u *errormsg = NULL; // error message - char_u *after_modifier = NULL; + char_u *errormsg = NULL; // error message + char_u *after_modifier = NULL; exarg_T ea; const int save_msg_scroll = msg_scroll; cmdmod_T save_cmdmod; const int save_reg_executing = reg_executing; - char_u *cmd; + char_u *cmd; memset(&ea, 0, sizeof(ea)); ea.line1 = 1; @@ -2578,7 +2578,7 @@ static char_u *find_command(exarg_T *eap, int *full) FUNC_ATTR_NONNULL_ARG(1) { int len; - char_u *p; + char_u *p; int i; /* @@ -2701,11 +2701,11 @@ static char_u *find_ucmd(exarg_T *eap, char_u *p, int *full, expand_T *xp, int * { int len = (int)(p - eap->cmd); int j, k, matchlen = 0; - ucmd_T *uc; + ucmd_T *uc; int found = FALSE; int possible = FALSE; - char_u *cp, *np; // Point into typed cmd and test name - garray_T *gap; + char_u *cp, *np; // Point into typed cmd and test name + garray_T *gap; int amb_local = FALSE; /* Found ambiguous buffer-local command, only full match global is accepted. */ @@ -2799,7 +2799,7 @@ static char_u *find_ucmd(exarg_T *eap, char_u *p, int *full, expand_T *xp, int * } static struct cmdmod { - char *name; + char *name; int minlen; int has_count; // :123verbose :3tab } cmdmods[] = { @@ -2834,7 +2834,7 @@ static struct cmdmod { */ int modifier_len(char_u *cmd) { - char_u *p = cmd; + char_u *p = cmd; if (ascii_isdigit(*cmd)) { p = skipwhite(skipdigits(cmd + 1)); @@ -2863,7 +2863,7 @@ int modifier_len(char_u *cmd) int cmd_exists(const char *const name) { exarg_T ea; - char_u *p; + char_u *p; // Check command modifiers. for (int i = 0; i < (int)ARRAY_SIZE(cmdmods); i++) { @@ -3851,9 +3851,9 @@ static linenr_T get_address(exarg_T *eap, char_u **ptr, cmd_addr_T addr_type, in int c; int i; long n; - char_u *cmd; + char_u *cmd; pos_T pos; - pos_T *fp; + pos_T *fp; linenr_T lnum; buf_T *buf; @@ -4296,7 +4296,7 @@ static void correct_range(exarg_T *eap) */ static char_u *skip_grep_pat(exarg_T *eap) { - char_u *p = eap->arg; + char_u *p = eap->arg; if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep || eap->cmdidx == CMD_vimgrepadd @@ -4316,10 +4316,10 @@ static char_u *skip_grep_pat(exarg_T *eap) */ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) { - char_u *new_cmdline; - char_u *program; - char_u *pos; - char_u *ptr; + char_u *new_cmdline; + char_u *program; + char_u *pos; + char_u *ptr; int len; int i; @@ -4387,9 +4387,9 @@ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) { int has_wildcards; // need to expand wildcards - char_u *repl; + char_u *repl; size_t srclen; - char_u *p; + char_u *p; int escaped; // Skip a regexp pattern for ":vimgrep[add] pat file..." @@ -4459,7 +4459,7 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) && eap->cmdidx != CMD_make && eap->cmdidx != CMD_terminal && !(eap->argt & EX_NOSPC)) { - char_u *l; + char_u *l; #ifdef BACKSLASH_IN_FILENAME /* Don't escape a backslash here, because rem_backslash() doesn't * remove it later. */ @@ -4484,7 +4484,7 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) || eap->cmdidx == CMD_bang || eap->cmdidx == CMD_terminal) && vim_strpbrk(repl, (char_u *)"!") != NULL) { - char_u *l; + char_u *l; l = vim_strsave_escaped(repl, (char_u *)"!"); xfree(repl); @@ -4610,7 +4610,7 @@ static char_u *repl_cmdline(exarg_T *eap, char_u *src, size_t srclen, char_u *re */ void separate_nextcmd(exarg_T *eap) { - char_u *p; + char_u *p; p = skip_grep_pat(eap); @@ -4727,10 +4727,10 @@ int get_bad_opt(const char_u *p, exarg_T *eap) */ static int getargopt(exarg_T *eap) { - char_u *arg = eap->arg + 2; - int *pp = NULL; + char_u *arg = eap->arg + 2; + int *pp = NULL; int bad_char_idx; - char_u *p; + char_u *p; // ":edit ++[no]bin[ary] file" if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0) { @@ -5154,11 +5154,11 @@ static int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t a int flags, int compl, char_u *compl_arg, cmd_addr_T addr_type, bool force) FUNC_ATTR_NONNULL_ARG(1, 3) { - ucmd_T *cmd = NULL; + ucmd_T *cmd = NULL; int i; int cmp = 1; - char_u *rep_buf = NULL; - garray_T *gap; + char_u *rep_buf = NULL; + garray_T *gap; replace_termcodes(rep, STRLEN(rep), &rep_buf, false, false, true, CPO_TO_CPO_FLAGS); @@ -5325,7 +5325,7 @@ static void uc_list(char_u *name, size_t name_len) { int i, j; bool found = false; - ucmd_T *cmd; + ucmd_T *cmd; uint32_t a; // In cmdwin, the alternative buffer should be used. @@ -5489,7 +5489,7 @@ static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, int int *complp, char_u **compl_arg, cmd_addr_T *addr_type_arg) FUNC_ATTR_NONNULL_ALL { - char_u *p; + char_u *p; if (len == 0) { EMSG(_("E175: No attribute specified")); @@ -5507,7 +5507,7 @@ static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, int *argt |= EX_TRLBAR; } else { int i; - char_u *val = NULL; + char_u *val = NULL; size_t vallen = 0; size_t attrlen = len; @@ -5630,14 +5630,14 @@ static char e_complete_used_without_nargs[] = N_("E1208: -complete used without */ static void ex_command(exarg_T *eap) { - char_u *name; - char_u *end; - char_u *p; + char_u *name; + char_u *end; + char_u *p; uint32_t argt = 0; long def = -1; int flags = 0; int compl = EXPAND_NOTHING; - char_u *compl_arg = NULL; + char_u *compl_arg = NULL; cmd_addr_T addr_type_arg = ADDR_NONE; int has_attr = (eap->arg[0] == '-'); int name_len; @@ -5696,7 +5696,7 @@ void ex_comclear(exarg_T *eap) uc_clear(&curbuf->b_ucmds); } -static void free_ucmd(ucmd_T* cmd) { +static void free_ucmd(ucmd_T * cmd) { xfree(cmd->uc_name); xfree(cmd->uc_rep); xfree(cmd->uc_compl_arg); @@ -5713,9 +5713,9 @@ void uc_clear(garray_T *gap) static void ex_delcommand(exarg_T *eap) { int i = 0; - ucmd_T *cmd = NULL; + ucmd_T *cmd = NULL; int cmp = -1; - garray_T *gap; + garray_T *gap; gap = &curbuf->b_ucmds; for (;; ) { @@ -5854,7 +5854,7 @@ static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd, char_u **split_buf, size_t *split_len) { size_t result = 0; - char_u *p = code + 1; + char_u *p = code + 1; size_t l = len - 2; int quote = 0; enum { @@ -6132,18 +6132,18 @@ static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd, static void do_ucmd(exarg_T *eap) { - char_u *buf; - char_u *p; - char_u *q; + char_u *buf; + char_u *p; + char_u *q; - char_u *start; - char_u *end = NULL; - char_u *ksp; + char_u *start; + char_u *end = NULL; + char_u *ksp; size_t len, totlen; size_t split_len = 0; - char_u *split_buf = NULL; - ucmd_T *cmd; + char_u *split_buf = NULL; + ucmd_T *cmd; const sctx_T save_current_sctx = current_sctx; if (eap->cmdidx == CMD_USER) { @@ -6643,7 +6643,7 @@ static void ex_pclose(exarg_T *eap) void ex_win_close(int forceit, win_T *win, tabpage_T *tp) { int need_hide; - buf_T *buf = win->w_buffer; + buf_T *buf = win->w_buffer; // Never close the autocommand window. if (win == aucmd_win) { @@ -6682,7 +6682,7 @@ void ex_win_close(int forceit, win_T *win, tabpage_T *tp) */ static void ex_tabclose(exarg_T *eap) { - tabpage_T *tp; + tabpage_T *tp; if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; @@ -6767,7 +6767,7 @@ void tabpage_close(int forceit) void tabpage_close_other(tabpage_T *tp, int forceit) { int done = 0; - win_T *wp; + win_T *wp; int h = tabline_height(); char_u prev_idx[NUMBUFLEN]; @@ -6993,11 +6993,11 @@ void alist_new(void) */ void alist_expand(int *fnum_list, int fnum_len) { - char_u **old_arg_files; + char_u **old_arg_files; int old_arg_count; - char_u **new_arg_files; + char_u **new_arg_files; int new_arg_file_count; - char_u *save_p_su = p_su; + char_u *save_p_su = p_su; int i; /* Don't use 'suffixes' here. This should work like the shell did the @@ -7159,8 +7159,8 @@ static void ex_wrongmodifier(exarg_T *eap) */ void ex_splitview(exarg_T *eap) { - win_T *old_curwin = curwin; - char_u *fname = NULL; + win_T *old_curwin = curwin; + char_u *fname = NULL; const bool use_tab = eap->cmdidx == CMD_tabedit || eap->cmdidx == CMD_tabfind || eap->cmdidx == CMD_tabnew; @@ -7364,7 +7364,7 @@ static void ex_mode(exarg_T *eap) static void ex_resize(exarg_T *eap) { int n; - win_T *wp = curwin; + win_T *wp = curwin; if (eap->addr_count > 0) { n = eap->line2; @@ -7396,7 +7396,7 @@ static void ex_resize(exarg_T *eap) */ static void ex_find(exarg_T *eap) { - char_u *fname; + char_u *fname; int count; fname = find_file_in_path(eap->arg, STRLEN(eap->arg), @@ -7579,8 +7579,8 @@ static void ex_swapname(exarg_T *eap) */ static void ex_syncbind(exarg_T *eap) { - win_T *save_curwin = curwin; - buf_T *save_curbuf = curbuf; + win_T *save_curwin = curwin; + buf_T *save_curbuf = curbuf; long topline; long y; linenr_T old_linenr = curwin->w_cursor.lnum; @@ -7696,7 +7696,7 @@ static void ex_read(exarg_T *eap) } } -static char_u *prev_dir = NULL; +static char_u *prev_dir = NULL; #if defined(EXITFREE) void free_cd_dir(void) @@ -7756,8 +7756,8 @@ void post_chdir(CdScope scope, bool trigger_dirchanged) /// `:cd`, `:tcd`, `:lcd`, `:chdir`, `:tchdir` and `:lchdir`. void ex_cd(exarg_T *eap) { - char_u *new_dir; - char_u *tofree; + char_u *new_dir; + char_u *tofree; new_dir = eap->arg; #if !defined(UNIX) @@ -7895,7 +7895,7 @@ void do_sleep(long msec) static void do_exmap(exarg_T *eap, int isabbrev) { int mode; - char_u *cmdp; + char_u *cmdp; cmdp = eap->cmd; mode = get_map_mode(&cmdp, eap->forceit || isabbrev); @@ -7936,7 +7936,7 @@ static void ex_winsize(exarg_T *eap) static void ex_wincmd(exarg_T *eap) { int xchar = NUL; - char_u *p; + char_u *p; if (*eap->arg == 'g' || *eap->arg == Ctrl_G) { // CTRL-W g and CTRL-W CTRL-G have an extra command character @@ -8190,7 +8190,7 @@ static void ex_later(exarg_T *eap) long count = 0; bool sec = false; bool file = false; - char_u *p = eap->arg; + char_u *p = eap->arg; if (*p == NUL) { count = 1; @@ -8223,9 +8223,9 @@ static void ex_later(exarg_T *eap) */ static void ex_redir(exarg_T *eap) { - char *mode; - char_u *fname; - char_u *arg = eap->arg; + char *mode; + char_u *fname; + char_u *arg = eap->arg; if (STRICMP(eap->arg, "END") == 0) { close_redir(); @@ -8416,7 +8416,7 @@ int vim_mkdir_emsg(const char *const name, const int prot) /// @return file descriptor, or NULL on failure. FILE *open_exfile(char_u *fname, int forceit, char *mode) { - FILE *fd; + FILE *fd; #ifdef UNIX // with Unix it is possible to open a directory @@ -8535,9 +8535,9 @@ static void ex_normal(exarg_T *eap) return; } save_state_T save_state; - char_u *arg = NULL; + char_u *arg = NULL; int l; - char_u *p; + char_u *p; if (ex_normal_lock > 0) { EMSG(_(e_secure)); @@ -8708,7 +8708,7 @@ static void ex_findpat(exarg_T *eap) { int whole = TRUE; long n; - char_u *p; + char_u *p; int action; switch (cmdnames[eap->cmdidx].cmd_name[2]) { @@ -8773,7 +8773,7 @@ static void ex_ptag(exarg_T *eap) */ static void ex_pedit(exarg_T *eap) { - win_T *curwin_save = curwin; + win_T *curwin_save = curwin; // Open the preview window or popup and make it the current window. g_do_tagpreview = p_pvh; @@ -8944,11 +8944,11 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum char_u **errormsg, int *escaped) { int i; - char_u *s; - char_u *result; - char_u *resultbuf = NULL; + char_u *s; + char_u *result; + char_u *resultbuf = NULL; size_t resultlen; - buf_T *buf; + buf_T *buf; int valid = VALID_HEAD | VALID_PATH; // Assume valid result. bool tilde_file = false; int skip_mod = false; @@ -9201,8 +9201,8 @@ static char_u *arg_all(void) { int len; int idx; - char_u *retval = NULL; - char_u *p; + char_u *retval = NULL; + char_u *p; /* * Do this loop two times: @@ -9262,13 +9262,13 @@ static char_u *arg_all(void) */ char_u *expand_sfile(char_u *arg) { - char_u *errormsg; + char_u *errormsg; size_t len; - char_u *result; - char_u *newres; - char_u *repl; + char_u *result; + char_u *newres; + char_u *repl; size_t srclen; - char_u *p; + char_u *p; result = vim_strsave(arg); @@ -9310,7 +9310,7 @@ char_u *expand_sfile(char_u *arg) */ static void ex_shada(exarg_T *eap) { - char_u *save_shada; + char_u *save_shada; save_shada = p_shada; if (*p_shada == NUL) { @@ -9404,7 +9404,7 @@ static TriState filetype_indent = kNone; */ static void ex_filetype(exarg_T *eap) { - char_u *arg = eap->arg; + char_u *arg = eap->arg; bool plugin = false; bool indent = false; diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 92b48c36cb..e87520359e 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -5,15 +5,13 @@ #include #include +#include +#include #include #include -#include -#include -#include "nvim/vim.h" #include "nvim/api/private/helpers.h" #include "nvim/ascii.h" -#include "nvim/fileio.h" #include "nvim/buffer.h" #include "nvim/buffer_updates.h" #include "nvim/change.h" @@ -25,8 +23,10 @@ #include "nvim/ex_cmds.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" +#include "nvim/fileio.h" #include "nvim/fold.h" #include "nvim/func_attr.h" +#include "nvim/garray.h" #include "nvim/getchar.h" #include "nvim/hashtab.h" #include "nvim/iconv.h" @@ -36,10 +36,13 @@ #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/garray.h" #include "nvim/move.h" #include "nvim/normal.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/os.h" +#include "nvim/os/os_defs.h" +#include "nvim/os/time.h" #include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/quickfix.h" @@ -47,21 +50,18 @@ #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/sha256.h" +#include "nvim/shada.h" #include "nvim/state.h" #include "nvim/strings.h" +#include "nvim/types.h" #include "nvim/ui.h" #include "nvim/ui_compositor.h" -#include "nvim/types.h" #include "nvim/undo.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/shada.h" -#include "nvim/os/os.h" -#include "nvim/os/os_defs.h" -#include "nvim/os/time.h" -#include "nvim/os/input.h" -#define BUFSIZE 8192 /* size of normal write buffer */ -#define SMBUFSIZE 256 /* size of emergency write buffer */ +#define BUFSIZE 8192 // size of normal write buffer +#define SMBUFSIZE 256 // size of emergency write buffer // For compatibility with libuv < 1.20.0 (tested on 1.18.0) #ifndef UV_FS_COPYFILE_FICLONE @@ -69,15 +69,15 @@ #endif #define HAS_BW_FLAGS -#define FIO_LATIN1 0x01 /* convert Latin1 */ -#define FIO_UTF8 0x02 /* convert UTF-8 */ -#define FIO_UCS2 0x04 /* convert UCS-2 */ -#define FIO_UCS4 0x08 /* convert UCS-4 */ -#define FIO_UTF16 0x10 /* convert UTF-16 */ -#define FIO_ENDIAN_L 0x80 /* little endian */ -#define FIO_NOCONVERT 0x2000 /* skip encoding conversion */ -#define FIO_UCSBOM 0x4000 /* check for BOM at start of file */ -#define FIO_ALL -1 /* allow all formats */ +#define FIO_LATIN1 0x01 // convert Latin1 +#define FIO_UTF8 0x02 // convert UTF-8 +#define FIO_UCS2 0x04 // convert UCS-2 +#define FIO_UCS4 0x08 // convert UCS-4 +#define FIO_UTF16 0x10 // convert UTF-16 +#define FIO_ENDIAN_L 0x80 // little endian +#define FIO_NOCONVERT 0x2000 // skip encoding conversion +#define FIO_UCSBOM 0x4000 // check for BOM at start of file +#define FIO_ALL -1 // allow all formats /* When converting, a read() or write() may leave some bytes to be converted * for the next call. The value is guessed... */ @@ -92,7 +92,7 @@ */ struct bw_info { int bw_fd; // file descriptor - char_u *bw_buf; // buffer with data to be written + char_u *bw_buf; // buffer with data to be written int bw_len; // length of data #ifdef HAS_BW_FLAGS int bw_flags; // FIO_ flags @@ -100,7 +100,7 @@ struct bw_info { char_u bw_rest[CONV_RESTLEN]; // not converted bytes int bw_restlen; // nr of bytes in bw_rest[] int bw_first; // first write call - char_u *bw_conv_buf; // buffer for writing converted chars + char_u *bw_conv_buf; // buffer for writing converted chars int bw_conv_buflen; // size of bw_conv_buf int bw_conv_error; // set for conversion error linenr_T bw_conv_error_lnum; // first line with error or zero @@ -114,8 +114,7 @@ struct bw_info { # include "fileio.c.generated.h" #endif -static char *e_auchangedbuf = N_( - "E812: Autocommands changed buffer or buffer name"); +static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name"); void filemess(buf_T *buf, char_u *name, char_u *s, int attr) { @@ -131,14 +130,16 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr) // For further ones overwrite the previous one, reset msg_scroll before // calling filemess(). msg_scroll_save = msg_scroll; - if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) + if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) { msg_scroll = FALSE; - if (!msg_scroll) /* wait a bit when overwriting an error msg */ + } + if (!msg_scroll) { // wait a bit when overwriting an error msg check_for_delay(FALSE); + } msg_start(); msg_scroll = msg_scroll_save; msg_scrolled_ign = TRUE; - /* may truncate the message to avoid a hit-return prompt */ + // may truncate the message to avoid a hit-return prompt msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr); msg_clr_eos(); ui_flush(); @@ -146,41 +147,33 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr) } -/* - * Read lines from file "fname" into the buffer after line "from". - * - * 1. We allocate blocks with try_malloc, as big as possible. - * 2. Each block is filled with characters from the file with a single read(). - * 3. The lines are inserted in the buffer with ml_append(). - * - * (caller must check that fname != NULL, unless READ_STDIN is used) - * - * "lines_to_skip" is the number of lines that must be skipped - * "lines_to_read" is the number of lines that are appended - * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM. - * - * flags: - * READ_NEW starting to edit a new buffer - * READ_FILTER reading filter output - * READ_STDIN read from stdin instead of a file - * READ_BUFFER read from curbuf instead of a file (converting after reading - * stdin) - * READ_DUMMY read into a dummy buffer (to check if file contents changed) - * READ_KEEP_UNDO don't clear undo info or read it from a file - * READ_FIFO read from fifo/socket instead of a file - * - * return FAIL for failure, NOTDONE for directory (failure), or OK - */ -int -readfile( - char_u *fname, - char_u *sfname, - linenr_T from, - linenr_T lines_to_skip, - linenr_T lines_to_read, - exarg_T *eap, // can be NULL! - int flags -) +/// Read lines from file "fname" into the buffer after line "from". +/// +/// 1. We allocate blocks with try_malloc, as big as possible. +/// 2. Each block is filled with characters from the file with a single read(). +/// 3. The lines are inserted in the buffer with ml_append(). +/// +/// (caller must check that fname != NULL, unless READ_STDIN is used) +/// +/// "lines_to_skip" is the number of lines that must be skipped +/// "lines_to_read" is the number of lines that are appended +/// When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM. +/// +/// flags: +/// READ_NEW starting to edit a new buffer +/// READ_FILTER reading filter output +/// READ_STDIN read from stdin instead of a file +/// READ_BUFFER read from curbuf instead of a file (converting after reading +/// stdin) +/// READ_DUMMY read into a dummy buffer (to check if file contents changed) +/// READ_KEEP_UNDO don't clear undo info or read it from a file +/// READ_FIFO read from fifo/socket instead of a file +/// +/// @param eap can be NULL! +/// +/// @return FAIL for failure, NOTDONE for directory (failure), or OK +int readfile(char_u *fname, char_u *sfname, linenr_T from, linenr_T lines_to_skip, + linenr_T lines_to_read, exarg_T *eap, int flags) { int fd = 0; int newfile = (flags & READ_NEW); @@ -191,15 +184,15 @@ readfile( int read_fifo = (flags & READ_FIFO); int set_options = newfile || read_buffer || (eap != NULL && eap->read_edit); - linenr_T read_buf_lnum = 1; /* next line to read from curbuf */ - colnr_T read_buf_col = 0; /* next char to read from this line */ + linenr_T read_buf_lnum = 1; // next line to read from curbuf + colnr_T read_buf_col = 0; // next char to read from this line char_u c; linenr_T lnum = from; - char_u *ptr = NULL; /* pointer into read buffer */ - char_u *buffer = NULL; /* read buffer */ - char_u *new_buffer = NULL; /* init to shut up gcc */ - char_u *line_start = NULL; /* init to shut up gcc */ - int wasempty; /* buffer was empty before reading */ + char_u *ptr = NULL; // pointer into read buffer + char_u *buffer = NULL; // read buffer + char_u *new_buffer = NULL; // init to shut up gcc + char_u *line_start = NULL; // init to shut up gcc + int wasempty; // buffer was empty before reading colnr_T len; long size = 0; uint8_t *p = NULL; @@ -209,12 +202,12 @@ readfile( int read_undo_file = false; int split = 0; // number of split lines linenr_T linecnt; - int error = FALSE; /* errors encountered */ - int ff_error = EOL_UNKNOWN; /* file format with errors */ - long linerest = 0; /* remaining chars in line */ + int error = FALSE; // errors encountered + int ff_error = EOL_UNKNOWN; // file format with errors + long linerest = 0; // remaining chars in line int perm = 0; #ifdef UNIX - int swap_mode = -1; /* protection bits for swap file */ + int swap_mode = -1; // protection bits for swap file #endif int fileformat = 0; // end-of-line format bool keep_fileformat = false; @@ -234,11 +227,11 @@ readfile( int bad_char_behavior = BAD_REPLACE; /* BAD_KEEP, BAD_DROP or character to * replace with */ - char_u *tmpname = NULL; /* name of 'charconvert' output file */ + char_u *tmpname = NULL; // name of 'charconvert' output file int fio_flags = 0; - char_u *fenc; // fileencoding to use + char_u *fenc; // fileencoding to use bool fenc_alloced; // fenc_next is in allocated memory - char_u *fenc_next = NULL; // next item in 'fencs' or NULL + char_u *fenc_next = NULL; // next item in 'fencs' or NULL bool advance_fenc = false; long real_size = 0; # ifdef HAVE_ICONV @@ -246,21 +239,21 @@ readfile( int did_iconv = false; // TRUE when iconv() failed and trying // 'charconvert' next # endif - int converted = FALSE; /* TRUE if conversion done */ + int converted = FALSE; // TRUE if conversion done int notconverted = FALSE; /* TRUE if conversion wanted but it wasn't possible */ char_u conv_rest[CONV_RESTLEN]; - int conv_restlen = 0; /* nr of bytes in conv_rest[] */ - buf_T *old_curbuf; - char_u *old_b_ffname; - char_u *old_b_fname; + int conv_restlen = 0; // nr of bytes in conv_rest[] + buf_T *old_curbuf; + char_u *old_b_ffname; + char_u *old_b_fname; int using_b_ffname; int using_b_fname; static char *msg_is_a_directory = N_("is a directory"); au_did_filetype = false; // reset before triggering any autocommands - curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */ + curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read /* * If there is no file name yet, use the one for the read file. @@ -273,8 +266,9 @@ readfile( && fname != NULL && vim_strchr(p_cpo, CPO_FNAMER) != NULL && !(flags & READ_DUMMY)) { - if (set_rw_fname(fname, sfname) == FAIL) + if (set_rw_fname(fname, sfname) == FAIL) { return FAIL; + } } /* Remember the initial values of curbuf, curbuf->b_ffname and @@ -315,7 +309,7 @@ readfile( pos = curbuf->b_op_start; - /* Set '[ mark to the line above where the lines go (line 1 if zero). */ + // Set '[ mark to the line above where the lines go (line 1 if zero). curbuf->b_op_start.lnum = ((from == 0) ? 1 : from); curbuf->b_op_start.col = 0; @@ -346,11 +340,11 @@ readfile( curbuf->b_op_start = pos; } - if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0) - msg_scroll = FALSE; /* overwrite previous file message */ - else - msg_scroll = TRUE; /* don't overwrite previous file message */ - + if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0) { + msg_scroll = FALSE; // overwrite previous file message + } else { + msg_scroll = TRUE; // don't overwrite previous file message + } // If the name is too long we might crash further on, quit here. if (fname != NULL && *fname != NUL) { size_t namelen = STRLEN(fname); @@ -397,7 +391,7 @@ readfile( } } - /* Set default or forced 'fileformat' and 'binary'. */ + // Set default or forced 'fileformat' and 'binary'. set_file_options(set_options, eap); /* @@ -407,8 +401,9 @@ readfile( * Only set/reset b_p_ro when BF_CHECK_RO is set. */ check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO)); - if (check_readonly && !readonlymode) + if (check_readonly && !readonlymode) { curbuf->b_p_ro = FALSE; + } if (newfile && !read_stdin && !read_buffer && !read_fifo) { // Remember time of file. @@ -466,7 +461,7 @@ readfile( * "nofile" or "nowrite" buffer type. */ if (!bt_dontwrite(curbuf)) { check_need_swap(newfile); - /* SwapExists autocommand may mess things up */ + // SwapExists autocommand may mess things up if (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) @@ -493,19 +488,20 @@ readfile( // remember the current fileformat save_file_ff(curbuf); - if (aborting()) /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing return FAIL; - return OK; /* a new file is not an error */ + } + return OK; // a new file is not an error } else { filemess(curbuf, sfname, (char_u *)( - (fd == UV_EFBIG) ? _("[File too big]") : + (fd == UV_EFBIG) ? _("[File too big]") : # if defined(UNIX) && defined(EOVERFLOW) - // libuv only returns -errno in Unix and in Windows open() does not - // set EOVERFLOW - (fd == -EOVERFLOW) ? _("[File too big]") : + // libuv only returns -errno in Unix and in Windows open() does not + // set EOVERFLOW + (fd == -EOVERFLOW) ? _("[File too big]") : # endif - _("[Permission Denied]")), 0); - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + _("[Permission Denied]")), 0); + curbuf->b_p_ro = TRUE; // must use "w!" now } return FAIL; @@ -513,10 +509,11 @@ readfile( /* * Only set the 'ro' flag for readonly files the first time they are - * loaded. Help files always get readonly mode + * loaded. Help files always get readonly mode */ - if ((check_readonly && file_readonly) || curbuf->b_help) + if ((check_readonly && file_readonly) || curbuf->b_help) { curbuf->b_p_ro = TRUE; + } if (set_options) { /* Don't change 'eol' if reading from buffer as it will already be @@ -573,12 +570,13 @@ readfile( // If "Quit" selected at ATTENTION dialog, don't load the file. if (swap_exists_action == SEA_QUIT) { - if (!read_buffer && !read_stdin) + if (!read_buffer && !read_stdin) { close(fd); + } return FAIL; } - ++no_wait_return; /* don't wait for return yet */ + ++no_wait_return; // don't wait for return yet /* * Set '[ mark to the line above where the lines go (line 1 if zero). @@ -627,10 +625,10 @@ readfile( msg_scroll = m; } - if (aborting()) { /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing --no_wait_return; msg_scroll = msg_save; - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + curbuf->b_p_ro = TRUE; // must use "w!" now return FAIL; } /* @@ -646,16 +644,17 @@ readfile( || (fd = os_open((char *)fname, O_RDONLY, 0)) < 0)) { --no_wait_return; msg_scroll = msg_save; - if (fd < 0) + if (fd < 0) { EMSG(_("E200: *ReadPre autocommands made the file unreadable")); - else + } else { EMSG(_("E201: *ReadPre autocommands must not change current buffer")); - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + } + curbuf->b_p_ro = TRUE; // must use "w!" now return FAIL; } } - /* Autocommands may add lines to the file, need to check if it is empty */ + // Autocommands may add lines to the file, need to check if it is empty wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY); if (!recoverymode && !filtering && !(flags & READ_DUMMY)) { @@ -664,7 +663,7 @@ readfile( } } - msg_scroll = FALSE; /* overwrite the file message */ + msg_scroll = FALSE; // overwrite the file message /* * Set linecnt now, before the "retry" caused by a wrong guess for @@ -672,13 +671,15 @@ readfile( */ linecnt = curbuf->b_ml.ml_line_count; - /* "++bad=" argument. */ + // "++bad=" argument. if (eap != NULL && eap->bad_char != 0) { bad_char_behavior = eap->bad_char; - if (set_options) + if (set_options) { curbuf->b_bad_char = eap->bad_char; - } else + } + } else { curbuf->b_bad_char = 0; + } /* * Decide which 'encoding' to use or use first. @@ -715,16 +716,16 @@ readfile( * - "fileformat" check failed: try another * * Variables set for special retry actions: - * "file_rewind" Rewind the file to start reading it again. - * "advance_fenc" Advance "fenc" using "fenc_next". - * "skip_read" Re-use already read bytes (BOM detected). - * "did_iconv" iconv() conversion failed, try 'charconvert'. + * "file_rewind" Rewind the file to start reading it again. + * "advance_fenc" Advance "fenc" using "fenc_next". + * "skip_read" Re-use already read bytes (BOM detected). + * "did_iconv" iconv() conversion failed, try 'charconvert'. * "keep_fileformat" Don't reset "fileformat". * * Other status indicators: - * "tmpname" When != NULL did conversion with 'charconvert'. - * Output file has to be deleted afterwards. - * "iconv_fd" When != -1 did conversion with iconv(). + * "tmpname" When != NULL did conversion with 'charconvert'. + * Output file has to be deleted afterwards. + * "iconv_fd" When != -1 did conversion with iconv(). */ retry: @@ -759,17 +760,19 @@ retry: if (eap != NULL && eap->force_ff != 0) { fileformat = get_fileformat_force(curbuf, eap); try_unix = try_dos = try_mac = FALSE; - } else if (curbuf->b_p_bin) - fileformat = EOL_UNIX; /* binary: use Unix format */ - else if (*p_ffs == NUL) - fileformat = get_fileformat(curbuf); /* use format from buffer */ - else - fileformat = EOL_UNKNOWN; /* detect from file */ + } else if (curbuf->b_p_bin) { + fileformat = EOL_UNIX; // binary: use Unix format + } else if (*p_ffs == + NUL) { + fileformat = get_fileformat(curbuf); // use format from buffer + } else { + fileformat = EOL_UNKNOWN; // detect from file + } } # ifdef HAVE_ICONV if (iconv_fd != (iconv_t)-1) { - /* aborted conversion with iconv(), close the descriptor */ + // aborted conversion with iconv(), close the descriptor iconv_close(iconv_fd); iconv_fd = (iconv_t)-1; } @@ -786,13 +789,15 @@ retry: * without conversion. */ notconverted = TRUE; conv_error = 0; - if (fenc_alloced) + if (fenc_alloced) { xfree(fenc); + } fenc = (char_u *)""; fenc_alloced = false; } else { - if (fenc_alloced) + if (fenc_alloced) { xfree(fenc); + } if (fenc_next != NULL) { fenc = next_fenc(&fenc_next, &fenc_alloced); } else { @@ -813,7 +818,6 @@ retry: fio_flags = 0; converted = need_conversion(fenc); if (converted) { - /* "ucs-bom" means we need to check the first bytes of the file * for a BOM. */ if (STRCMP(fenc, ENC_UCSBOM) == 0) { @@ -834,8 +838,7 @@ retry: # ifdef HAVE_ICONV // Try using iconv() if we can't convert internally. if (fio_flags == 0 - && !did_iconv - ) { + && !did_iconv) { iconv_fd = (iconv_t)my_iconv_open((char_u *)"utf-8", fenc); } # endif @@ -861,7 +864,7 @@ retry: // Conversion failed. Try another one. advance_fenc = true; if (fd < 0) { - /* Re-opening the original file failed! */ + // Re-opening the original file failed! EMSG(_("E202: Conversion made file unreadable!")); error = TRUE; goto failed; @@ -901,8 +904,9 @@ retry: && !read_fifo && !read_stdin && !read_buffer); - if (read_undo_file) + if (read_undo_file) { sha256_start(&sha_ctx); + } } while (!error && !got_int) { @@ -939,8 +943,9 @@ retry: error = TRUE; break; } - if (linerest) /* copy characters from the previous buffer */ + if (linerest) { // copy characters from the previous buffer memmove(new_buffer, ptr - linerest, (size_t)linerest); + } xfree(buffer); buffer = new_buffer; ptr = buffer + linerest; @@ -972,7 +977,7 @@ retry: size = size / ICONV_MULT; // worst case } # ifdef HAVE_ICONV - } + } # endif if (conv_restlen > 0) { // Insert unconverted bytes from previous line. @@ -986,9 +991,9 @@ retry: * Read bytes from curbuf. Used for converting text read * from stdin. */ - if (read_buf_lnum > from) + if (read_buf_lnum > from) { size = 0; - else { + } else { int n, ni; long tlen; @@ -1002,10 +1007,11 @@ retry: * below. */ n = (int)(size - tlen); for (ni = 0; ni < n; ++ni) { - if (p[ni] == NL) + if (p[ni] == NL) { ptr[tlen++] = NUL; - else + } else { ptr[tlen++] = p[ni]; + } } read_buf_col += n; break; @@ -1013,18 +1019,20 @@ retry: /* Append whole line and new-line. Change NL * to NUL to reverse the effect done below. */ for (ni = 0; ni < n; ++ni) { - if (p[ni] == NL) + if (p[ni] == NL) { ptr[tlen++] = NUL; - else + } else { ptr[tlen++] = p[ni]; + } } ptr[tlen++] = NL; read_buf_col = 0; if (++read_buf_lnum > from) { /* When the last line didn't have an * end-of-line don't add it now either. */ - if (!curbuf->b_p_eol) + if (!curbuf->b_p_eol) { --tlen; + } size = tlen; break; } @@ -1039,30 +1047,33 @@ retry: } if (size <= 0) { - if (size < 0) /* read error */ + if (size < 0) { // read error error = TRUE; - else if (conv_restlen > 0) { + } else if (conv_restlen > 0) { /* * Reached end-of-file but some trailing bytes could * not be converted. Truncated file? */ - /* When we did a conversion report an error. */ + // When we did a conversion report an error. if (fio_flags != 0 # ifdef HAVE_ICONV || iconv_fd != (iconv_t)-1 # endif ) { - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = curbuf->b_ml.ml_line_count - linecnt + 1; + } } - /* Remember the first linenr with an illegal byte */ - else if (illegal_byte == 0) + // Remember the first linenr with an illegal byte + else if (illegal_byte == 0) { illegal_byte = curbuf->b_ml.ml_line_count - linecnt + 1; + } if (bad_char_behavior == BAD_DROP) { *(ptr - conv_restlen) = NUL; conv_restlen = 0; @@ -1106,17 +1117,18 @@ retry: || (!curbuf->b_p_bomb && tmpname == NULL && (*fenc == 'u' || *fenc == NUL)))) { - char_u *ccname; + char_u *ccname; int blen; - /* no BOM detection in a short file or in binary mode */ - if (size < 2 || curbuf->b_p_bin) + // no BOM detection in a short file or in binary mode + if (size < 2 || curbuf->b_p_bin) { ccname = NULL; - else + } else { ccname = check_for_bom(ptr, size, &blen, - fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc)); + fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc)); + } if (ccname != NULL) { - /* Remove BOM from the text */ + // Remove BOM from the text filesize += blen; size -= blen; memmove(ptr, ptr + blen, (size_t)size); @@ -1131,27 +1143,29 @@ retry: // No BOM detected: retry with next encoding. advance_fenc = true; } else { - /* BOM detected: set "fenc" and jump back */ - if (fenc_alloced) + // BOM detected: set "fenc" and jump back + if (fenc_alloced) { xfree(fenc); + } fenc = ccname; fenc_alloced = false; } - /* retry reading without getting new bytes or rewinding */ + // retry reading without getting new bytes or rewinding skip_read = TRUE; goto retry; } } - /* Include not converted bytes. */ + // Include not converted bytes. ptr -= conv_restlen; size += conv_restlen; conv_restlen = 0; /* * Break here for a read error or end-of-file. */ - if (size <= 0) + if (size <= 0) { break; + } # ifdef HAVE_ICONV if (iconv_fd != (iconv_t)-1) { @@ -1159,8 +1173,8 @@ retry: * Attempt conversion of the read bytes to 'encoding' using * iconv(). */ - const char *fromp; - char *top; + const char *fromp; + char *top; size_t from_size; size_t to_size; @@ -1176,16 +1190,18 @@ retry: * alternative (help files). */ while ((iconv(iconv_fd, (void *)&fromp, &from_size, - &top, &to_size) + &top, &to_size) == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) || from_size > CONV_RESTLEN) { - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, (char_u *)top); + ptr, (char_u *)top); + } - /* Deal with a bad byte and continue with the next. */ + // Deal with a bad byte and continue with the next. ++fromp; --from_size; if (bad_char_behavior == BAD_KEEP) { @@ -1204,7 +1220,7 @@ retry: conv_restlen = (int)from_size; } - /* move the linerest to before the converted characters */ + // move the linerest to before the converted characters line_start = ptr - linerest; memmove(line_start, buffer, (size_t)linerest); size = (long)((char_u *)top - ptr); @@ -1213,8 +1229,8 @@ retry: if (fio_flags != 0) { unsigned int u8c; - char_u *dest; - char_u *tail = NULL; + char_u *dest; + char_u *tail = NULL; // Convert Unicode or Latin1 to UTF-8. // Go from end to start through the buffer, because the number @@ -1225,22 +1241,25 @@ retry: if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8) { p = ptr + size; if (fio_flags == FIO_UTF8) { - /* Check for a trailing incomplete UTF-8 sequence */ + // Check for a trailing incomplete UTF-8 sequence tail = ptr + size - 1; - while (tail > ptr && (*tail & 0xc0) == 0x80) + while (tail > ptr && (*tail & 0xc0) == 0x80) { --tail; - if (tail + utf_byte2len(*tail) <= ptr + size) + } + if (tail + utf_byte2len(*tail) <= ptr + size) { tail = NULL; - else + } else { p = tail; + } } } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { - /* Check for a trailing byte */ + // Check for a trailing byte p = ptr + (size & ~1); - if (size & 1) + if (size & 1) { tail = p; + } if ((fio_flags & FIO_UTF16) && p > ptr) { - /* Check for a trailing leading word */ + // Check for a trailing leading word if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 8); u8c += *--p; @@ -1248,16 +1267,18 @@ retry: u8c = *--p; u8c += (*--p << 8); } - if (u8c >= 0xd800 && u8c <= 0xdbff) + if (u8c >= 0xd800 && u8c <= 0xdbff) { tail = p; - else + } else { p += 2; + } } - } else { /* FIO_UCS4 */ - /* Check for trailing 1, 2 or 3 bytes */ + } else { // FIO_UCS4 + // Check for trailing 1, 2 or 3 bytes p = ptr + (size & ~3); - if (size & 3) + if (size & 3) { tail = p; + } } /* If there is a trailing incomplete sequence move it to @@ -1270,9 +1291,9 @@ retry: while (p > ptr) { - if (fio_flags & FIO_LATIN1) + if (fio_flags & FIO_LATIN1) { u8c = *--p; - else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { + } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 8); u8c += *--p; @@ -1285,16 +1306,20 @@ retry: int u16c; if (p == ptr) { - /* Missing leading word. */ - if (can_retry) + // Missing leading word. + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, p); - if (bad_char_behavior == BAD_DROP) + ptr, p); + } + if (bad_char_behavior == BAD_DROP) { continue; - if (bad_char_behavior != BAD_KEEP) + } + if (bad_char_behavior != BAD_KEEP) { u8c = bad_char_behavior; + } } /* found second word of double-word, get the first @@ -1309,17 +1334,21 @@ retry: u8c = 0x10000 + ((u16c & 0x3ff) << 10) + (u8c & 0x3ff); - /* Check if the word is indeed a leading word. */ + // Check if the word is indeed a leading word. if (u16c < 0xd800 || u16c > 0xdbff) { - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, p); - if (bad_char_behavior == BAD_DROP) + ptr, p); + } + if (bad_char_behavior == BAD_DROP) { continue; - if (bad_char_behavior != BAD_KEEP) + } + if (bad_char_behavior != BAD_KEEP) { u8c = bad_char_behavior; + } } } } else if (fio_flags & FIO_UCS4) { @@ -1328,16 +1357,16 @@ retry: u8c += (unsigned)(*--p) << 16; u8c += (unsigned)(*--p) << 8; u8c += *--p; - } else { /* big endian */ + } else { // big endian u8c = *--p; u8c += (unsigned)(*--p) << 8; u8c += (unsigned)(*--p) << 16; u8c += (unsigned)(*--p) << 24; } - } else { /* UTF-8 */ - if (*--p < 0x80) + } else { // UTF-8 + if (*--p < 0x80) { u8c = *p; - else { + } else { len = utf_head_off(ptr, p); p -= len; u8c = utf_ptr2char(p); @@ -1345,15 +1374,19 @@ retry: /* Not a valid UTF-8 character, retry with * another fenc when possible, otherwise just * report the error. */ - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, p); - if (bad_char_behavior == BAD_DROP) + ptr, p); + } + if (bad_char_behavior == BAD_DROP) { continue; - if (bad_char_behavior != BAD_KEEP) + } + if (bad_char_behavior != BAD_KEEP) { u8c = bad_char_behavior; + } } } } @@ -1407,31 +1440,35 @@ retry: /* Illegal byte. If we can try another encoding * do that, unless at EOF where a truncated * file is more likely than a conversion error. */ - if (can_retry && !incomplete_tail) + if (can_retry && !incomplete_tail) { break; + } # ifdef HAVE_ICONV // When we did a conversion report an error. if (iconv_fd != (iconv_t)-1 && conv_error == 0) { conv_error = readfile_linenr(linecnt, ptr, p); } # endif - /* Remember the first linenr with an illegal byte */ - if (conv_error == 0 && illegal_byte == 0) + // Remember the first linenr with an illegal byte + if (conv_error == 0 && illegal_byte == 0) { illegal_byte = readfile_linenr(linecnt, ptr, p); + } - /* Drop, keep or replace the bad byte. */ + // Drop, keep or replace the bad byte. if (bad_char_behavior == BAD_DROP) { memmove(p, p + 1, todo - 1); --p; --size; - } else if (bad_char_behavior != BAD_KEEP) + } else if (bad_char_behavior != BAD_KEEP) { *p = bad_char_behavior; - } else + } + } else { p += l - 1; + } } } if (p < ptr + size && !incomplete_tail) { - /* Detected a UTF-8 error. */ + // Detected a UTF-8 error. rewind_retry: // Retry reading with another conversion. # ifdef HAVE_ICONV @@ -1443,21 +1480,21 @@ rewind_retry: // use next item from 'fileencodings' advance_fenc = true; # ifdef HAVE_ICONV - } + } # endif file_rewind = true; goto retry; } } - /* count the number of characters (after conversion!) */ + // count the number of characters (after conversion!) filesize += size; /* * when reading the first part of a file: guess EOL type */ if (fileformat == EOL_UNKNOWN) { - /* First try finding a NL, for Dos and Unix */ + // First try finding a NL, for Dos and Unix if (try_dos || try_unix) { // Reset the carriage return counter. if (try_mac) { @@ -1467,32 +1504,36 @@ rewind_retry: for (p = ptr; p < ptr + size; ++p) { if (*p == NL) { if (!try_unix - || (try_dos && p > ptr && p[-1] == CAR)) + || (try_dos && p > ptr && p[-1] == CAR)) { fileformat = EOL_DOS; - else + } else { fileformat = EOL_UNIX; + } break; } else if (*p == CAR && try_mac) { try_mac++; } } - /* Don't give in to EOL_UNIX if EOL_MAC is more likely */ + // Don't give in to EOL_UNIX if EOL_MAC is more likely if (fileformat == EOL_UNIX && try_mac) { - /* Need to reset the counters when retrying fenc. */ + // Need to reset the counters when retrying fenc. try_mac = 1; try_unix = 1; - for (; p >= ptr && *p != CAR; p--) + for (; p >= ptr && *p != CAR; p--) { ; + } if (p >= ptr) { for (p = ptr; p < ptr + size; ++p) { - if (*p == NL) + if (*p == NL) { try_unix++; - else if (*p == CAR) + } else if (*p == CAR) { try_mac++; + } } - if (try_mac > try_unix) + if (try_mac > try_unix) { fileformat = EOL_MAC; + } } } else if (fileformat == EOL_UNKNOWN && try_mac == 1) { // Looking for CR but found no end-of-line markers at all: @@ -1501,13 +1542,15 @@ rewind_retry: } } - /* No NL found: may use Mac format */ - if (fileformat == EOL_UNKNOWN && try_mac) + // No NL found: may use Mac format + if (fileformat == EOL_UNKNOWN && try_mac) { fileformat = EOL_MAC; + } - /* Still nothing found? Use first format in 'ffs' */ - if (fileformat == EOL_UNKNOWN) + // Still nothing found? Use first format in 'ffs' + if (fileformat == EOL_UNKNOWN) { fileformat = default_fileformat(); + } // May set 'p_ff' if editing a new file. if (set_options) { @@ -1523,44 +1566,48 @@ rewind_retry: if (fileformat == EOL_MAC) { --ptr; while (++ptr, --size >= 0) { - /* catch most common case first */ - if ((c = *ptr) != NUL && c != CAR && c != NL) + // catch most common case first + if ((c = *ptr) != NUL && c != CAR && c != NL) { continue; - if (c == NUL) - *ptr = NL; /* NULs are replaced by newlines! */ - else if (c == NL) - *ptr = CAR; /* NLs are replaced by CRs! */ - else { + } + if (c == NUL) { + *ptr = NL; // NULs are replaced by newlines! + } else if (c == NL) { + *ptr = CAR; // NLs are replaced by CRs! + } else { if (skip_count == 0) { - *ptr = NUL; /* end of line */ - len = (colnr_T) (ptr - line_start + 1); + *ptr = NUL; // end of line + len = (colnr_T)(ptr - line_start + 1); if (ml_append(lnum, line_start, len, newfile) == FAIL) { error = TRUE; break; } - if (read_undo_file) + if (read_undo_file) { sha256_update(&sha_ctx, line_start, len); + } ++lnum; if (--read_count == 0) { - error = TRUE; /* break loop */ - line_start = ptr; /* nothing left to write */ + error = TRUE; // break loop + line_start = ptr; // nothing left to write break; } - } else + } else { --skip_count; + } line_start = ptr + 1; } } } else { --ptr; while (++ptr, --size >= 0) { - if ((c = *ptr) != NUL && c != NL) /* catch most common case */ + if ((c = *ptr) != NUL && c != NL) { // catch most common case continue; - if (c == NUL) - *ptr = NL; /* NULs are replaced by newlines! */ - else { + } + if (c == NUL) { + *ptr = NL; // NULs are replaced by newlines! + } else { if (skip_count == 0) { - *ptr = NUL; /* end of line */ + *ptr = NUL; // end of line len = (colnr_T)(ptr - line_start + 1); if (fileformat == EOL_DOS) { if (ptr > line_start && ptr[-1] == CAR) { @@ -1577,8 +1624,9 @@ rewind_retry: && (read_buffer || vim_lseek(fd, (off_T)0L, SEEK_SET) == 0)) { fileformat = EOL_UNIX; - if (set_options) + if (set_options) { set_fileformat(EOL_UNIX, OPT_LOCAL); + } file_rewind = true; keep_fileformat = true; goto retry; @@ -1590,16 +1638,18 @@ rewind_retry: error = TRUE; break; } - if (read_undo_file) + if (read_undo_file) { sha256_update(&sha_ctx, line_start, len); + } ++lnum; if (--read_count == 0) { - error = TRUE; /* break loop */ - line_start = ptr; /* nothing left to write */ + error = TRUE; // break loop + line_start = ptr; // nothing left to write break; } - } else + } else { --skip_count; + } line_start = ptr + 1; } } @@ -1609,9 +1659,10 @@ rewind_retry: } failed: - /* not an error, max. number of lines reached */ - if (error && read_count == 0) + // not an error, max. number of lines reached + if (error && read_count == 0) { error = FALSE; + } /* * If we get EOF in the middle of a line, note the fact and @@ -1625,16 +1676,18 @@ failed: && fileformat == EOL_DOS && *line_start == Ctrl_Z && ptr == line_start + 1)) { - /* remember for when writing */ - if (set_options) + // remember for when writing + if (set_options) { curbuf->b_p_eol = FALSE; + } *ptr = NUL; len = (colnr_T)(ptr - line_start + 1); - if (ml_append(lnum, line_start, len, newfile) == FAIL) + if (ml_append(lnum, line_start, len, newfile) == FAIL) { error = TRUE; - else { - if (read_undo_file) + } else { + if (read_undo_file) { sha256_update(&sha_ctx, line_start, len); + } read_no_eol_lnum = ++lnum; } } @@ -1646,8 +1699,9 @@ failed: // Also for ":read ++edit file". set_string_option_direct("fenc", -1, fenc, OPT_FREE | OPT_LOCAL, 0); } - if (fenc_alloced) + if (fenc_alloced) { xfree(fenc); + } # ifdef HAVE_ICONV if (iconv_fd != (iconv_t)-1) { iconv_close(iconv_fd); @@ -1679,13 +1733,13 @@ failed: os_remove((char *)tmpname); // delete converted file xfree(tmpname); } - --no_wait_return; /* may wait for return now */ + --no_wait_return; // may wait for return now /* * In recovery mode everything but autocommands is skipped. */ if (!recoverymode) { - /* need to delete the last line, which comes from the empty buffer */ + // need to delete the last line, which comes from the empty buffer if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY)) { ml_delete(curbuf->b_ml.ml_line_count, false); linecnt--; @@ -1695,8 +1749,9 @@ failed: curbuf->deleted_codepoints = 0; curbuf->deleted_codeunits = 0; linecnt = curbuf->b_ml.ml_line_count - linecnt; - if (filesize == 0) + if (filesize == 0) { linecnt = 0; + } if (newfile || read_buffer) { redraw_curbuf_later(NOT_VALID); /* After reading the text into the buffer the diff info needs to @@ -1705,8 +1760,9 @@ failed: /* All folds in the window are invalid now. Mark them for update * before triggering autocommands. */ foldUpdateAll(curwin); - } else if (linecnt) /* appended at least one line */ + } else if (linecnt) { // appended at least one line appended_lines_mark(from, linecnt); + } /* * If we were reading from the same terminal as where messages go, @@ -1720,12 +1776,13 @@ failed: if (got_int) { if (!(flags & READ_DUMMY)) { filemess(curbuf, sfname, (char_u *)_(e_interr), 0); - if (newfile) - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + if (newfile) { + curbuf->b_p_ro = TRUE; // must use "w!" now + } } msg_scroll = msg_save; check_marks_read(); - return OK; /* an interrupt isn't really an error */ + return OK; // an interrupt isn't really an error } if (!filtering && !(flags & READ_DUMMY)) { @@ -1742,7 +1799,7 @@ failed: c = TRUE; } # ifdef OPEN_CHR_FILES - if (S_ISCHR(perm)) { /* or character special */ + if (S_ISCHR(perm)) { // or character special STRCAT(IObuff, _("[character special]")); c = TRUE; } @@ -1773,18 +1830,19 @@ failed: } if (conv_error != 0) { sprintf((char *)IObuff + STRLEN(IObuff), - _("[CONVERSION ERROR in line %" PRId64 "]"), (int64_t)conv_error); + _("[CONVERSION ERROR in line %" PRId64 "]"), (int64_t)conv_error); c = TRUE; } else if (illegal_byte > 0) { sprintf((char *)IObuff + STRLEN(IObuff), - _("[ILLEGAL BYTE in line %" PRId64 "]"), (int64_t)illegal_byte); + _("[ILLEGAL BYTE in line %" PRId64 "]"), (int64_t)illegal_byte); c = TRUE; - } else if (error) { + } else if (error) { STRCAT(IObuff, _("[READ ERRORS]")); c = TRUE; } - if (msg_add_fileformat(fileformat)) + if (msg_add_fileformat(fileformat)) { c = TRUE; + } msg_add_lines(c, (long)linecnt, filesize); @@ -1808,25 +1866,27 @@ failed: msg_scrolled_ign = FALSE; } - /* with errors writing the file requires ":w!" */ + // with errors writing the file requires ":w!" if (newfile && (error || conv_error != 0 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP) - )) + )) { curbuf->b_p_ro = TRUE; + } - u_clearline(); /* cannot use "U" command after adding lines */ + u_clearline(); // cannot use "U" command after adding lines /* * In Ex mode: cursor at last new line. * Otherwise: cursor at first new line. */ - if (exmode_active) + if (exmode_active) { curwin->w_cursor.lnum = from + linecnt; - else + } else { curwin->w_cursor.lnum = from + 1; + } check_cursor_lnum(); - beginline(BL_WHITE | BL_FIX); /* on first non-blank */ + beginline(BL_WHITE | BL_FIX); // on first non-blank /* * Set '[ and '] marks to the newly read lines. @@ -1835,7 +1895,6 @@ failed: curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = from + linecnt; curbuf->b_op_end.col = 0; - } msg_scroll = msg_save; @@ -1854,8 +1913,9 @@ failed: /* When reloading a buffer put the cursor at the first line that is * different. */ - if (flags & READ_KEEP_UNDO) + if (flags & READ_KEEP_UNDO) { u_find_first_changed(); + } /* * When opening a new file locate undo info and read it. @@ -1873,8 +1933,9 @@ failed: /* Save the fileformat now, otherwise the buffer will be considered * modified if the format/encoding was automatically detected. */ - if (set_options) + if (set_options) { save_file_ff(curbuf); + } /* * The output from the autocommands should not overwrite anything and @@ -1906,8 +1967,9 @@ failed: } } - if (recoverymode && error) + if (recoverymode && error) { return FAIL; + } return OK; } @@ -1930,25 +1992,24 @@ bool is_dev_fd_file(char_u *fname) #endif -/* - * From the current line count and characters read after that, estimate the - * line number where we are now. - * Used for error messages that include a line number. - */ -static linenr_T -readfile_linenr( - linenr_T linecnt, // line count before reading more bytes - char_u *p, // start of more bytes read - char_u *endp // end of more bytes read -) +/// From the current line count and characters read after that, estimate the +/// line number where we are now. +/// Used for error messages that include a line number. +/// +/// @param linecnt line count before reading more bytes +/// @param p start of more bytes read +/// @param endp end of more bytes read +static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp) { - char_u *s; + char_u *s; linenr_T lnum; lnum = curbuf->b_ml.ml_line_count - linecnt + 1; - for (s = p; s < endp; ++s) - if (*s == '\n') + for (s = p; s < endp; ++s) { + if (*s == '\n') { ++lnum; + } + } return lnum; } @@ -1977,15 +2038,16 @@ void prep_exarg(exarg_T *eap, const buf_T *buf) */ void set_file_options(int set_options, exarg_T *eap) { - /* set default 'fileformat' */ + // set default 'fileformat' if (set_options) { - if (eap != NULL && eap->force_ff != 0) + if (eap != NULL && eap->force_ff != 0) { set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL); - else if (*p_ffs != NUL) + } else if (*p_ffs != NUL) { set_fileformat(default_fileformat(), OPT_LOCAL); + } } - /* set or reset 'binary' */ + // set or reset 'binary' if (eap != NULL && eap->force_bin != 0) { int oldval = curbuf->b_p_bin; @@ -2015,8 +2077,8 @@ void set_forced_fenc(exarg_T *eap) static char_u *next_fenc(char_u **pp, bool *alloced) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { - char_u *p; - char_u *r; + char_u *p; + char_u *r; *alloced = false; if (**pp == NUL) { @@ -2038,29 +2100,26 @@ static char_u *next_fenc(char_u **pp, bool *alloced) return r; } -/* - * Convert a file with the 'charconvert' expression. - * This closes the file which is to be read, converts it and opens the - * resulting file for reading. - * Returns name of the resulting converted file (the caller should delete it - * after reading it). - * Returns NULL if the conversion failed ("*fdp" is not set) . - */ -static char_u * -readfile_charconvert ( - char_u *fname, /* name of input file */ - char_u *fenc, /* converted from */ - int *fdp /* in/out: file descriptor of file */ -) +/// Convert a file with the 'charconvert' expression. +/// This closes the file which is to be read, converts it and opens the +/// resulting file for reading. +/// +/// @param fname name of input file +/// @param fenc converted from +/// @param fdp in/out: file descriptor of file +/// +/// @return name of the resulting converted file (the caller should delete it after reading it). +/// Returns NULL if the conversion failed ("*fdp" is not set) . +static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp) { - char_u *tmpname; - char_u *errmsg = NULL; + char_u *tmpname; + char_u *errmsg = NULL; tmpname = vim_tempname(); - if (tmpname == NULL) + if (tmpname == NULL) { errmsg = (char_u *)_("Can't find temp file for conversion"); - else { - close(*fdp); /* close the input file, ignore errors */ + } else { + close(*fdp); // close the input file, ignore errors *fdp = -1; if (eval_charconvert((char *)fenc, "utf-8", (char *)fname, (char *)tmpname) == FAIL) { @@ -2081,7 +2140,7 @@ readfile_charconvert ( } } - /* If the input file is closed, open it (caller should check for error). */ + // If the input file is closed, open it (caller should check for error). if (*fdp < 0) { *fdp = os_open((char *)fname, O_RDONLY, 0); } @@ -2111,45 +2170,35 @@ char *new_file_message(void) return shortmess(SHM_NEW) ? _("[New]") : _("[New File]"); } -/* - * buf_write() - write to file "fname" lines "start" through "end" - * - * We do our own buffering here because fwrite() is so slow. - * - * If "forceit" is true, we don't care for errors when attempting backups. - * In case of an error everything possible is done to restore the original - * file. But when "forceit" is TRUE, we risk losing it. - * - * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and - * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed. - * - * This function must NOT use NameBuff (because it's called by autowrite()). - * - * return FAIL for failure, OK otherwise - */ -int -buf_write( - buf_T *buf, - char_u *fname, - char_u *sfname, - linenr_T start, - linenr_T end, - exarg_T *eap, /* for forced 'ff' and 'fenc', can be - NULL! */ - int append, /* append to the file */ - int forceit, - int reset_changed, - int filtering -) +/// buf_write() - write to file "fname" lines "start" through "end" +/// +/// We do our own buffering here because fwrite() is so slow. +/// +/// If "forceit" is true, we don't care for errors when attempting backups. +/// In case of an error everything possible is done to restore the original +/// file. But when "forceit" is TRUE, we risk losing it. +/// +/// When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and +/// "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed. +/// +/// This function must NOT use NameBuff (because it's called by autowrite()). +/// +/// +/// @param eap for forced 'ff' and 'fenc', can be NULL! +/// @param append append to the file +/// +/// @return FAIL for failure, OK otherwise +int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_T end, exarg_T *eap, + int append, int forceit, int reset_changed, int filtering) { int fd; - char_u *backup = NULL; - int backup_copy = FALSE; /* copy the original file? */ + char_u *backup = NULL; + int backup_copy = FALSE; // copy the original file? int dobackup; - char_u *ffname; - char_u *wfname = NULL; /* name of file to write to */ - char_u *s; - char_u *ptr; + char_u *ffname; + char_u *wfname = NULL; // name of file to write to + char_u *s; + char_u *ptr; char_u c; int len; linenr_T lnum; @@ -2164,9 +2213,9 @@ buf_write( char *errmsg = NULL; int errmsgarg = 0; bool errmsg_allocated = false; - char_u *buffer; + char_u *buffer; char_u smallbuf[SMBUFSIZE]; - char_u *backup_ext; + char_u *backup_ext; int bufsize; long perm; // file permissions int retval = OK; @@ -2178,21 +2227,21 @@ buf_write( int prev_got_int = got_int; int checking_conversion; bool file_readonly = false; // overwritten file is read-only - static char *err_readonly = + static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')"; #if defined(UNIX) - int made_writable = FALSE; /* 'w' bit has been set */ + int made_writable = FALSE; // 'w' bit has been set #endif - /* writing everything */ + // writing everything int whole = (start == 1 && end == buf->b_ml.ml_line_count); linenr_T old_line_count = buf->b_ml.ml_line_count; int fileformat; int write_bin; - struct bw_info write_info; /* info for buf_write_bytes() */ + struct bw_info write_info; // info for buf_write_bytes() int converted = FALSE; int notconverted = FALSE; - char_u *fenc; /* effective 'fileencoding' */ - char_u *fenc_tofree = NULL; /* allocated "fenc" */ + char_u *fenc; // effective 'fileencoding' + char_u *fenc_tofree = NULL; // allocated "fenc" #ifdef HAS_BW_FLAGS int wb_flags = 0; #endif @@ -2204,8 +2253,9 @@ buf_write( context_sha256_T sha_ctx; unsigned int bkc = get_bkc_value(buf); - if (fname == NULL || *fname == NUL) /* safety check */ + if (fname == NULL || *fname == NUL) { // safety check return FAIL; + } if (buf->b_ml.ml_mfp == NULL) { /* This can happen during startup when there is a stray "w" in the * vimrc file. */ @@ -2217,16 +2267,17 @@ buf_write( * Disallow writing from .exrc and .vimrc in current directory for * security reasons. */ - if (check_secure()) + if (check_secure()) { return FAIL; + } - /* Avoid a crash for a long name. */ + // Avoid a crash for a long name. if (STRLEN(fname) >= MAXPATHL) { EMSG(_(e_longname)); return FAIL; } - /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */ + // must init bw_conv_buf and bw_iconv_fd before jumping to "fail" write_info.bw_conv_buf = NULL; write_info.bw_conv_error = FALSE; write_info.bw_conv_error_lnum = 0; @@ -2254,13 +2305,15 @@ buf_write( && !filtering && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL) && vim_strchr(p_cpo, CPO_FNAMEW) != NULL) { - if (set_rw_fname(fname, sfname) == FAIL) + if (set_rw_fname(fname, sfname) == FAIL) { return FAIL; - buf = curbuf; /* just in case autocmds made "buf" invalid */ + } + buf = curbuf; // just in case autocmds made "buf" invalid } - if (sfname == NULL) + if (sfname == NULL) { sfname = fname; + } // For Unix: Use the short file name whenever possible. // Avoids problems with networks and when directory names are changed. @@ -2271,12 +2324,13 @@ buf_write( fname = sfname; #endif - if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0) + if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0) { overwriting = TRUE; - else + } else { overwriting = FALSE; + } - ++no_wait_return; /* don't wait for return yet */ + ++no_wait_return; // don't wait for return yet /* * Set '[ and '] marks to the lines to be written. @@ -2302,14 +2356,18 @@ buf_write( * Set curbuf to the buffer to be written. * Careful: The autocommands may call buf_write() recursively! */ - if (ffname == buf->b_ffname) + if (ffname == buf->b_ffname) { buf_ffname = TRUE; - if (sfname == buf->b_sfname) + } + if (sfname == buf->b_sfname) { buf_sfname = TRUE; - if (fname == buf->b_ffname) + } + if (fname == buf->b_ffname) { buf_fname_f = TRUE; - if (fname == buf->b_sfname) + } + if (fname == buf->b_sfname) { buf_fname_s = TRUE; + } // Set curwin/curbuf to buf and save a few things. aucmd_prepbuf(&aco, buf); @@ -2317,21 +2375,22 @@ buf_write( if (append) { if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD, - sfname, sfname, FALSE, curbuf, eap))) { - if (overwriting && bt_nofile(curbuf)) + sfname, sfname, FALSE, curbuf, eap))) { + if (overwriting && bt_nofile(curbuf)) { nofile_err = TRUE; - else + } else { apply_autocmds_exarg(EVENT_FILEAPPENDPRE, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); + } } } else if (filtering) { apply_autocmds_exarg(EVENT_FILTERWRITEPRE, - NULL, sfname, FALSE, curbuf, eap); - } else if (reset_changed && whole) { + NULL, sfname, FALSE, curbuf, eap); + } else if (reset_changed && whole) { int was_changed = curbufIsChanged(); did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); if (did_cmd) { if (was_changed && !curbufIsChanged()) { /* Written everything correctly and BufWriteCmd has reset @@ -2341,24 +2400,26 @@ buf_write( u_update_save_nr(curbuf); } } else { - if (overwriting && bt_nofile(curbuf)) + if (overwriting && bt_nofile(curbuf)) { nofile_err = TRUE; - else + } else { apply_autocmds_exarg(EVENT_BUFWRITEPRE, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); + } } } else { if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD, - sfname, sfname, FALSE, curbuf, eap))) { - if (overwriting && bt_nofile(curbuf)) + sfname, sfname, FALSE, curbuf, eap))) { + if (overwriting && bt_nofile(curbuf)) { nofile_err = TRUE; - else + } else { apply_autocmds_exarg(EVENT_FILEWRITEPRE, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); + } } } - /* restore curwin/curbuf and a few other things */ + // restore curwin/curbuf and a few other things aucmd_restbuf(&aco); // In three situations we return here and don't write the file: @@ -2370,41 +2431,45 @@ buf_write( } if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline) || did_cmd || nofile_err - || aborting() - ) { + || aborting()) { --no_wait_return; msg_scroll = msg_save; - if (nofile_err) + if (nofile_err) { EMSG(_("E676: No matching autocommands for acwrite buffer")); + } if (nofile_err - || aborting() - ) + || aborting()) { /* An aborting error, interrupt or exception in the * autocommands. */ return FAIL; + } if (did_cmd) { - if (buf == NULL) + if (buf == NULL) { /* The buffer was deleted. We assume it was written * (can't retry anyway). */ return OK; + } if (overwriting) { - /* Assume the buffer was written, update the timestamp. */ + // Assume the buffer was written, update the timestamp. ml_timestamp(buf); - if (append) + if (append) { buf->b_flags &= ~BF_NEW; - else + } else { buf->b_flags &= ~BF_WRITE_MASK; + } } if (reset_changed && buf->b_changed && !append - && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) + && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) { /* Buffer still changed, the autocommands didn't work * properly. */ return FAIL; + } return OK; } - if (!aborting()) + if (!aborting()) { EMSG(_("E203: Autocommands deleted or unloaded buffer to be written")); + } return FAIL; } @@ -2415,11 +2480,11 @@ buf_write( * changed the number of lines that are to be written (tricky!). */ if (buf->b_ml.ml_line_count != old_line_count) { - if (whole) /* write all */ + if (whole) { // write all end = buf->b_ml.ml_line_count; - else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */ + } else if (buf->b_ml.ml_line_count > old_line_count) { // more lines end += buf->b_ml.ml_line_count - old_line_count; - else { /* less lines */ + } else { // less lines end -= old_line_count - buf->b_ml.ml_line_count; if (end < start) { --no_wait_return; @@ -2434,30 +2499,36 @@ buf_write( * The autocommands may have changed the name of the buffer, which may * be kept in fname, ffname and sfname. */ - if (buf_ffname) + if (buf_ffname) { ffname = buf->b_ffname; - if (buf_sfname) + } + if (buf_sfname) { sfname = buf->b_sfname; - if (buf_fname_f) + } + if (buf_fname_f) { fname = buf->b_ffname; - if (buf_fname_s) + } + if (buf_fname_s) { fname = buf->b_sfname; + } } - if (shortmess(SHM_OVER) && !exiting) - msg_scroll = FALSE; /* overwrite previous file message */ - else - msg_scroll = TRUE; /* don't overwrite previous file message */ - if (!filtering) + if (shortmess(SHM_OVER) && !exiting) { + msg_scroll = FALSE; // overwrite previous file message + } else { + msg_scroll = TRUE; // don't overwrite previous file message + } + if (!filtering) { filemess(buf, #ifndef UNIX - sfname, + sfname, #else - fname, + fname, #endif - (char_u *)"", 0); /* show that we are busy */ - msg_scroll = FALSE; /* always overwrite the file message now */ + (char_u *)"", 0); // show that we are busy + } + msg_scroll = FALSE; // always overwrite the file message now buffer = verbose_try_malloc(BUFSIZE); // can't allocate big buffer, use small one (to be able to write when out of @@ -2465,8 +2536,9 @@ buf_write( if (buffer == NULL) { buffer = smallbuf; bufsize = SMBUFSIZE; - } else + } else { bufsize = BUFSIZE; + } /* * Get information about original file (if there is one). @@ -2478,7 +2550,7 @@ buf_write( newfile = TRUE; } else { perm = file_info_old.stat.st_mode; - if (!S_ISREG(file_info_old.stat.st_mode)) { /* not a file */ + if (!S_ISREG(file_info_old.stat.st_mode)) { // not a file if (S_ISDIR(file_info_old.stat.st_mode)) { SET_ERRMSG_NUM("E502", _("is a directory")); goto fail; @@ -2540,8 +2612,9 @@ buf_write( */ if (overwriting) { retval = check_mtime(buf, &file_info_old); - if (retval == FAIL) + if (retval == FAIL) { goto fail; + } } } @@ -2549,16 +2622,18 @@ buf_write( /* * For systems that support ACL: get the ACL from the original file. */ - if (!newfile) + if (!newfile) { acl = mch_get_acl(fname); + } #endif /* * If 'backupskip' is not empty, don't make a backup for some files. */ dobackup = (p_wb || p_bk || *p_pm != NUL); - if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) + if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) { dobackup = FALSE; + } /* * Save the value of got_int and reset it. We don't want a previous @@ -2568,7 +2643,7 @@ buf_write( prev_got_int = got_int; got_int = FALSE; - /* Mark the buffer as 'being saved' to prevent changed buffer warnings */ + // Mark the buffer as 'being saved' to prevent changed buffer warnings buf->b_saving = true; /* @@ -2583,9 +2658,9 @@ buf_write( FileInfo file_info; const bool no_prepend_dot = false; - if ((bkc & BKC_YES) || append) { /* "yes" */ + if ((bkc & BKC_YES) || append) { // "yes" backup_copy = TRUE; - } else if ((bkc & BKC_AUTO)) { /* "auto" */ + } else if ((bkc & BKC_AUTO)) { // "auto" int i; /* @@ -2613,10 +2688,10 @@ buf_write( } } fd = os_open((char *)IObuff, - O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); - if (fd < 0) /* can't write in directory */ + O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); + if (fd < 0) { // can't write in directory backup_copy = TRUE; - else { + } else { # ifdef UNIX os_fchown(fd, file_info_old.stat.st_uid, file_info_old.stat.st_gid); if (!os_fileinfo((char *)IObuff, &file_info) @@ -2641,14 +2716,14 @@ buf_write( # ifdef UNIX bool file_info_link_ok = os_fileinfo_link((char *)fname, &file_info); - /* Symlinks. */ + // Symlinks. if ((bkc & BKC_BREAKSYMLINK) && file_info_link_ok && !os_fileinfo_id_equal(&file_info, &file_info_old)) { backup_copy = FALSE; } - /* Hardlinks. */ + // Hardlinks. if ((bkc & BKC_BREAKHARDLINK) && os_fileinfo_hardlinks(&file_info_old) > 1 && (!file_info_link_ok @@ -2658,18 +2733,19 @@ buf_write( # endif } - /* make sure we have a valid backup extension to use */ - if (*p_bex == NUL) + // make sure we have a valid backup extension to use + if (*p_bex == NUL) { backup_ext = (char_u *)".bak"; - else + } else { backup_ext = p_bex; + } if (backup_copy) { char_u *wp; int some_error = false; - char_u *dirp; - char_u *rootname; - char_u *p; + char_u *dirp; + char_u *rootname; + char_u *p; /* * Try to make the backup in each directory in the 'bdir' option. @@ -2715,7 +2791,7 @@ buf_write( rootname = get_file_in_dir(fname, IObuff); if (rootname == NULL) { - some_error = TRUE; /* out of memory */ + some_error = TRUE; // out of memory goto nobackup; } @@ -2731,7 +2807,7 @@ buf_write( if (backup == NULL) { xfree(rootname); - some_error = TRUE; /* out of memory */ + some_error = TRUE; // out of memory goto nobackup; } @@ -2774,7 +2850,7 @@ buf_write( * Try to create the backup file */ if (backup != NULL) { - /* remove old backup, if present */ + // remove old backup, if present os_remove((char *)backup); // set file protection same as original file, but @@ -2815,8 +2891,7 @@ buf_write( nobackup: if (backup == NULL && errmsg == NULL) { - SET_ERRMSG(_( - "E509: Cannot create backup file (add ! to override)")); + SET_ERRMSG(_("E509: Cannot create backup file (add ! to override)")); } // Ignore errors when forceit is TRUE. if ((some_error || errmsg != NULL) && !forceit) { @@ -2825,9 +2900,9 @@ nobackup: } SET_ERRMSG(NULL); } else { - char_u *dirp; - char_u *p; - char_u *rootname; + char_u *dirp; + char_u *p; + char_u *rootname; /* * Make a backup by renaming the original file. @@ -2897,8 +2972,9 @@ nobackup: */ if (!p_bk && os_path_exists(backup)) { p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext); - if (p < backup) /* empty file name ??? */ + if (p < backup) { // empty file name ??? p = backup; + } *p = 'z'; while (*p > 'a' && os_path_exists(backup)) { (*p)--; @@ -2951,10 +3027,12 @@ nobackup: status_redraw_all(); // redraw status lines later } - if (end > buf->b_ml.ml_line_count) + if (end > buf->b_ml.ml_line_count) { end = buf->b_ml.ml_line_count; - if (buf->b_ml.ml_flags & ML_EMPTY) + } + if (buf->b_ml.ml_flags & ML_EMPTY) { start = end + 1; + } // If the original file is being overwritten, there is a small chance that // we crash in the middle of writing. Therefore the file is preserved now. @@ -3014,7 +3092,7 @@ nobackup: // internally. write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc, (char_u *)"utf-8"); if (write_info.bw_iconv_fd != (iconv_t)-1) { - /* We're going to use iconv(), allocate a buffer to convert in. */ + // We're going to use iconv(), allocate a buffer to convert in. write_info.bw_conv_buflen = bufsize * ICONV_MULT; write_info.bw_conv_buf = verbose_try_malloc(write_info.bw_conv_buflen); if (!write_info.bw_conv_buf) { @@ -3041,11 +3119,9 @@ nobackup: # ifdef HAVE_ICONV && write_info.bw_iconv_fd == (iconv_t)-1 # endif - && wfname == fname - ) { + && wfname == fname) { if (!forceit) { - SET_ERRMSG(_( - "E213: Cannot convert (add ! to write without conversion)")); + SET_ERRMSG(_("E213: Cannot convert (add ! to write without conversion)")); goto restore_backup; } notconverted = TRUE; @@ -3080,7 +3156,7 @@ nobackup: O_WRONLY | (append ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND) - : (O_CREAT | O_TRUNC)) + : (O_CREAT | O_TRUNC)) , perm < 0 ? 0666 : (perm & 0777))) < 0) { // A forced write will try to create a new file if the old one // is still readonly. This may also happen when the directory @@ -3096,28 +3172,28 @@ nobackup: SET_ERRMSG(_("E166: Can't open linked file for writing")); } else { #endif - SET_ERRMSG_ARG(_("E212: Can't open file for writing: %s"), fd); - if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL - && perm >= 0) { + SET_ERRMSG_ARG(_("E212: Can't open file for writing: %s"), fd); + if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL + && perm >= 0) { #ifdef UNIX - // we write to the file, thus it should be marked - // writable after all - if (!(perm & 0200)) { - made_writable = true; - } - perm |= 0200; - if (file_info_old.stat.st_uid != getuid() - || file_info_old.stat.st_gid != getgid()) { - perm &= 0777; - } -#endif - if (!append) { // don't remove when appending - os_remove((char *)wfname); - } - continue; + // we write to the file, thus it should be marked + // writable after all + if (!(perm & 0200)) { + made_writable = true; } -#ifdef UNIX + perm |= 0200; + if (file_info_old.stat.st_uid != getuid() + || file_info_old.stat.st_gid != getgid()) { + perm &= 0777; + } +#endif + if (!append) { // don't remove when appending + os_remove((char *)wfname); + } + continue; } +#ifdef UNIX + } #endif } @@ -3282,7 +3358,7 @@ restore_backup: // Stop when writing done or an error was encountered. if (!checking_conversion || end == 0) { - break; + break; } // If no error happened until now, writing should be ok, so loop to @@ -3371,17 +3447,15 @@ restore_backup: if (errmsg == NULL) { if (write_info.bw_conv_error) { if (write_info.bw_conv_error_lnum == 0) { - SET_ERRMSG(_( - "E513: write error, conversion failed " - "(make 'fenc' empty to override)")); + SET_ERRMSG(_("E513: write error, conversion failed " + "(make 'fenc' empty to override)")); } else { errmsg_allocated = true; SET_ERRMSG(xmalloc(300)); - vim_snprintf( - errmsg, 300, - _("E513: write error, conversion failed in line %" PRIdLINENR - " (make 'fenc' empty to override)"), - write_info.bw_conv_error_lnum); + vim_snprintf(errmsg, 300, + _("E513: write error, conversion failed in line %" PRIdLINENR + " (make 'fenc' empty to override)"), + write_info.bw_conv_error_lnum); } } else if (got_int) { SET_ERRMSG(_(e_interr)); @@ -3420,11 +3494,11 @@ restore_backup: goto fail; } - lnum -= start; /* compute number of written lines */ - --no_wait_return; /* may wait for return now */ + lnum -= start; // compute number of written lines + --no_wait_return; // may wait for return now #if !defined(UNIX) - fname = sfname; /* use shortname now, for the messages */ + fname = sfname; // use shortname now, for the messages #endif if (!filtering) { add_quoted_fname((char *)IObuff, IOSIZE, buf, (const char *)fname); @@ -3432,9 +3506,10 @@ restore_backup: if (write_info.bw_conv_error) { STRCAT(IObuff, _(" CONVERSION ERROR")); c = TRUE; - if (write_info.bw_conv_error_lnum != 0) + if (write_info.bw_conv_error_lnum != 0) { vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %" PRId64 ";"), - (int64_t)write_info.bw_conv_error_lnum); + (int64_t)write_info.bw_conv_error_lnum); + } } else if (notconverted) { STRCAT(IObuff, _("[NOT converted]")); c = TRUE; @@ -3453,15 +3528,17 @@ restore_backup: msg_add_eol(); c = TRUE; } - /* may add [unix/dos/mac] */ - if (msg_add_fileformat(fileformat)) + // may add [unix/dos/mac] + if (msg_add_fileformat(fileformat)) { c = TRUE; - msg_add_lines(c, (long)lnum, nchars); /* add line/char count */ + } + msg_add_lines(c, (long)lnum, nchars); // add line/char count if (!shortmess(SHM_WRITE)) { - if (append) + if (append) { STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended")); - else + } else { STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written")); + } } set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0); @@ -3489,10 +3566,11 @@ restore_backup: */ if (overwriting) { ml_timestamp(buf); - if (append) + if (append) { buf->b_flags &= ~BF_NEW; - else + } else { buf->b_flags &= ~BF_WRITE_MASK; + } } /* @@ -3528,11 +3606,12 @@ restore_backup: if (org == NULL || (empty_fd = os_open(org, - O_CREAT | O_EXCL | O_NOFOLLOW, - perm < 0 ? 0666 : (perm & 0777))) < 0) + O_CREAT | O_EXCL | O_NOFOLLOW, + perm < 0 ? 0666 : (perm & 0777))) < 0) { EMSG(_("E206: patchmode: can't touch empty original file")); - else + } else { close(empty_fd); + } } if (org != NULL) { os_setperm(org, os_getperm((const char *)fname) & 0777); @@ -3555,15 +3634,16 @@ restore_backup: * Finish up. We get here either after failure or success. */ fail: - --no_wait_return; /* may wait for return now */ + --no_wait_return; // may wait for return now nofail: - /* Done saving, we accept changed buffer warnings again */ + // Done saving, we accept changed buffer warnings again buf->b_saving = false; xfree(backup); - if (buffer != smallbuf) + if (buffer != smallbuf) { xfree(buffer); + } xfree(fenc_tofree); xfree(write_info.bw_conv_buf); # ifdef HAVE_ICONV @@ -3603,9 +3683,8 @@ nofail: const int attr = HL_ATTR(HLF_E); // Set highlight for error messages. MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"), attr | MSG_HIST); - MSG_PUTS_ATTR(_( - "don't quit the editor until the file is successfully written!"), - attr | MSG_HIST); + MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"), + attr | MSG_HIST); /* Update the timestamp to avoid an "overwrite changed file" * prompt when writing again. */ @@ -3631,7 +3710,7 @@ nofail: if (!should_abort(retval)) { aco_save_T aco; - curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */ + curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read /* * Apply POST autocommands. @@ -3639,24 +3718,26 @@ nofail: */ aucmd_prepbuf(&aco, buf); - if (append) + if (append) { apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname, - FALSE, curbuf, eap); - else if (filtering) + FALSE, curbuf, eap); + } else if (filtering) { apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname, - FALSE, curbuf, eap); - else if (reset_changed && whole) + FALSE, curbuf, eap); + } else if (reset_changed && whole) { apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname, - FALSE, curbuf, eap); - else + FALSE, curbuf, eap); + } else { apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname, - FALSE, curbuf, eap); + FALSE, curbuf, eap); + } - /* restore curwin/curbuf and a few other things */ + // restore curwin/curbuf and a few other things aucmd_restbuf(&aco); - if (aborting()) /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing retval = FALSE; + } } got_int |= prev_got_int; @@ -3673,16 +3754,18 @@ nofail: */ static int set_rw_fname(char_u *fname, char_u *sfname) { - buf_T *buf = curbuf; + buf_T *buf = curbuf; - /* It's like the unnamed buffer is deleted.... */ - if (curbuf->b_p_bl) + // It's like the unnamed buffer is deleted.... + if (curbuf->b_p_bl) { apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); + } apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf); - if (aborting()) /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing return FAIL; + } if (curbuf != buf) { - /* We are in another buffer now, don't do the renaming. */ + // We are in another buffer now, don't do the renaming. EMSG(_(e_auchangedbuf)); return FAIL; } @@ -3691,14 +3774,16 @@ static int set_rw_fname(char_u *fname, char_u *sfname) curbuf->b_flags |= BF_NOTEDITED; } - /* ....and a new named one is created */ + // ....and a new named one is created apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf); - if (curbuf->b_p_bl) + if (curbuf->b_p_bl) { apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf); - if (aborting()) /* autocmds may abort script processing */ + } + if (aborting()) { // autocmds may abort script processing return FAIL; + } - /* Do filetype detection now if 'filetype' is empty. */ + // Do filetype detection now if 'filetype' is empty. if (*curbuf->b_p_ft == NUL) { if (au_has_group((char_u *)"filetypedetect")) { (void)do_doautocmd((char_u *)"filetypedetect BufRead", false, NULL); @@ -3717,8 +3802,8 @@ static int set_rw_fname(char_u *fname, char_u *sfname) /// @param[in] buf_len ret_buf length. /// @param[in] buf buf_T file name is coming from. /// @param[in] fname File name to write. -static void add_quoted_fname(char *const ret_buf, const size_t buf_len, - const buf_T *const buf, const char *fname) +static void add_quoted_fname(char *const ret_buf, const size_t buf_len, const buf_T *const buf, + const char *fname) FUNC_ATTR_NONNULL_ARG(1) { if (fname == NULL) { @@ -3761,25 +3846,26 @@ static bool msg_add_fileformat(int eol_type) */ void msg_add_lines(int insert_space, long lnum, off_T nchars) { - char_u *p; + char_u *p; p = IObuff + STRLEN(IObuff); - if (insert_space) + if (insert_space) { *p++ = ' '; - if (shortmess(SHM_LINES)) { - sprintf((char *)p, "%" PRId64 "L, %" PRId64 "C", - (int64_t)lnum, (int64_t)nchars); } - else { - if (lnum == 1) + if (shortmess(SHM_LINES)) { + sprintf((char *)p, "%" PRId64 "L, %" PRId64 "C", + (int64_t)lnum, (int64_t)nchars); + } else { + if (lnum == 1) { STRCPY(p, _("1 line, ")); - else + } else { sprintf((char *)p, _("%" PRId64 " lines, "), (int64_t)lnum); + } p += STRLEN(p); - if (nchars == 1) + if (nchars == 1) { STRCPY(p, _("1 character")); - else { + } else { sprintf((char *)p, _("%" PRId64 " characters"), (int64_t)nchars); } } @@ -3791,7 +3877,7 @@ void msg_add_lines(int insert_space, long lnum, off_T nchars) static void msg_add_eol(void) { STRCAT(IObuff, - shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]")); + shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]")); } /* @@ -3842,17 +3928,17 @@ static bool time_differs(long t1, long t2) FUNC_ATTR_CONST static int buf_write_bytes(struct bw_info *ip) { int wlen; - char_u *buf = ip->bw_buf; /* data to write */ - int len = ip->bw_len; /* length of data */ + char_u *buf = ip->bw_buf; // data to write + int len = ip->bw_len; // length of data #ifdef HAS_BW_FLAGS - int flags = ip->bw_flags; /* extra flags */ + int flags = ip->bw_flags; // extra flags #endif /* * Skip conversion when writing the BOM. */ if (!(flags & FIO_NOCONVERT)) { - char_u *p; + char_u *p; unsigned c; int n; @@ -3860,9 +3946,10 @@ static int buf_write_bytes(struct bw_info *ip) /* * Convert latin1 in the buffer to UTF-8 in the file. */ - p = ip->bw_conv_buf; /* translate to buffer */ - for (wlen = 0; wlen < len; ++wlen) + p = ip->bw_conv_buf; // translate to buffer + for (wlen = 0; wlen < len; ++wlen) { p += utf_char2bytes(buf[wlen], p); + } buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) { @@ -3870,10 +3957,11 @@ static int buf_write_bytes(struct bw_info *ip) * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or * Latin1 chars in the file. */ - if (flags & FIO_LATIN1) - p = buf; /* translate in-place (can only get shorter) */ - else - p = ip->bw_conv_buf; /* translate to buffer */ + if (flags & FIO_LATIN1) { + p = buf; // translate in-place (can only get shorter) + } else { + p = ip->bw_conv_buf; // translate to buffer + } for (wlen = 0; wlen < len; wlen += n) { if (wlen == 0 && ip->bw_restlen != 0) { int l; @@ -3882,30 +3970,33 @@ static int buf_write_bytes(struct bw_info *ip) * buf[] to get a full sequence. Might still be too * short! */ l = CONV_RESTLEN - ip->bw_restlen; - if (l > len) + if (l > len) { l = len; + } memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l); n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l); if (n > ip->bw_restlen + len) { /* We have an incomplete byte sequence at the end to * be written. We can't convert it without the * remaining bytes. Keep them for the next call. */ - if (ip->bw_restlen + len > CONV_RESTLEN) + if (ip->bw_restlen + len > CONV_RESTLEN) { return FAIL; + } ip->bw_restlen += len; break; } - if (n > 1) + if (n > 1) { c = utf_ptr2char(ip->bw_rest); - else + } else { c = ip->bw_rest[0]; + } if (n >= ip->bw_restlen) { n -= ip->bw_restlen; ip->bw_restlen = 0; } else { ip->bw_restlen -= n; memmove(ip->bw_rest, ip->bw_rest + n, - (size_t)ip->bw_restlen); + (size_t)ip->bw_restlen); n = 0; } } else { @@ -3914,29 +4005,32 @@ static int buf_write_bytes(struct bw_info *ip) /* We have an incomplete byte sequence at the end to * be written. We can't convert it without the * remaining bytes. Keep them for the next call. */ - if (len - wlen > CONV_RESTLEN) + if (len - wlen > CONV_RESTLEN) { return FAIL; + } ip->bw_restlen = len - wlen; memmove(ip->bw_rest, buf + wlen, - (size_t)ip->bw_restlen); + (size_t)ip->bw_restlen); break; } - if (n > 1) + if (n > 1) { c = utf_ptr2char(buf + wlen); - else + } else { c = buf[wlen]; + } } if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error) { ip->bw_conv_error = TRUE; ip->bw_conv_error_lnum = ip->bw_start_lnum; } - if (c == NL) + if (c == NL) { ++ip->bw_start_lnum; + } } - if (flags & FIO_LATIN1) + if (flags & FIO_LATIN1) { len = (int)(p - buf); - else { + } else { buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } @@ -3944,12 +4038,12 @@ static int buf_write_bytes(struct bw_info *ip) # ifdef HAVE_ICONV if (ip->bw_iconv_fd != (iconv_t)-1) { - const char *from; + const char *from; size_t fromlen; - char *to; + char *to; size_t tolen; - /* Convert with iconv(). */ + // Convert with iconv(). if (ip->bw_restlen > 0) { char *fp; @@ -3972,7 +4066,7 @@ static int buf_write_bytes(struct bw_info *ip) if (ip->bw_first) { size_t save_len = tolen; - /* output the initial shift state sequence */ + // output the initial shift state sequence (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen); /* There is a bug in iconv() on Linux (which appears to be @@ -3995,9 +4089,10 @@ static int buf_write_bytes(struct bw_info *ip) return FAIL; } - /* copy remainder to ip->bw_rest[] to be used for the next call. */ - if (fromlen > 0) + // copy remainder to ip->bw_rest[] to be used for the next call. + if (fromlen > 0) { memmove(ip->bw_rest, (void *)from, fromlen); + } ip->bw_restlen = (int)fromlen; buf = ip->bw_conv_buf; @@ -4023,7 +4118,7 @@ static int buf_write_bytes(struct bw_info *ip) /// @return true for an error, false when it's OK. static bool ucs2bytes(unsigned c, char_u **pp, int flags) FUNC_ATTR_NONNULL_ALL { - char_u *p = *pp; + char_u *p = *pp; bool error = false; int cc; @@ -4069,12 +4164,13 @@ static bool ucs2bytes(unsigned c, char_u **pp, int flags) FUNC_ATTR_NONNULL_ALL *p++ = (c >> 8); *p++ = c; } - } else { /* Latin1 */ + } else { // Latin1 if (c >= 0x100) { error = true; *p++ = 0xBF; - } else + } else { *p++ = c; + } } *pp = p; @@ -4129,25 +4225,29 @@ static int get_fio_flags(const char_u *name) prop = enc_canon_props(name); if (prop & ENC_UNICODE) { if (prop & ENC_2BYTE) { - if (prop & ENC_ENDIAN_L) + if (prop & ENC_ENDIAN_L) { return FIO_UCS2 | FIO_ENDIAN_L; + } return FIO_UCS2; } if (prop & ENC_4BYTE) { - if (prop & ENC_ENDIAN_L) + if (prop & ENC_ENDIAN_L) { return FIO_UCS4 | FIO_ENDIAN_L; + } return FIO_UCS4; } if (prop & ENC_2WORD) { - if (prop & ENC_ENDIAN_L) + if (prop & ENC_ENDIAN_L) { return FIO_UTF16 | FIO_ENDIAN_L; + } return FIO_UTF16; } return FIO_UTF8; } - if (prop & ENC_LATIN1) + if (prop & ENC_LATIN1) { return FIO_LATIN1; - /* must be ENC_DBCS, requires iconv() */ + } + // must be ENC_DBCS, requires iconv() return 0; } @@ -4161,34 +4261,37 @@ static int get_fio_flags(const char_u *name) */ static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags) { - char *name = NULL; + char *name = NULL; int len = 2; if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0)) { - name = "utf-8"; /* EF BB BF */ + name = "utf-8"; // EF BB BF len = 3; } else if (p[0] == 0xff && p[1] == 0xfe) { if (size >= 4 && p[2] == 0 && p[3] == 0 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L))) { - name = "ucs-4le"; /* FF FE 00 00 */ + name = "ucs-4le"; // FF FE 00 00 len = 4; - } else if (flags == (FIO_UCS2 | FIO_ENDIAN_L)) - name = "ucs-2le"; /* FF FE */ - else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L)) - /* utf-16le is preferred, it also works for ucs-2le text */ - name = "utf-16le"; /* FF FE */ + } else if (flags == (FIO_UCS2 | FIO_ENDIAN_L)) { + name = "ucs-2le"; // FF FE + } else if (flags == FIO_ALL || + flags == (FIO_UTF16 | FIO_ENDIAN_L)) { + // utf-16le is preferred, it also works for ucs-2le text + name = "utf-16le"; // FF FE + } } else if (p[0] == 0xfe && p[1] == 0xff && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16)) { - /* Default to utf-16, it works also for ucs-2 text. */ - if (flags == FIO_UCS2) - name = "ucs-2"; /* FE FF */ - else - name = "utf-16"; /* FE FF */ + // Default to utf-16, it works also for ucs-2 text. + if (flags == FIO_UCS2) { + name = "ucs-2"; // FE FF + } else { + name = "utf-16"; // FE FF + } } else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4)) { - name = "ucs-4"; /* 00 00 FE FF */ + name = "ucs-4"; // 00 00 FE FF len = 4; } @@ -4203,15 +4306,16 @@ static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags) static int make_bom(char_u *buf, char_u *name) { int flags; - char_u *p; + char_u *p; flags = get_fio_flags(name); - /* Can't put a BOM in a non-Unicode file. */ - if (flags == FIO_LATIN1 || flags == 0) + // Can't put a BOM in a non-Unicode file. + if (flags == FIO_LATIN1 || flags == 0) { return 0; + } - if (flags == FIO_UTF8) { /* UTF-8 */ + if (flags == FIO_UTF8) { // UTF-8 buf[0] = 0xef; buf[1] = 0xbb; buf[2] = 0xbf; @@ -4231,7 +4335,7 @@ static int make_bom(char_u *buf, char_u *name) /// name. void shorten_buf_fname(buf_T *buf, char_u *dirname, int force) { - char_u *p; + char_u *p; if (buf->b_fname != NULL && !bt_nofile(buf) @@ -4260,7 +4364,7 @@ void shorten_fnames(int force) os_dirname(dirname, MAXPATHL); FOR_ALL_BUFFERS(buf) { - shorten_buf_fname(buf, dirname, force); + shorten_buf_fname(buf, dirname, force); // Always make the swap file name a full path, a "nofile" buffer may // also have a swap file. @@ -4533,11 +4637,11 @@ int vim_rename(const char_u *from, const char_u *to) int fd_in; int fd_out; int n; - char *errmsg = NULL; - char *buffer; + char *errmsg = NULL; + char *buffer; long perm; #ifdef HAVE_ACL - vim_acl_T acl; /* ACL from original file */ + vim_acl_T acl; // ACL from original file #endif bool use_tmp_file = false; @@ -4577,8 +4681,9 @@ int vim_rename(const char_u *from, const char_u *to) * Find a name that doesn't exist and is in the same directory. * Rename "from" to "tempname" and then rename "tempname" to "to". */ - if (STRLEN(from) >= MAXPATHL - 5) + if (STRLEN(from) >= MAXPATHL - 5) { return -1; + } STRCPY(tempname, from); for (n = 123; n < 99999; n++) { char * tail = (char *)path_tail(tempname); @@ -4613,8 +4718,9 @@ int vim_rename(const char_u *from, const char_u *to) /* * First try a normal rename, return if it works. */ - if (os_rename(from, to) == OK) + if (os_rename(from, to) == OK) { return 0; + } /* * Rename() failed, try copying the file. @@ -4632,9 +4738,9 @@ int vim_rename(const char_u *from, const char_u *to) return -1; } - /* Create the new file with same permissions as the original. */ + // Create the new file with same permissions as the original. fd_out = os_open((char *)to, - O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, (int)perm); + O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, (int)perm); if (fd_out < 0) { close(fd_in); #ifdef HAVE_ACL @@ -4655,16 +4761,18 @@ int vim_rename(const char_u *from, const char_u *to) return -1; } - while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0) + while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0) { if (write_eintr(fd_out, buffer, n) != n) { errmsg = _("E208: Error writing to \"%s\""); break; } + } xfree(buffer); close(fd_in); - if (close(fd_out) < 0) + if (close(fd_out) < 0) { errmsg = _("E209: Error closing \"%s\""); + } if (n < 0) { errmsg = _("E210: Error reading \"%s\""); to = from; @@ -4686,23 +4794,23 @@ int vim_rename(const char_u *from, const char_u *to) static int already_warned = FALSE; -// Check if any not hidden buffer has been changed. -// Postpone the check if there are characters in the stuff buffer, a global -// command is being executed, a mapping is being executed or an autocommand is -// busy. -// Returns TRUE if some message was written (screen should be redrawn and -// cursor positioned). -int -check_timestamps( - int focus // called for GUI focus event -) +/// Check if any not hidden buffer has been changed. +/// Postpone the check if there are characters in the stuff buffer, a global +/// command is being executed, a mapping is being executed or an autocommand is +/// busy. +/// +/// @param focus called for GUI focus event +/// +/// @return TRUE if some message was written (screen should be redrawn and cursor positioned). +int check_timestamps(int focus) { int didit = 0; /* Don't check timestamps while system() or another low-level function may * cause us to lose and gain focus. */ - if (no_check_timestamps > 0) + if (no_check_timestamps > 0) { return FALSE; + } /* Avoid doing a check twice. The OK/Reload dialog can cause a focus * event and we would keep on checking if the file is steadily growing. @@ -4713,8 +4821,8 @@ check_timestamps( } if (!stuff_empty() || global_busy || !typebuf_typed() - || autocmd_busy || curbuf->b_ro_locked > 0 || allbuf_lock > 0 - ) { + || autocmd_busy || curbuf->b_ro_locked > 0 || + allbuf_lock > 0) { need_check_timestamps = true; // check later } else { no_wait_return++; @@ -4754,12 +4862,12 @@ check_timestamps( */ static int move_lines(buf_T *frombuf, buf_T *tobuf) { - buf_T *tbuf = curbuf; + buf_T *tbuf = curbuf; int retval = OK; linenr_T lnum; - char_u *p; + char_u *p; - /* Copy the lines in "frombuf" to "tobuf". */ + // Copy the lines in "frombuf" to "tobuf". curbuf = tobuf; for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; lnum++) { p = vim_strsave(ml_get_buf(frombuf, lnum, false)); @@ -4771,7 +4879,7 @@ static int move_lines(buf_T *frombuf, buf_T *tobuf) xfree(p); } - /* Delete all the lines in "frombuf". */ + // Delete all the lines in "frombuf". if (retval != FAIL) { curbuf = frombuf; for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; lnum--) { @@ -4799,17 +4907,17 @@ int buf_check_timestamp(buf_T *buf) FUNC_ATTR_NONNULL_ALL { int retval = 0; - char_u *path; - char *mesg = NULL; - char *mesg2 = ""; + char_u *path; + char *mesg = NULL; + char *mesg2 = ""; bool helpmesg = false; bool reload = false; bool can_reload = false; uint64_t orig_size = buf->b_orig_size; int orig_mode = buf->b_orig_mode; static bool busy = false; - char_u *s; - char *reason; + char_u *s; + char *reason; bufref_T bufref; set_bufref(&bufref, buf); @@ -4822,9 +4930,9 @@ int buf_check_timestamp(buf_T *buf) || buf->b_ml.ml_mfp == NULL || !bt_normal(buf) || buf->b_saving - || busy - ) + || busy) { return 0; + } FileInfo file_info; bool file_info_ok; @@ -4910,24 +5018,22 @@ int buf_check_timestamp(buf_T *buf) // changed. if (reason[2] == 'n') { mesg = _( - "W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well"); + "W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well"); mesg2 = _("See \":help W12\" for more info."); } else if (reason[1] == 'h') { - mesg = _( - "W11: Warning: File \"%s\" has changed since editing started"); + mesg = _("W11: Warning: File \"%s\" has changed since editing started"); mesg2 = _("See \":help W11\" for more info."); } else if (*reason == 'm') { - mesg = _( - "W16: Warning: Mode of file \"%s\" has changed since editing started"); + mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started"); mesg2 = _("See \":help W16\" for more info."); - } else + } else { /* Only timestamp changed, store it to avoid a warning * in check_mtime() later. */ buf->b_mtime_read = buf->b_mtime; + } } } } - } else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W) && os_path_exists(buf->b_ffname)) { retval = 1; @@ -4952,8 +5058,8 @@ int buf_check_timestamp(buf_T *buf) xstrlcat(tbuf, "\n", tbuf_len - 1); xstrlcat(tbuf, mesg2, tbuf_len - 1); } - if (do_dialog(VIM_WARNING, (char_u *) _("Warning"), (char_u *) tbuf, - (char_u *) _("&OK\n&Load File"), 1, NULL, true) == 2) { + if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), (char_u *)tbuf, + (char_u *)_("&OK\n&Load File"), 1, NULL, true) == 2) { reload = true; } } else if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned) { @@ -4989,7 +5095,7 @@ int buf_check_timestamp(buf_T *buf) } if (reload) { - /* Reload the buffer. */ + // Reload the buffer. buf_reload(buf, orig_mode); if (buf->b_p_udf && buf->b_ffname != NULL) { char_u hash[UNDO_HASH_SIZE]; @@ -5020,13 +5126,13 @@ void buf_reload(buf_T *buf, int orig_mode) pos_T old_cursor; linenr_T old_topline; int old_ro = buf->b_p_ro; - buf_T *savebuf; + buf_T *savebuf; bufref_T bufref; int saved = OK; aco_save_T aco; int flags = READ_NEW; - /* set curwin/curbuf for "buf" and save some things */ + // set curwin/curbuf for "buf" and save some things aucmd_prepbuf(&aco, buf); // We only want to read the text from the file, not reset the syntax @@ -5057,7 +5163,7 @@ void buf_reload(buf_T *buf, int orig_mode) savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY); set_bufref(&bufref, savebuf); if (savebuf != NULL && buf == curbuf) { - /* Open the memline. */ + // Open the memline. curbuf = savebuf; curwin->w_buffer = savebuf; saved = ml_open(curbuf); @@ -5067,7 +5173,7 @@ void buf_reload(buf_T *buf, int orig_mode) if (savebuf == NULL || saved == FAIL || buf != curbuf || move_lines(buf, savebuf) == FAIL) { EMSG2(_("E462: Could not prepare for reloading \"%s\""), - buf->b_fname); + buf->b_fname); saved = FAIL; } } @@ -5110,21 +5216,22 @@ void buf_reload(buf_T *buf, int orig_mode) wipe_buffer(savebuf, false); } - /* Invalidate diff info if necessary. */ + // Invalidate diff info if necessary. diff_invalidate(curbuf); /* Restore the topline and cursor position and check it (lines may * have been removed). */ - if (old_topline > curbuf->b_ml.ml_line_count) + if (old_topline > curbuf->b_ml.ml_line_count) { curwin->w_topline = curbuf->b_ml.ml_line_count; - else + } else { curwin->w_topline = old_topline; + } curwin->w_cursor = old_cursor; check_cursor(); update_topline(curwin); keep_filetype = false; - /* Update folds unless they are defined manually. */ + // Update folds unless they are defined manually. FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp->w_buffer == curwin->w_buffer && !foldmethodIsManual(wp)) { @@ -5135,15 +5242,16 @@ void buf_reload(buf_T *buf, int orig_mode) /* If the mode didn't change and 'readonly' was set, keep the old * value; the user probably used the ":view" command. But don't * reset it, might have had a read error. */ - if (orig_mode == curbuf->b_orig_mode) + if (orig_mode == curbuf->b_orig_mode) { curbuf->b_p_ro |= old_ro; + } - /* Modelines must override settings done by autocommands. */ + // Modelines must override settings done by autocommands. do_modelines(0); - /* restore curwin/curbuf and a few other things */ + // restore curwin/curbuf and a few other things aucmd_restbuf(&aco); - /* Careful: autocommands may have made "buf" invalid! */ + // Careful: autocommands may have made "buf" invalid! } void buf_store_file_info(buf_T *buf, FileInfo *file_info) @@ -5160,8 +5268,9 @@ void buf_store_file_info(buf_T *buf, FileInfo *file_info) */ void write_lnum_adjust(linenr_T offset) { - if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */ + if (curbuf->b_no_eol_lnum != 0) { // only if there is a missing eol curbuf->b_no_eol_lnum += offset; + } } #if defined(BACKSLASH_IN_FILENAME) @@ -5169,7 +5278,7 @@ void write_lnum_adjust(linenr_T offset) /// unless when it looks like a URL. void forward_slash(char_u *fname) { - char_u *p; + char_u *p; if (path_with_url((const char *)fname)) { return; @@ -5344,18 +5453,19 @@ char_u *vim_tempname(void) /// @param allow_dirs Allow matching with dir /// /// @return true if there is a match, false otherwise -bool match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, - char_u *sfname, char_u *tail, int allow_dirs) +bool match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, + int allow_dirs) { regmatch_T regmatch; bool result = false; - regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */ + regmatch.rm_ic = p_fic; // ignore case if 'fileignorecase' is set { - if (prog != NULL) + if (prog != NULL) { regmatch.regprog = *prog; - else + } else { regmatch.regprog = vim_regcomp(pattern, RE_MAGIC); + } } /* @@ -5394,11 +5504,11 @@ bool match_file_list(char_u *list, char_u *sfname, char_u *ffname) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1, 3) { char_u buf[100]; - char_u *tail; - char_u *regpat; + char_u *tail; + char_u *regpat; char allow_dirs; bool match; - char_u *p; + char_u *p; tail = path_tail(sfname); @@ -5425,25 +5535,27 @@ bool match_file_list(char_u *list, char_u *sfname, char_u *ffname) /// allow_dirs, otherwise FALSE is put there -- webb. /// Handle backslashes before special characters, like "\*" and "\ ". /// -/// Returns NULL on failure. -char_u * file_pat_to_reg_pat( - const char_u *pat, - const char_u *pat_end, // first char after pattern or NULL - char *allow_dirs, // Result passed back out in here - int no_bslash // Don't use a backward slash as pathsep -) +/// @param pat_end first char after pattern or NULL +/// @param allow_dirs Result passed back out in here +/// @param no_bslash Don't use a backward slash as pathsep +/// +/// @return NULL on failure. +char_u * file_pat_to_reg_pat(const char_u *pat, const char_u *pat_end, char *allow_dirs, + int no_bslash) FUNC_ATTR_NONNULL_ARG(1) { const char_u *endp; - char_u *reg_pat; + char_u *reg_pat; const char_u *p; int nested = 0; int add_dollar = TRUE; - if (allow_dirs != NULL) + if (allow_dirs != NULL) { *allow_dirs = FALSE; - if (pat_end == NULL) + } + if (pat_end == NULL) { pat_end = pat + STRLEN(pat); + } if (pat_end == pat) { return (char_u *)xstrdup("^$"); @@ -5459,12 +5571,12 @@ char_u * file_pat_to_reg_pat( case '{': case '}': case '~': - size += 2; /* extra backslash */ + size += 2; // extra backslash break; #ifdef BACKSLASH_IN_FILENAME case '\\': case '/': - size += 4; /* could become "[\/]" */ + size += 4; // could become "[\/]" break; #endif default: @@ -5476,11 +5588,13 @@ char_u * file_pat_to_reg_pat( size_t i = 0; - if (pat[0] == '*') - while (pat[0] == '*' && pat < pat_end - 1) + if (pat[0] == '*') { + while (pat[0] == '*' && pat < pat_end - 1) { pat++; - else + } + } else { reg_pat[i++] = '^'; + } endp = pat_end - 1; if (endp >= pat && *endp == '*') { while (endp - pat > 0 && *endp == '*') { @@ -5493,8 +5607,9 @@ char_u * file_pat_to_reg_pat( case '*': reg_pat[i++] = '.'; reg_pat[i++] = '*'; - while (p[1] == '*') /* "**" matches like "*" */ + while (p[1] == '*') { // "**" matches like "*" ++p; + } break; case '.': case '~': @@ -5505,8 +5620,9 @@ char_u * file_pat_to_reg_pat( reg_pat[i++] = '.'; break; case '\\': - if (p[1] == NUL) + if (p[1] == NUL) { break; + } #ifdef BACKSLASH_IN_FILENAME if (!no_bslash) { /* translate: @@ -5521,8 +5637,9 @@ char_u * file_pat_to_reg_pat( reg_pat[i++] = '\\'; reg_pat[i++] = '/'; reg_pat[i++] = ']'; - if (allow_dirs != NULL) + if (allow_dirs != NULL) { *allow_dirs = TRUE; + } break; } } @@ -5555,8 +5672,9 @@ char_u * file_pat_to_reg_pat( #ifdef BACKSLASH_IN_FILENAME && (!no_bslash || *p != '\\') #endif - ) + ) { *allow_dirs = TRUE; + } reg_pat[i++] = '\\'; reg_pat[i++] = *p; } @@ -5567,8 +5685,9 @@ char_u * file_pat_to_reg_pat( reg_pat[i++] = '\\'; reg_pat[i++] = '/'; reg_pat[i++] = ']'; - if (allow_dirs != NULL) + if (allow_dirs != NULL) { *allow_dirs = TRUE; + } break; #endif case '{': @@ -5585,8 +5704,9 @@ char_u * file_pat_to_reg_pat( if (nested) { reg_pat[i++] = '\\'; reg_pat[i++] = '|'; - } else + } else { reg_pat[i++] = ','; + } break; default: if (allow_dirs != NULL && vim_ispathsep(*p)) { @@ -5596,8 +5716,9 @@ char_u * file_pat_to_reg_pat( break; } } - if (add_dollar) + if (add_dollar) { reg_pat[i++] = '$'; + } reg_pat[i] = NUL; if (nested != 0) { if (nested < 0) { @@ -5621,8 +5742,9 @@ long read_eintr(int fd, void *buf, size_t bufsize) for (;; ) { ret = read(fd, buf, bufsize); - if (ret >= 0 || errno != EINTR) + if (ret >= 0 || errno != EINTR) { break; + } } return ret; } @@ -5641,10 +5763,12 @@ long write_eintr(int fd, void *buf, size_t bufsize) while (ret < (long)bufsize) { wlen = write(fd, (char *)buf + ret, bufsize - ret); if (wlen < 0) { - if (errno != EINTR) + if (errno != EINTR) { break; - } else + } + } else { ret += wlen; + } } return ret; } diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 51a8a85aa0..567cf9c8c3 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -7,12 +7,11 @@ * fold.c: code for folding */ -#include #include +#include -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/fold.h" +#include "nvim/buffer_updates.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" @@ -20,27 +19,28 @@ #include "nvim/eval.h" #include "nvim/ex_docmd.h" #include "nvim/ex_session.h" -#include "nvim/func_attr.h" -#include "nvim/indent.h" -#include "nvim/buffer_updates.h" #include "nvim/extmark.h" +#include "nvim/fold.h" +#include "nvim/func_attr.h" +#include "nvim/garray.h" +#include "nvim/indent.h" #include "nvim/mark.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/plines.h" -#include "nvim/garray.h" #include "nvim/move.h" +#include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/plines.h" #include "nvim/screen.h" #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/undo.h" -#include "nvim/ops.h" +#include "nvim/vim.h" -/* local declarations. {{{1 */ -/* typedef fold_T {{{2 */ +// local declarations. {{{1 +// typedef fold_T {{{2 /* * The toplevel folds for each window are stored in the w_folds growarray. * Each toplevel fold can contain an array of second level folds in the @@ -58,20 +58,20 @@ typedef struct { // folds too } fold_T; -#define FD_OPEN 0 /* fold is open (nested ones can be closed) */ -#define FD_CLOSED 1 /* fold is closed */ -#define FD_LEVEL 2 /* depends on 'foldlevel' (nested folds too) */ +#define FD_OPEN 0 // fold is open (nested ones can be closed) +#define FD_CLOSED 1 // fold is closed +#define FD_LEVEL 2 // depends on 'foldlevel' (nested folds too) -#define MAX_LEVEL 20 /* maximum fold depth */ +#define MAX_LEVEL 20 // maximum fold depth -/* Define "fline_T", passed to get fold level for a line. {{{2 */ +// Define "fline_T", passed to get fold level for a line. {{{2 typedef struct { - win_T *wp; /* window */ - linenr_T lnum; /* current line number */ - linenr_T off; /* offset between lnum and real line number */ - linenr_T lnum_save; /* line nr used by foldUpdateIEMSRecurse() */ - int lvl; /* current level (-1 for undefined) */ - int lvl_next; /* level used for next line */ + win_T *wp; // window + linenr_T lnum; // current line number + linenr_T off; // offset between lnum and real line number + linenr_T lnum_save; // line nr used by foldUpdateIEMSRecurse() + int lvl; // current level (-1 for undefined) + int lvl_next; // level used for next line int start; /* number of folds that are forced to start at this line. */ int end; /* level of fold that is forced to end below @@ -83,10 +83,10 @@ typedef struct { // Flag is set when redrawing is needed. static bool fold_changed; -/* Function used by foldUpdateIEMSRecurse */ +// Function used by foldUpdateIEMSRecurse typedef void (*LevelGetter)(fline_T *); -/* static functions {{{2 */ +// static functions {{{2 #ifdef INCLUDE_GENERATED_DECLARATIONS # include "fold.c.generated.h" @@ -110,17 +110,17 @@ static linenr_T invalid_bot = (linenr_T)0; static linenr_T prev_lnum = 0; static int prev_lnum_lvl = -1; -/* Flags used for "done" argument of setManualFold. */ +// Flags used for "done" argument of setManualFold. #define DONE_NOTHING 0 -#define DONE_ACTION 1 /* did close or open a fold */ -#define DONE_FOLD 2 /* did find a fold */ +#define DONE_ACTION 1 // did close or open a fold +#define DONE_FOLD 2 // did find a fold static size_t foldstartmarkerlen; static char_u *foldendmarker; static size_t foldendmarkerlen; -/* Exported folding functions. {{{1 */ -/* copyFoldingState() {{{2 */ +// Exported folding functions. {{{1 +// copyFoldingState() {{{2 /* * Copy that folding state from window "wp_from" to window "wp_to". */ @@ -131,18 +131,18 @@ void copyFoldingState(win_T *wp_from, win_T *wp_to) cloneFoldGrowArray(&wp_from->w_folds, &wp_to->w_folds); } -/* hasAnyFolding() {{{2 */ +// hasAnyFolding() {{{2 /* * Return TRUE if there may be folded lines in the current window. */ int hasAnyFolding(win_T *win) { - /* very simple now, but can become more complex later */ + // very simple now, but can become more complex later return !win->w_buffer->terminal && win->w_p_fen && (!foldmethodIsManual(win) || !GA_EMPTY(&win->w_folds)); } -/* hasFolding() {{{2 */ +// hasFolding() {{{2 /* * Return TRUE if line "lnum" in the current window is part of a closed * fold. @@ -163,20 +163,14 @@ bool hasFolding(linenr_T lnum, linenr_T *firstp, linenr_T *lastp) /// @param[out] infop where to store fold info /// /// @return true if range contains folds -bool hasFoldingWin( - win_T *const win, - const linenr_T lnum, - linenr_T *const firstp, - linenr_T *const lastp, - const bool cache, - foldinfo_T *const infop -) +bool hasFoldingWin(win_T *const win, const linenr_T lnum, linenr_T *const firstp, + linenr_T *const lastp, const bool cache, foldinfo_T *const infop) { bool had_folded = false; linenr_T first = 0; linenr_T last = 0; linenr_T lnum_rel = lnum; - fold_T *fp; + fold_T *fp; int level = 0; bool use_level = false; bool maybe_small = false; @@ -186,8 +180,9 @@ bool hasFoldingWin( // Return quickly when there is no folding at all in this window. if (!hasAnyFolding(win)) { - if (infop != NULL) + if (infop != NULL) { infop->fi_level = 0; + } return false; } @@ -210,21 +205,23 @@ bool hasFoldingWin( */ garray_T *gap = &win->w_folds; for (;; ) { - if (!foldFind(gap, lnum_rel, &fp)) + if (!foldFind(gap, lnum_rel, &fp)) { break; + } - /* Remember lowest level of fold that starts in "lnum". */ - if (lnum_rel == fp->fd_top && low_level == 0) + // Remember lowest level of fold that starts in "lnum". + if (lnum_rel == fp->fd_top && low_level == 0) { low_level = level + 1; + } first += fp->fd_top; last += fp->fd_top; - /* is this fold closed? */ + // is this fold closed? had_folded = check_closed(win, fp, &use_level, level, - &maybe_small, lnum - lnum_rel); + &maybe_small, lnum - lnum_rel); if (had_folded) { - /* Fold closed: Set last and quit loop. */ + // Fold closed: Set last and quit loop. last += fp->fd_len - 1; break; } @@ -249,10 +246,12 @@ bool hasFoldingWin( if (last > win->w_buffer->b_ml.ml_line_count) { last = win->w_buffer->b_ml.ml_line_count; } - if (lastp != NULL) + if (lastp != NULL) { *lastp = last; - if (firstp != NULL) + } + if (firstp != NULL) { *firstp = first; + } if (infop != NULL) { infop->fi_level = level + 1; infop->fi_lnum = first; @@ -261,7 +260,7 @@ bool hasFoldingWin( return true; } -/* foldLevel() {{{2 */ +// foldLevel() {{{2 /* * Return fold level at line number "lnum" in the current window. */ @@ -269,16 +268,18 @@ int foldLevel(linenr_T lnum) { /* While updating the folds lines between invalid_top and invalid_bot have * an undefined fold level. Otherwise update the folds first. */ - if (invalid_top == (linenr_T)0) + if (invalid_top == (linenr_T)0) { checkupdate(curwin); - else if (lnum == prev_lnum && prev_lnum_lvl >= 0) + } else if (lnum == prev_lnum && prev_lnum_lvl >= 0) { return prev_lnum_lvl; - else if (lnum >= invalid_top && lnum <= invalid_bot) + } else if (lnum >= invalid_top && lnum <= invalid_bot) { return -1; + } - /* Return quickly when there is no folding at all in this window. */ - if (!hasAnyFolding(curwin)) + // Return quickly when there is no folding at all in this window. + if (!hasAnyFolding(curwin)) { return 0; + } return foldLevelWin(curwin, lnum); } @@ -316,7 +317,7 @@ foldinfo_T fold_info(win_T *win, linenr_T lnum) return info; } -/* foldmethodIsManual() {{{2 */ +// foldmethodIsManual() {{{2 /* * Return TRUE if 'foldmethod' is "manual" */ @@ -325,7 +326,7 @@ int foldmethodIsManual(win_T *wp) return wp->w_p_fdm[3] == 'u'; } -/* foldmethodIsIndent() {{{2 */ +// foldmethodIsIndent() {{{2 /* * Return TRUE if 'foldmethod' is "indent" */ @@ -334,7 +335,7 @@ int foldmethodIsIndent(win_T *wp) return wp->w_p_fdm[0] == 'i'; } -/* foldmethodIsExpr() {{{2 */ +// foldmethodIsExpr() {{{2 /* * Return TRUE if 'foldmethod' is "expr" */ @@ -343,7 +344,7 @@ int foldmethodIsExpr(win_T *wp) return wp->w_p_fdm[1] == 'x'; } -/* foldmethodIsMarker() {{{2 */ +// foldmethodIsMarker() {{{2 /* * Return TRUE if 'foldmethod' is "marker" */ @@ -352,7 +353,7 @@ int foldmethodIsMarker(win_T *wp) return wp->w_p_fdm[2] == 'r'; } -/* foldmethodIsSyntax() {{{2 */ +// foldmethodIsSyntax() {{{2 /* * Return TRUE if 'foldmethod' is "syntax" */ @@ -361,7 +362,7 @@ int foldmethodIsSyntax(win_T *wp) return wp->w_p_fdm[0] == 's'; } -/* foldmethodIsDiff() {{{2 */ +// foldmethodIsDiff() {{{2 /* * Return TRUE if 'foldmethod' is "diff" */ @@ -378,7 +379,7 @@ void closeFold(pos_T pos, long count) setFoldRepeat(pos, count, false); } -/* closeFoldRecurse() {{{2 */ +// closeFoldRecurse() {{{2 /* * Close fold for current window at line "lnum" recursively. */ @@ -387,19 +388,15 @@ void closeFoldRecurse(pos_T pos) (void)setManualFold(pos, false, true, NULL); } -/* opFoldRange() {{{2 */ -/* - * Open or Close folds for current window in lines "first" to "last". - * Used for "zo", "zO", "zc" and "zC" in Visual mode. - */ -void -opFoldRange( - pos_T firstpos, - pos_T lastpos, - int opening, // TRUE to open, FALSE to close - int recurse, // TRUE to do it recursively - int had_visual // TRUE when Visual selection used -) +// opFoldRange() {{{2 +/// +/// Open or Close folds for current window in lines "first" to "last". +/// Used for "zo", "zO", "zc" and "zC" in Visual mode. +/// +/// @param opening TRUE to open, FALSE to close +/// @param recurse TRUE to do it recursively +/// @param had_visual TRUE when Visual selection used +void opFoldRange(pos_T firstpos, pos_T lastpos, int opening, int recurse, int had_visual) { int done = DONE_NOTHING; // avoid error messages linenr_T first = firstpos.lnum; @@ -412,8 +409,9 @@ opFoldRange( lnum_next = lnum; /* Opening one level only: next fold to open is after the one going to * be opened. */ - if (opening && !recurse) + if (opening && !recurse) { (void)hasFolding(lnum, NULL, &lnum_next); + } (void)setManualFold(temp, opening, recurse, &done); // Closing one level only: next line to close a fold is after just // closed fold. @@ -421,14 +419,16 @@ opFoldRange( (void)hasFolding(lnum, NULL, &lnum_next); } } - if (done == DONE_NOTHING) + if (done == DONE_NOTHING) { EMSG(_(e_nofold)); - /* Force a redraw to remove the Visual highlighting. */ - if (had_visual) + } + // Force a redraw to remove the Visual highlighting. + if (had_visual) { redraw_curbuf_later(INVERTED); + } } -/* openFold() {{{2 */ +// openFold() {{{2 /* * Open fold for current window at line "lnum". * Repeat "count" times. @@ -438,7 +438,7 @@ void openFold(pos_T pos, long count) setFoldRepeat(pos, count, true); } -/* openFoldRecurse() {{{2 */ +// openFoldRecurse() {{{2 /* * Open fold for current window at line "lnum" recursively. */ @@ -447,7 +447,7 @@ void openFoldRecurse(pos_T pos) (void)setManualFold(pos, true, true, NULL); } -/* foldOpenCursor() {{{2 */ +// foldOpenCursor() {{{2 /* * Open folds until the cursor line is not in a closed fold. */ @@ -456,7 +456,7 @@ void foldOpenCursor(void) int done; checkupdate(curwin); - if (hasAnyFolding(curwin)) + if (hasAnyFolding(curwin)) { for (;; ) { done = DONE_NOTHING; (void)setManualFold(curwin->w_cursor, true, false, &done); @@ -464,9 +464,10 @@ void foldOpenCursor(void) break; } } + } } -/* newFoldLevel() {{{2 */ +// newFoldLevel() {{{2 /* * Set new foldlevel for current window. */ @@ -489,7 +490,7 @@ void newFoldLevel(void) static void newFoldLevelWin(win_T *wp) { - fold_T *fp; + fold_T *fp; checkupdate(wp); if (wp->w_fold_manual) { @@ -497,62 +498,67 @@ static void newFoldLevelWin(win_T *wp) * manual open/close will then change the flags to FD_OPEN or * FD_CLOSED for those folds that don't use 'foldlevel'. */ fp = (fold_T *)wp->w_folds.ga_data; - for (int i = 0; i < wp->w_folds.ga_len; ++i) + for (int i = 0; i < wp->w_folds.ga_len; ++i) { fp[i].fd_flags = FD_LEVEL; + } wp->w_fold_manual = false; } changed_window_setting_win(wp); } -/* foldCheckClose() {{{2 */ +// foldCheckClose() {{{2 /* * Apply 'foldlevel' to all folds that don't contain the cursor. */ void foldCheckClose(void) { - if (*p_fcl != NUL) { /* can only be "all" right now */ + if (*p_fcl != NUL) { // can only be "all" right now checkupdate(curwin); if (checkCloseRec(&curwin->w_folds, curwin->w_cursor.lnum, - (int)curwin->w_p_fdl)) + (int)curwin->w_p_fdl)) { changed_window_setting(); + } } } -/* checkCloseRec() {{{2 */ +// checkCloseRec() {{{2 static int checkCloseRec(garray_T *gap, linenr_T lnum, int level) { - fold_T *fp; + fold_T *fp; int retval = FALSE; fp = (fold_T *)gap->ga_data; for (int i = 0; i < gap->ga_len; ++i) { - /* Only manually opened folds may need to be closed. */ + // Only manually opened folds may need to be closed. if (fp[i].fd_flags == FD_OPEN) { if (level <= 0 && (lnum < fp[i].fd_top || lnum >= fp[i].fd_top + fp[i].fd_len)) { fp[i].fd_flags = FD_LEVEL; retval = TRUE; - } else + } else { retval |= checkCloseRec(&fp[i].fd_nested, lnum - fp[i].fd_top, - level - 1); + level - 1); + } } } return retval; } -/* foldCreateAllowed() {{{2 */ +// foldCreateAllowed() {{{2 /* * Return TRUE if it's allowed to manually create or delete a fold. * Give an error message and return FALSE if not. */ int foldManualAllowed(int create) { - if (foldmethodIsManual(curwin) || foldmethodIsMarker(curwin)) + if (foldmethodIsManual(curwin) || foldmethodIsMarker(curwin)) { return TRUE; - if (create) + } + if (create) { EMSG(_("E350: Cannot create fold with current 'foldmethod'")); - else + } else { EMSG(_("E351: Cannot delete fold with current 'foldmethod'")); + } return FALSE; } @@ -561,8 +567,8 @@ int foldManualAllowed(int create) /// window. void foldCreate(win_T *wp, pos_T start, pos_T end) { - fold_T *fp; - garray_T *gap; + fold_T *fp; + garray_T *gap; garray_T fold_ga; int i; int cont; @@ -659,13 +665,14 @@ void foldCreate(win_T *wp, pos_T start, pos_T end) ((fold_T *)fold_ga.ga_data)[j].fd_top -= start_rel.lnum; } } - /* Move remaining entries to after the new fold. */ - if (i < gap->ga_len) + // Move remaining entries to after the new fold. + if (i < gap->ga_len) { memmove(fp + 1, (fold_T *)gap->ga_data + i, sizeof(fold_T) * (size_t)(gap->ga_len - i)); + } gap->ga_len = gap->ga_len + 1 - cont; - /* insert new fold */ + // insert new fold fp->fd_nested = fold_ga; fp->fd_top = start_rel.lnum; fp->fd_len = end_rel.lnum - start_rel.lnum + 1; @@ -693,16 +700,11 @@ void foldCreate(win_T *wp, pos_T start, pos_T end) /// @param end delete all folds from start to end when not 0 /// @param recursive delete recursively if true /// @param had_visual true when Visual selection used -void deleteFold( - win_T *const wp, - const linenr_T start, - const linenr_T end, - const int recursive, - const bool had_visual // true when Visual selection used -) +void deleteFold(win_T *const wp, const linenr_T start, const linenr_T end, const int recursive, + const bool had_visual) { - fold_T *fp; - fold_T *found_fp = NULL; + fold_T *fp; + fold_T *found_fp = NULL; linenr_T found_off = 0; bool maybe_small = false; int level = 0; @@ -720,9 +722,10 @@ void deleteFold( linenr_T lnum_off = 0; bool use_level = false; for (;; ) { - if (!foldFind(gap, lnum - lnum_off, &fp)) + if (!foldFind(gap, lnum - lnum_off, &fp)) { break; - /* lnum is inside this fold, remember info */ + } + // lnum is inside this fold, remember info found_ga = gap; found_fp = fp; found_off = lnum_off; @@ -733,7 +736,7 @@ void deleteFold( break; } - /* check nested folds */ + // check nested folds gap = &fp->fd_nested; lnum_off += fp->fd_top; ++level; @@ -791,7 +794,7 @@ void deleteFold( } } -/* clearFolding() {{{2 */ +// clearFolding() {{{2 /* * Remove all folding for window "win". */ @@ -801,7 +804,7 @@ void clearFolding(win_T *win) win->w_foldinvalid = false; } -/* foldUpdate() {{{2 */ +// foldUpdate() {{{2 /* * Update folds for changes in the buffer of a window. * Note that inserted/deleted lines must have already been taken care of by @@ -837,7 +840,7 @@ void foldUpdate(win_T *wp, linenr_T top, linenr_T bot) || foldmethodIsSyntax(wp)) { int save_got_int = got_int; - /* reset got_int here, otherwise it won't work */ + // reset got_int here, otherwise it won't work got_int = FALSE; foldUpdateIEMS(wp, top, bot); got_int |= save_got_int; @@ -857,7 +860,7 @@ void foldUpdateAfterInsert(void) foldOpenCursor(); } -/* foldUpdateAll() {{{2 */ +// foldUpdateAll() {{{2 /* * Update all lines in a window for folding. * Used when a fold setting changes or after reloading the buffer. @@ -871,19 +874,17 @@ void foldUpdateAll(win_T *win) } // foldMoveTo() {{{2 -// -// If "updown" is false: Move to the start or end of the fold. -// If "updown" is true: move to fold at the same level. -// If not moved return FAIL. -int foldMoveTo( - const bool updown, - const int dir, // FORWARD or BACKWARD - const long count -) +/// +/// If "updown" is false: Move to the start or end of the fold. +/// If "updown" is true: move to fold at the same level. +/// @return FAIL if not moved. +/// +/// @param dir FORWARD or BACKWARD +int foldMoveTo(const bool updown, const int dir, const long count) { int retval = FAIL; linenr_T lnum; - fold_T *fp; + fold_T *fp; checkupdate(curwin); @@ -910,12 +911,14 @@ int foldMoveTo( /* When moving up, consider a fold above the cursor; when * moving down consider a fold below the cursor. */ if (dir == FORWARD) { - if (fp - (fold_T *)gap->ga_data >= gap->ga_len) + if (fp - (fold_T *)gap->ga_data >= gap->ga_len) { break; + } --fp; } else { - if (fp == (fold_T *)gap->ga_data) + if (fp == (fold_T *)gap->ga_data) { break; + } } /* don't look for contained folds, they will always move * the cursor too far. */ @@ -923,31 +926,34 @@ int foldMoveTo( } if (!last) { - /* Check if this fold is closed. */ + // Check if this fold is closed. if (check_closed(curwin, fp, &use_level, level, &maybe_small, lnum_off)) { last = true; } - /* "[z" and "]z" stop at closed fold */ - if (last && !updown) + // "[z" and "]z" stop at closed fold + if (last && !updown) { break; + } } if (updown) { if (dir == FORWARD) { - /* to start of next fold if there is one */ + // to start of next fold if there is one if (fp + 1 - (fold_T *)gap->ga_data < gap->ga_len) { lnum = fp[1].fd_top + lnum_off; - if (lnum > curwin->w_cursor.lnum) + if (lnum > curwin->w_cursor.lnum) { lnum_found = lnum; + } } } else { - /* to end of previous fold if there is one */ + // to end of previous fold if there is one if (fp > (fold_T *)gap->ga_data) { lnum = fp[-1].fd_top + lnum_off + fp[-1].fd_len - 1; - if (lnum < curwin->w_cursor.lnum) + if (lnum < curwin->w_cursor.lnum) { lnum_found = lnum; + } } } } else { @@ -955,37 +961,42 @@ int foldMoveTo( * nested folds. */ if (dir == FORWARD) { lnum = fp->fd_top + lnum_off + fp->fd_len - 1; - if (lnum > curwin->w_cursor.lnum) + if (lnum > curwin->w_cursor.lnum) { lnum_found = lnum; + } } else { lnum = fp->fd_top + lnum_off; - if (lnum < curwin->w_cursor.lnum) + if (lnum < curwin->w_cursor.lnum) { lnum_found = lnum; + } } } - if (last) + if (last) { break; + } - /* Check nested folds (if any). */ + // Check nested folds (if any). gap = &fp->fd_nested; lnum_off += fp->fd_top; ++level; } if (lnum_found != curwin->w_cursor.lnum) { - if (retval == FAIL) + if (retval == FAIL) { setpcmark(); + } curwin->w_cursor.lnum = lnum_found; curwin->w_cursor.col = 0; retval = OK; - } else + } else { break; + } } return retval; } -/* foldInitWin() {{{2 */ +// foldInitWin() {{{2 /* * Init the fold info in a new window. */ @@ -994,7 +1005,7 @@ void foldInitWin(win_T *new_win) ga_init(&new_win->w_folds, (int)sizeof(fold_T), 10); } -/* find_wl_entry() {{{2 */ +// find_wl_entry() {{{2 /* * Find an entry in the win->w_lines[] array for buffer line "lnum". * Only valid entries are considered (for entries where wl_valid is FALSE the @@ -1005,27 +1016,31 @@ int find_wl_entry(win_T *win, linenr_T lnum) { int i; - for (i = 0; i < win->w_lines_valid; ++i) + for (i = 0; i < win->w_lines_valid; ++i) { if (win->w_lines[i].wl_valid) { - if (lnum < win->w_lines[i].wl_lnum) + if (lnum < win->w_lines[i].wl_lnum) { return -1; - if (lnum <= win->w_lines[i].wl_lastlnum) + } + if (lnum <= win->w_lines[i].wl_lastlnum) { return i; + } } + } return -1; } -/* foldAdjustVisual() {{{2 */ +// foldAdjustVisual() {{{2 /* * Adjust the Visual area to include any fold at the start or end completely. */ void foldAdjustVisual(void) { - pos_T *start, *end; - char_u *ptr; + pos_T *start, *end; + char_u *ptr; - if (!VIsual_active || !hasAnyFolding(curwin)) + if (!VIsual_active || !hasAnyFolding(curwin)) { return; + } if (ltoreq(VIsual, curwin->w_cursor)) { start = &VIsual; @@ -1034,8 +1049,9 @@ void foldAdjustVisual(void) start = &curwin->w_cursor; end = &VIsual; } - if (hasFolding(start->lnum, &start->lnum, NULL)) + if (hasFolding(start->lnum, &start->lnum, NULL)) { start->col = 0; + } if (hasFolding(end->lnum, NULL, &end->lnum)) { ptr = ml_get(end->lnum); end->col = (colnr_T)STRLEN(ptr); @@ -1047,7 +1063,7 @@ void foldAdjustVisual(void) } } -/* cursor_foldstart() {{{2 */ +// cursor_foldstart() {{{2 /* * Move the cursor to the first line of a closed fold. */ @@ -1056,20 +1072,21 @@ void foldAdjustCursor(void) (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); } -/* Internal functions for "fold_T" {{{1 */ -/* cloneFoldGrowArray() {{{2 */ +// Internal functions for "fold_T" {{{1 +// cloneFoldGrowArray() {{{2 /* * Will "clone" (i.e deep copy) a garray_T of folds. */ void cloneFoldGrowArray(garray_T *from, garray_T *to) { - fold_T *from_p; - fold_T *to_p; + fold_T *from_p; + fold_T *to_p; ga_init(to, from->ga_itemsize, from->ga_growsize); - if (GA_EMPTY(from)) + if (GA_EMPTY(from)) { return; + } ga_grow(to, from->ga_len); @@ -1088,7 +1105,7 @@ void cloneFoldGrowArray(garray_T *from, garray_T *to) } } -/* foldFind() {{{2 */ +// foldFind() {{{2 /* * Search for line "lnum" in folds of growarray "gap". * Set *fpp to the fold struct for the fold that contains "lnum" or @@ -1098,7 +1115,7 @@ void cloneFoldGrowArray(garray_T *from, garray_T *to) static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp) { linenr_T low, high; - fold_T *fp; + fold_T *fp; if (gap->ga_len == 0) { *fpp = NULL; @@ -1115,14 +1132,14 @@ static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp) high = gap->ga_len - 1; while (low <= high) { linenr_T i = (low + high) / 2; - if (fp[i].fd_top > lnum) - /* fold below lnum, adjust high */ + if (fp[i].fd_top > lnum) { + // fold below lnum, adjust high high = i - 1; - else if (fp[i].fd_top + fp[i].fd_len <= lnum) - /* fold above lnum, adjust low */ + } else if (fp[i].fd_top + fp[i].fd_len <= lnum) { + // fold above lnum, adjust low low = i + 1; - else { - /* lnum is inside this fold */ + } else { + // lnum is inside this fold *fpp = fp + i; return TRUE; } @@ -1131,23 +1148,24 @@ static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp) return false; } -/* foldLevelWin() {{{2 */ +// foldLevelWin() {{{2 /* * Return fold level at line number "lnum" in window "wp". */ static int foldLevelWin(win_T *wp, linenr_T lnum) { - fold_T *fp; + fold_T *fp; linenr_T lnum_rel = lnum; int level = 0; - garray_T *gap; + garray_T *gap; - /* Recursively search for a fold that contains "lnum". */ + // Recursively search for a fold that contains "lnum". gap = &wp->w_folds; for (;; ) { - if (!foldFind(gap, lnum_rel, &fp)) + if (!foldFind(gap, lnum_rel, &fp)) { break; - /* Check nested folds. Line number is relative to containing fold. */ + } + // Check nested folds. Line number is relative to containing fold. gap = &fp->fd_nested; lnum_rel -= fp->fd_top; ++level; @@ -1156,19 +1174,19 @@ static int foldLevelWin(win_T *wp, linenr_T lnum) return level; } -/* checkupdate() {{{2 */ +// checkupdate() {{{2 /* * Check if the folds in window "wp" are invalid and update them if needed. */ static void checkupdate(win_T *wp) { if (wp->w_foldinvalid) { - foldUpdate(wp, (linenr_T)1, (linenr_T)MAXLNUM); /* will update all */ + foldUpdate(wp, (linenr_T)1, (linenr_T)MAXLNUM); // will update all wp->w_foldinvalid = false; } } -/* setFoldRepeat() {{{2 */ +// setFoldRepeat() {{{2 /* * Open or close fold for current window at line "lnum". * Repeat "count" times. @@ -1182,26 +1200,23 @@ static void setFoldRepeat(pos_T pos, long count, int do_open) done = DONE_NOTHING; (void)setManualFold(pos, do_open, false, &done); if (!(done & DONE_ACTION)) { - /* Only give an error message when no fold could be opened. */ - if (n == 0 && !(done & DONE_FOLD)) + // Only give an error message when no fold could be opened. + if (n == 0 && !(done & DONE_FOLD)) { EMSG(_(e_nofold)); + } break; } } } -/* setManualFold() {{{2 */ -/* - * Open or close the fold in the current window which contains "lnum". - * Also does this for other windows in diff mode when needed. - */ -static linenr_T -setManualFold( - pos_T pos, - int opening, // TRUE when opening, FALSE when closing - int recurse, // TRUE when closing/opening recursive - int *donep -) +// setManualFold() {{{2 +/// +/// Open or close the fold in the current window which contains "lnum". +/// Also does this for other windows in diff mode when needed. +/// +/// @param opening TRUE when opening, FALSE when closing +/// @param recurse TRUE when closing/opening recursive +static linenr_T setManualFold(pos_T pos, int opening, int recurse, int *donep) { linenr_T lnum = pos.lnum; if (foldmethodIsDiff(curwin) && curwin->w_p_scb) { @@ -1224,33 +1239,28 @@ setManualFold( return setManualFoldWin(curwin, lnum, opening, recurse, donep); } -/* setManualFoldWin() {{{2 */ -/* - * Open or close the fold in window "wp" which contains "lnum". - * "donep", when not NULL, points to flag that is set to DONE_FOLD when some - * fold was found and to DONE_ACTION when some fold was opened or closed. - * When "donep" is NULL give an error message when no fold was found for - * "lnum", but only if "wp" is "curwin". - * Return the line number of the next line that could be closed. - * It's only valid when "opening" is TRUE! - */ -static linenr_T -setManualFoldWin( - win_T *wp, - linenr_T lnum, - int opening, // TRUE when opening, FALSE when closing - int recurse, // TRUE when closing/opening recursive - int *donep -) +// setManualFoldWin() {{{2 +/// Open or close the fold in window "wp" which contains "lnum". +/// "donep", when not NULL, points to flag that is set to DONE_FOLD when some +/// fold was found and to DONE_ACTION when some fold was opened or closed. +/// When "donep" is NULL give an error message when no fold was found for +/// "lnum", but only if "wp" is "curwin". +/// +/// @param opening TRUE when opening, FALSE when closing +/// @param recurse TRUE when closing/opening recursive +/// +/// @return the line number of the next line that could be closed. +/// It's only valid when "opening" is TRUE! +static linenr_T setManualFoldWin(win_T *wp, linenr_T lnum, int opening, int recurse, int *donep) { - fold_T *fp; - fold_T *fp2; - fold_T *found = NULL; + fold_T *fp; + fold_T *fp2; + fold_T *found = NULL; int j; int level = 0; int use_level = FALSE; int found_fold = FALSE; - garray_T *gap; + garray_T *gap; linenr_T next = MAXLNUM; linenr_T off = 0; int done = 0; @@ -1270,43 +1280,47 @@ setManualFoldWin( break; } - /* lnum is inside this fold */ + // lnum is inside this fold found_fold = TRUE; - /* If there is a following fold, continue there next time. */ - if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len) + // If there is a following fold, continue there next time. + if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len) { next = fp[1].fd_top + off; - - /* Change from level-dependent folding to manual. */ - if (use_level || fp->fd_flags == FD_LEVEL) { - use_level = TRUE; - if (level >= wp->w_p_fdl) - fp->fd_flags = FD_CLOSED; - else - fp->fd_flags = FD_OPEN; - fp2 = (fold_T *)fp->fd_nested.ga_data; - for (j = 0; j < fp->fd_nested.ga_len; ++j) - fp2[j].fd_flags = FD_LEVEL; } - /* Simple case: Close recursively means closing the fold. */ + // Change from level-dependent folding to manual. + if (use_level || fp->fd_flags == FD_LEVEL) { + use_level = TRUE; + if (level >= wp->w_p_fdl) { + fp->fd_flags = FD_CLOSED; + } else { + fp->fd_flags = FD_OPEN; + } + fp2 = (fold_T *)fp->fd_nested.ga_data; + for (j = 0; j < fp->fd_nested.ga_len; ++j) { + fp2[j].fd_flags = FD_LEVEL; + } + } + + // Simple case: Close recursively means closing the fold. if (!opening && recurse) { if (fp->fd_flags != FD_CLOSED) { done |= DONE_ACTION; fp->fd_flags = FD_CLOSED; } } else if (fp->fd_flags == FD_CLOSED) { - /* When opening, open topmost closed fold. */ + // When opening, open topmost closed fold. if (opening) { fp->fd_flags = FD_OPEN; done |= DONE_ACTION; - if (recurse) + if (recurse) { foldOpenNested(fp); + } } break; } - /* fold is open, check nested folds */ + // fold is open, check nested folds found = fp; gap = &fp->fd_nested; lnum -= fp->fd_top; @@ -1314,31 +1328,34 @@ setManualFoldWin( ++level; } if (found_fold) { - /* When closing and not recurse, close deepest open fold. */ + // When closing and not recurse, close deepest open fold. if (!opening && found != NULL) { found->fd_flags = FD_CLOSED; done |= DONE_ACTION; } wp->w_fold_manual = true; - if (done & DONE_ACTION) + if (done & DONE_ACTION) { changed_window_setting_win(wp); + } done |= DONE_FOLD; - } else if (donep == NULL && wp == curwin) + } else if (donep == NULL && wp == curwin) { EMSG(_(e_nofold)); + } - if (donep != NULL) + if (donep != NULL) { *donep |= done; + } return next; } -/* foldOpenNested() {{{2 */ +// foldOpenNested() {{{2 /* * Open all nested folds in fold "fpr" recursively. */ static void foldOpenNested(fold_T *fpr) { - fold_T *fp; + fold_T *fp; fp = (fold_T *)fpr->fd_nested.ga_data; for (int i = 0; i < fpr->fd_nested.ga_len; ++i) { @@ -1368,15 +1385,16 @@ static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx, int moved = fp->fd_nested.ga_len; ga_grow(gap, moved - 1); { - /* Get "fp" again, the array may have been reallocated. */ + // Get "fp" again, the array may have been reallocated. fp = (fold_T *)gap->ga_data + idx; // adjust fd_top and fd_flags for the moved folds fold_T *nfp = (fold_T *)fp->fd_nested.ga_data; for (int i = 0; i < moved; i++) { nfp[i].fd_top += fp->fd_top; - if (fp->fd_flags == FD_LEVEL) + if (fp->fd_flags == FD_LEVEL) { nfp[i].fd_flags = FD_LEVEL; + } if (fp->fd_small == kNone) { nfp[i].fd_small = kNone; } @@ -1395,7 +1413,7 @@ static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx, } } -/* deleteFoldRecurse() {{{2 */ +// deleteFoldRecurse() {{{2 /* * Delete nested folds in a fold. */ @@ -1405,7 +1423,7 @@ void deleteFoldRecurse(buf_T *bp, garray_T *gap) GA_DEEP_CLEAR(gap, fold_T, DELETE_FOLD_NESTED); } -/* foldMarkAdjust() {{{2 */ +// foldMarkAdjust() {{{2 /* * Update line numbers of folds for inserted/deleted lines. */ @@ -1413,8 +1431,9 @@ void foldMarkAdjust(win_T *wp, linenr_T line1, linenr_T line2, long amount, long { /* If deleting marks from line1 to line2, but not deleting all those * lines, set line2 so that only deleted lines have their folds removed. */ - if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after) + if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after) { line2 = line1 - amount_after - 1; + } /* If appending a line in Insert mode, it should be included in the fold * just above the line. */ if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM) { @@ -1424,12 +1443,10 @@ void foldMarkAdjust(win_T *wp, linenr_T line1, linenr_T line2, long amount, long } // foldMarkAdjustRecurse() {{{2 -static void foldMarkAdjustRecurse( - win_T *wp, garray_T *gap, - linenr_T line1, linenr_T line2, long amount, long amount_after -) +static void foldMarkAdjustRecurse(win_T *wp, garray_T *gap, linenr_T line1, linenr_T line2, + long amount, long amount_after) { - fold_T *fp; + fold_T *fp; linenr_T last; linenr_T top; @@ -1439,12 +1456,13 @@ static void foldMarkAdjustRecurse( /* In Insert mode an inserted line at the top of a fold is considered part * of the fold, otherwise it isn't. */ - if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM) + if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM) { top = line1 + 1; - else + } else { top = line1; + } - /* Find the fold containing or just below "line1". */ + // Find the fold containing or just below "line1". (void)foldFind(gap, line1, &fp); /* @@ -1453,26 +1471,28 @@ static void foldMarkAdjustRecurse( for (int i = (int)(fp - (fold_T *)gap->ga_data); i < gap->ga_len; ++i, ++fp) { /* * Check for these situations: - * 1 2 3 - * 1 2 3 - * line1 2 3 4 5 - * 2 3 4 5 - * 2 3 4 5 - * line2 2 3 4 5 - * 3 5 6 - * 3 5 6 + * 1 2 3 + * 1 2 3 + * line1 2 3 4 5 + * 2 3 4 5 + * 2 3 4 5 + * line2 2 3 4 5 + * 3 5 6 + * 3 5 6 */ - last = fp->fd_top + fp->fd_len - 1; /* last line of fold */ + last = fp->fd_top + fp->fd_len - 1; // last line of fold - /* 1. fold completely above line1: nothing to do */ - if (last < line1) + // 1. fold completely above line1: nothing to do + if (last < line1) { continue; + } - /* 6. fold below line2: only adjust for amount_after */ + // 6. fold below line2: only adjust for amount_after if (fp->fd_top > line2) { - if (amount_after == 0) + if (amount_after == 0) { break; + } fp->fd_top += amount_after; } else { if (fp->fd_top >= top && last <= line2) { @@ -1491,13 +1511,14 @@ static void foldMarkAdjustRecurse( foldMarkAdjustRecurse(wp, &fp->fd_nested, line1 - fp->fd_top, line2 - fp->fd_top, amount, amount_after); if (last <= line2) { - /* 2. fold contains line1, line2 is below fold */ - if (amount == MAXLNUM) + // 2. fold contains line1, line2 is below fold + if (amount == MAXLNUM) { fp->fd_len = line1 - fp->fd_top; - else + } else { fp->fd_len += amount; + } } else { - /* 3. fold contains line1 and line2 */ + // 3. fold contains line1 and line2 fp->fd_len += amount_after; } } else { @@ -1522,7 +1543,7 @@ static void foldMarkAdjustRecurse( } } -/* getDeepestNesting() {{{2 */ +// getDeepestNesting() {{{2 /* * Get the lowest 'foldlevel' value that makes the deepest nested fold in the * current window open. @@ -1537,13 +1558,14 @@ static int getDeepestNestingRecurse(garray_T *gap) { int level; int maxlevel = 0; - fold_T *fp; + fold_T *fp; fp = (fold_T *)gap->ga_data; for (int i = 0; i < gap->ga_len; ++i) { level = getDeepestNestingRecurse(&fp[i].fd_nested) + 1; - if (level > maxlevel) + if (level > maxlevel) { maxlevel = level; + } } return maxlevel; @@ -1558,14 +1580,8 @@ static int getDeepestNestingRecurse(garray_T *gap) /// @param[out] maybe_smallp true: outer this had fd_small == kNone /// @param lnum_off line number offset for fp->fd_top /// @return true if fold is closed -static bool check_closed( - win_T *const wp, - fold_T *const fp, - bool *const use_levelp, - const int level, - bool *const maybe_smallp, - const linenr_T lnum_off -) +static bool check_closed(win_T *const wp, fold_T *const fp, bool *const use_levelp, const int level, + bool *const maybe_smallp, const linenr_T lnum_off) { bool closed = false; @@ -1598,13 +1614,9 @@ static bool check_closed( // checkSmall() {{{2 /// Update fd_small field of fold "fp". -/// @param lnum_off offset for fp->fd_top -static void -checkSmall( - win_T *const wp, - fold_T *const fp, - const linenr_T lnum_off // offset for fp->fd_top -) +/// +/// @param lnum_off offset for fp->fd_top +static void checkSmall(win_T *const wp, fold_T *const fp, const linenr_T lnum_off) { if (fp->fd_small == kNone) { // Mark any nested folds to maybe-small @@ -1636,7 +1648,7 @@ static void setSmallMaybe(garray_T *gap) } } -/* foldCreateMarkers() {{{2 */ +// foldCreateMarkers() {{{2 /* * Create a fold from line "start" to line "end" (inclusive) in the current * window by adding markers. @@ -1665,17 +1677,16 @@ static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end) buf_updates_send_changes(buf, start.lnum, num_changed, num_changed, true); } -/* foldAddMarker() {{{2 */ +// foldAddMarker() {{{2 /* * Add "marker[markerlen]" in 'commentstring' to line "lnum". */ -static void foldAddMarker( - buf_T *buf, pos_T pos, const char_u *marker, size_t markerlen) +static void foldAddMarker(buf_T *buf, pos_T pos, const char_u *marker, size_t markerlen) { - char_u *cms = buf->b_p_cms; - char_u *line; - char_u *newline; - char_u *p = (char_u *)strstr((char *)buf->b_p_cms, "%s"); + char_u *cms = buf->b_p_cms; + char_u *line; + char_u *newline; + char_u *p = (char_u *)strstr((char *)buf->b_p_cms, "%s"); bool line_is_comment = false; linenr_T lnum = pos.lnum; @@ -1707,17 +1718,11 @@ static void foldAddMarker( } } -/* deleteFoldMarkers() {{{2 */ -/* - * Delete the markers for a fold, causing it to be deleted. - */ -static void -deleteFoldMarkers( - win_T *wp, - fold_T *fp, - int recursive, - linenr_T lnum_off // offset for fp->fd_top -) +// deleteFoldMarkers() {{{2 +/// Delete the markers for a fold, causing it to be deleted. +/// +/// @param lnum_off offset for fp->fd_top +static void deleteFoldMarkers(win_T *wp, fold_T *fp, int recursive, linenr_T lnum_off) { if (recursive) { for (int i = 0; i < fp->fd_nested.ga_len; i++) { @@ -1737,13 +1742,11 @@ deleteFoldMarkers( // Delete 'commentstring' if it matches. // If the marker is not found, there is no error message. Could be a missing // close-marker. -static void foldDelMarker( - buf_T *buf, linenr_T lnum, char_u *marker, size_t markerlen -) +static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t markerlen) { - char_u *newline; - char_u *cms = buf->b_p_cms; - char_u *cms2; + char_u *newline; + char_u *cms = buf->b_p_cms; + char_u *cms2; // end marker may be missing and fold extends below the last line if (lnum > buf->b_ml.ml_line_count) { @@ -1754,12 +1757,13 @@ static void foldDelMarker( if (STRNCMP(p, marker, markerlen) != 0) { continue; } - /* Found the marker, include a digit if it's there. */ + // Found the marker, include a digit if it's there. size_t len = markerlen; - if (ascii_isdigit(p[len])) + if (ascii_isdigit(p[len])) { ++len; + } if (*cms != NUL) { - /* Also delete 'commentstring' if it matches. */ + // Also delete 'commentstring' if it matches. cms2 = (char_u *)strstr((char *)cms, "%s"); if (p - line >= cms2 - cms && STRNCMP(p - (cms2 - cms), cms, cms2 - cms) == 0 @@ -1769,7 +1773,7 @@ static void foldDelMarker( } } if (u_save(lnum - 1, lnum + 1) == OK) { - /* Make new line: text-before-marker + text-after-marker */ + // Make new line: text-before-marker + text-after-marker newline = xmalloc(STRLEN(line) - len + 1); assert(p >= line); memcpy(newline, line, (size_t)(p - line)); @@ -1791,34 +1795,35 @@ static void foldDelMarker( /// @return the text for a closed fold /// /// Otherwise the result is in allocated memory. -char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, - foldinfo_T foldinfo, char_u *buf) +char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldinfo, char_u *buf) FUNC_ATTR_NONNULL_ARG(1) { - char_u *text = NULL; - /* an error occurred when evaluating 'fdt' setting */ + char_u *text = NULL; + // an error occurred when evaluating 'fdt' setting static int got_fdt_error = FALSE; int save_did_emsg = did_emsg; - static win_T *last_wp = NULL; + static win_T *last_wp = NULL; static linenr_T last_lnum = 0; - if (last_wp == NULL || last_wp != wp || last_lnum > lnum || last_lnum == 0) - /* window changed, try evaluating foldtext setting once again */ + if (last_wp == NULL || last_wp != wp || last_lnum > lnum || last_lnum == 0) { + // window changed, try evaluating foldtext setting once again got_fdt_error = FALSE; + } - if (!got_fdt_error) - /* a previous error should not abort evaluating 'foldexpr' */ + if (!got_fdt_error) { + // a previous error should not abort evaluating 'foldexpr' did_emsg = FALSE; + } if (*wp->w_p_fdt != NUL) { char dashes[MAX_LEVEL + 2]; - win_T *save_curwin; + win_T *save_curwin; int level; - char_u *p; + char_u *p; // Set "v:foldstart" and "v:foldend". - set_vim_var_nr(VV_FOLDSTART, (varnumber_T) lnum); - set_vim_var_nr(VV_FOLDEND, (varnumber_T) lnume); + set_vim_var_nr(VV_FOLDSTART, (varnumber_T)lnum); + set_vim_var_nr(VV_FOLDEND, (varnumber_T)lnume); // Set "v:folddashes" to a string of "level" dashes. // Set "v:foldlevel" to "level". @@ -1829,22 +1834,22 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, memset(dashes, '-', (size_t)level); dashes[level] = NUL; set_vim_var_string(VV_FOLDDASHES, dashes, -1); - set_vim_var_nr(VV_FOLDLEVEL, (varnumber_T) level); + set_vim_var_nr(VV_FOLDLEVEL, (varnumber_T)level); - /* skip evaluating foldtext on errors */ + // skip evaluating foldtext on errors if (!got_fdt_error) { save_curwin = curwin; curwin = wp; curbuf = wp->w_buffer; emsg_silent++; // handle exceptions, but don't display errors - text = eval_to_string_safe( - wp->w_p_fdt, NULL, - was_set_insecurely(wp, (char_u *)"foldtext", OPT_LOCAL)); + text = eval_to_string_safe(wp->w_p_fdt, NULL, + was_set_insecurely(wp, (char_u *)"foldtext", OPT_LOCAL)); emsg_silent--; - if (text == NULL || did_emsg) + if (text == NULL || did_emsg) { got_fdt_error = TRUE; + } curwin = save_curwin; curbuf = curwin->w_buffer; @@ -1853,8 +1858,9 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, last_wp = wp; set_vim_var_string(VV_FOLDDASHES, NULL, -1); - if (!did_emsg && save_did_emsg) + if (!did_emsg && save_did_emsg) { did_emsg = save_did_emsg; + } if (text != NULL) { /* Replace unprintable characters, if there are any. But @@ -1867,10 +1873,11 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, break; } p += len - 1; - } else if (*p == TAB) + } else if (*p == TAB) { *p = ' '; - else if (ptr2cells(p) > 1) + } else if (ptr2cells(p) > 1) { break; + } } if (*p != NUL) { p = (char_u *)transstr((const char *)text); @@ -1891,35 +1898,37 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, return text; } -/* foldtext_cleanup() {{{2 */ +// foldtext_cleanup() {{{2 /* * Remove 'foldmarker' and 'commentstring' from "str" (in-place). */ void foldtext_cleanup(char_u *str) { - char_u *s; - char_u *p; + char_u *s; + char_u *p; int did1 = FALSE; int did2 = FALSE; - /* Ignore leading and trailing white space in 'commentstring'. */ + // Ignore leading and trailing white space in 'commentstring'. char_u *cms_start = skipwhite(curbuf->b_p_cms); size_t cms_slen = STRLEN(cms_start); - while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) + while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) { --cms_slen; + } - /* locate "%s" in 'commentstring', use the part before and after it. */ + // locate "%s" in 'commentstring', use the part before and after it. char_u *cms_end = (char_u *)strstr((char *)cms_start, "%s"); size_t cms_elen = 0; if (cms_end != NULL) { cms_elen = cms_slen - (size_t)(cms_end - cms_start); cms_slen = (size_t)(cms_end - cms_start); - /* exclude white space before "%s" */ - while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) + // exclude white space before "%s" + while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) { --cms_slen; + } - /* skip "%s" and white space after it */ + // skip "%s" and white space after it s = skipwhite(cms_end + 2); cms_elen -= (size_t)(s - cms_end); cms_end = s; @@ -1928,18 +1937,21 @@ void foldtext_cleanup(char_u *str) for (s = str; *s != NUL; ) { size_t len = 0; - if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0) + if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0) { len = foldstartmarkerlen; - else if (STRNCMP(s, foldendmarker, foldendmarkerlen) == 0) + } else if (STRNCMP(s, foldendmarker, foldendmarkerlen) == 0) { len = foldendmarkerlen; + } if (len > 0) { - if (ascii_isdigit(s[len])) + if (ascii_isdigit(s[len])) { ++len; + } /* May remove 'commentstring' start. Useful when it's a double * quote and we already removed a double quote. */ - for (p = s; p > str && ascii_iswhite(p[-1]); --p) + for (p = s; p > str && ascii_iswhite(p[-1]); --p) { ; + } if (p >= str + cms_slen && STRNCMP(p - cms_slen, cms_start, cms_slen) == 0) { len += (size_t)(s - p) + cms_slen; @@ -1956,8 +1968,9 @@ void foldtext_cleanup(char_u *str) } } if (len != 0) { - while (ascii_iswhite(s[len])) + while (ascii_iswhite(s[len])) { ++len; + } STRMOVE(s, s + len); } else { MB_PTR_ADV(s); @@ -1965,10 +1978,10 @@ void foldtext_cleanup(char_u *str) } } -/* Folding by indent, expr, marker and syntax. {{{1 */ -/* Function declarations. {{{2 */ +// Folding by indent, expr, marker and syntax. {{{1 +// Function declarations. {{{2 -/* foldUpdateIEMS() {{{2 */ +// foldUpdateIEMS() {{{2 /* * Update the folding for window "wp", at least from lines "top" to "bot". * IEMS = "Indent Expr Marker Syntax" @@ -1977,28 +1990,30 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) { fline_T fline; LevelGetter getlevel = NULL; - fold_T *fp; + fold_T *fp; - /* Avoid problems when being called recursively. */ - if (invalid_top != (linenr_T)0) + // Avoid problems when being called recursively. + if (invalid_top != (linenr_T)0) { return; + } if (wp->w_foldinvalid) { - /* Need to update all folds. */ + // Need to update all folds. top = 1; bot = wp->w_buffer->b_ml.ml_line_count; wp->w_foldinvalid = false; - /* Mark all folds a maybe-small. */ + // Mark all folds a maybe-small. setSmallMaybe(&wp->w_folds); } - /* add the context for "diff" folding */ + // add the context for "diff" folding if (foldmethodIsDiff(wp)) { - if (top > diff_context) + if (top > diff_context) { top -= diff_context; - else + } else { top = 1; + } bot += diff_context; } @@ -2023,7 +2038,7 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) if (foldmethodIsMarker(wp)) { getlevel = foldlevelMarker; - /* Init marker variables to speed up foldlevelMarker(). */ + // Init marker variables to speed up foldlevelMarker(). parseMarker(wp); /* Need to get the level of the line above top, it is used if there is @@ -2032,7 +2047,7 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) // Get the fold level at top - 1. const int level = foldLevelWin(wp, top - 1); - /* The fold may end just above the top, check for that. */ + // The fold may end just above the top, check for that. fline.lnum = top - 1; fline.lvl = level; getlevel(&fline); @@ -2040,10 +2055,11 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) /* If a fold started here, we already had the level, if it stops * here, we need to use lvl_next. Could also start and end a fold * in the same line. */ - if (fline.lvl > level) + if (fline.lvl > level) { fline.lvl = level - (fline.lvl - fline.lvl_next); - else + } else { fline.lvl = fline.lvl_next; + } } fline.lnum = top; getlevel(&fline); @@ -2053,14 +2069,16 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) getlevel = foldlevelExpr; /* start one line back, because a "<1" may indicate the end of a * fold in the topline */ - if (top > 1) + if (top > 1) { --fline.lnum; - } else if (foldmethodIsSyntax(wp)) + } + } else if (foldmethodIsSyntax(wp)) { getlevel = foldlevelSyntax; - else if (foldmethodIsDiff(wp)) + } else if (foldmethodIsDiff(wp)) { getlevel = foldlevelDiff; - else + } else { getlevel = foldlevelIndent; + } /* Backup to a line for which the fold level is defined. Since it's * always defined for line one, we will stop there. */ @@ -2070,8 +2088,9 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) * the next line, but we search backwards here. */ fline.lvl_next = -1; getlevel(&fline); - if (fline.lvl >= 0) + if (fline.lvl >= 0) { break; + } } } @@ -2084,14 +2103,15 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) */ if (foldlevelSyntax == getlevel) { garray_T *gap = &wp->w_folds; - fold_T *fpn = NULL; + fold_T *fpn = NULL; int current_fdl = 0; linenr_T fold_start_lnum = 0; linenr_T lnum_rel = fline.lnum; while (current_fdl < fline.lvl) { - if (!foldFind(gap, lnum_rel, &fpn)) + if (!foldFind(gap, lnum_rel, &fpn)) { break; + } ++current_fdl; fold_start_lnum += fpn->fd_top; @@ -2101,8 +2121,9 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) if (fpn != NULL && current_fdl == fline.lvl) { linenr_T fold_end_lnum = fold_start_lnum + fpn->fd_len; - if (fold_end_lnum > bot) + if (fold_end_lnum > bot) { bot = fold_end_lnum; + } } } @@ -2115,34 +2136,37 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) while (!got_int) { /* Always stop at the end of the file ("end" can be past the end of * the file). */ - if (fline.lnum > wp->w_buffer->b_ml.ml_line_count) + if (fline.lnum > wp->w_buffer->b_ml.ml_line_count) { break; + } if (fline.lnum > end) { /* For "marker", "expr" and "syntax" methods: If a change caused * a fold to be removed, we need to continue at least until where * it ended. */ if (getlevel != foldlevelMarker && getlevel != foldlevelSyntax - && getlevel != foldlevelExpr) + && getlevel != foldlevelExpr) { break; + } if ((start <= end && foldFind(&wp->w_folds, end, &fp) && fp->fd_top + fp->fd_len - 1 > end) || (fline.lvl == 0 && foldFind(&wp->w_folds, fline.lnum, &fp) - && fp->fd_top < fline.lnum)) + && fp->fd_top < fline.lnum)) { end = fp->fd_top + fp->fd_len - 1; - else if (getlevel == foldlevelSyntax - && foldLevelWin(wp, fline.lnum) != fline.lvl) + } else if (getlevel == foldlevelSyntax + && foldLevelWin(wp, fline.lnum) != fline.lvl) { /* For "syntax" method: Compare the foldlevel that the syntax * tells us to the foldlevel from the existing folds. If they * don't match continue updating folds. */ end = fline.lnum; - else + } else { break; + } } - /* A level 1 fold starts at a line with foldlevel > 0. */ + // A level 1 fold starts at a line with foldlevel > 0. if (fline.lvl > 0) { invalid_top = fline.lnum; invalid_bot = end; @@ -2150,8 +2174,9 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) FD_LEVEL); start = fline.lnum; } else { - if (fline.lnum == wp->w_buffer->b_ml.ml_line_count) + if (fline.lnum == wp->w_buffer->b_ml.ml_line_count) { break; + } ++fline.lnum; fline.lvl = fline.lvl_next; getlevel(&fline); @@ -2161,56 +2186,58 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) // There can't be any folds from start until end now. foldRemove(wp, &wp->w_folds, start, end); - /* If some fold changed, need to redraw and position cursor. */ - if (fold_changed && wp->w_p_fen) + // If some fold changed, need to redraw and position cursor. + if (fold_changed && wp->w_p_fen) { changed_window_setting_win(wp); + } /* If we updated folds past "bot", need to redraw more lines. Don't do * this in other situations, the changed lines will be redrawn anyway and * this method can cause the whole window to be updated. */ if (end != bot) { - if (wp->w_redraw_top == 0 || wp->w_redraw_top > top) + if (wp->w_redraw_top == 0 || wp->w_redraw_top > top) { wp->w_redraw_top = top; - if (wp->w_redraw_bot < end) + } + if (wp->w_redraw_bot < end) { wp->w_redraw_bot = end; + } } invalid_top = (linenr_T)0; } -/* foldUpdateIEMSRecurse() {{{2 */ -/* - * Update a fold that starts at "flp->lnum". At this line there is always a - * valid foldlevel, and its level >= "level". - * "flp" is valid for "flp->lnum" when called and it's valid when returning. - * "flp->lnum" is set to the lnum just below the fold, if it ends before - * "bot", it's "bot" plus one if the fold continues and it's bigger when using - * the marker method and a text change made following folds to change. - * When returning, "flp->lnum_save" is the line number that was used to get - * the level when the level at "flp->lnum" is invalid. - * Remove any folds from "startlnum" up to here at this level. - * Recursively update nested folds. - * Below line "bot" there are no changes in the text. - * "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the - * outer fold. - * "flp->off" is the offset to the real line number in the buffer. - * - * All this would be a lot simpler if all folds in the range would be deleted - * and then created again. But we would lose all information about the - * folds, even when making changes that don't affect the folding (e.g. "vj~"). - * - * Returns bot, which may have been increased for lines that also need to be - * updated as a result of a detected change in the fold. - */ -static linenr_T foldUpdateIEMSRecurse( - garray_T *const gap, const int level, const linenr_T startlnum, - fline_T *const flp, LevelGetter getlevel, linenr_T bot, - const char topflags // containing fold flags -) +// foldUpdateIEMSRecurse() {{{2 +/// Update a fold that starts at "flp->lnum". At this line there is always a +/// valid foldlevel, and its level >= "level". +/// +/// "flp" is valid for "flp->lnum" when called and it's valid when returning. +/// "flp->lnum" is set to the lnum just below the fold, if it ends before +/// "bot", it's "bot" plus one if the fold continues and it's bigger when using +/// the marker method and a text change made following folds to change. +/// When returning, "flp->lnum_save" is the line number that was used to get +/// the level when the level at "flp->lnum" is invalid. +/// Remove any folds from "startlnum" up to here at this level. +/// Recursively update nested folds. +/// Below line "bot" there are no changes in the text. +/// "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the +/// outer fold. +/// "flp->off" is the offset to the real line number in the buffer. +/// +/// All this would be a lot simpler if all folds in the range would be deleted +/// and then created again. But we would lose all information about the +/// folds, even when making changes that don't affect the folding (e.g. "vj~"). +/// +/// @param topflags containing fold flags +/// +/// @return bot, which may have been increased for lines that also need to be +/// updated as a result of a detected change in the fold. +static linenr_T foldUpdateIEMSRecurse(garray_T *const gap, const int level, + const linenr_T startlnum, fline_T *const flp, + LevelGetter getlevel, linenr_T bot, const char topflags) { linenr_T ll; - fold_T *fp = NULL; - fold_T *fp2; + fold_T *fp = NULL; + fold_T *fp2; int lvl = level; linenr_T startlnum2 = startlnum; const linenr_T firstlnum = flp->lnum; // first lnum we got @@ -2248,7 +2275,7 @@ static linenr_T foldUpdateIEMSRecurse( */ flp->lnum_save = flp->lnum; while (!got_int) { - /* Updating folds can be slow, check for CTRL-C. */ + // Updating folds can be slow, check for CTRL-C. line_breakcheck(); /* Set "lvl" to the level of line "flp->lnum". When flp->start is set @@ -2256,11 +2283,13 @@ static linenr_T foldUpdateIEMSRecurse( * force the fold to end. Do the same when had_end is set: Previous * line was marked as end of a fold. */ lvl = flp->lvl; - if (lvl > MAX_LEVEL) + if (lvl > MAX_LEVEL) { lvl = MAX_LEVEL; + } if (flp->lnum > firstlnum - && (level > lvl - flp->start || level >= flp->had_end)) + && (level > lvl - flp->start || level >= flp->had_end)) { lvl = 0; + } if (flp->lnum > bot && !finish && fp != NULL) { /* For "marker" and "syntax" methods: @@ -2271,8 +2300,9 @@ static linenr_T foldUpdateIEMSRecurse( */ if (getlevel != foldlevelMarker && getlevel != foldlevelExpr - && getlevel != foldlevelSyntax) + && getlevel != foldlevelSyntax) { break; + } i = 0; fp2 = fp; if (lvl >= level) { @@ -2313,10 +2343,11 @@ static linenr_T foldUpdateIEMSRecurse( while (!got_int) { /* set concat to 1 if it's allowed to concatenated this fold * with a previous one that touches it. */ - if (flp->start != 0 || flp->had_end <= MAX_LEVEL) + if (flp->start != 0 || flp->had_end <= MAX_LEVEL) { concat = 0; - else + } else { concat = 1; + } /* Find an existing fold to re-use. Preferably one that * includes startlnum, otherwise one that ends just before @@ -2439,10 +2470,12 @@ static linenr_T foldUpdateIEMSRecurse( fp->fd_flags = FD_OPEN; } else if (i <= 0) { fp->fd_flags = topflags; - if (topflags != FD_LEVEL) + if (topflags != FD_LEVEL) { flp->wp->w_fold_manual = true; - } else + } + } else { fp->fd_flags = (fp - 1)->fd_flags; + } fp->fd_small = kNone; // If using the "marker", "expr" or "syntax" method, we // need to continue until the end of the fold is found. @@ -2491,7 +2524,7 @@ static linenr_T foldUpdateIEMSRecurse( bot += fp->fd_top; startlnum2 = flp->lnum; - /* This fold may end at the same line, don't incr. flp->lnum. */ + // This fold may end at the same line, don't incr. flp->lnum. } else { /* * Get the level of the next line, then continue the loop to check @@ -2502,20 +2535,23 @@ static linenr_T foldUpdateIEMSRecurse( flp->lnum = flp->lnum_save; ll = flp->lnum + 1; while (!got_int) { - /* Make the previous level available to foldlevel(). */ + // Make the previous level available to foldlevel(). prev_lnum = flp->lnum; prev_lnum_lvl = flp->lvl; - if (++flp->lnum > linecount) + if (++flp->lnum > linecount) { break; + } flp->lvl = flp->lvl_next; getlevel(flp); - if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL) + if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL) { break; + } } prev_lnum = 0; - if (flp->lnum > linecount) + if (flp->lnum > linecount) { break; + } /* leave flp->lnum_save to lnum of the line that was used to get * the level, flp->lnum to the lnum of the next line. */ @@ -2524,8 +2560,9 @@ static linenr_T foldUpdateIEMSRecurse( } } - if (fp == NULL) /* only happens when got_int is set */ + if (fp == NULL) { // only happens when got_int is set return bot; + } /* * Get here when: @@ -2574,12 +2611,13 @@ static linenr_T foldUpdateIEMSRecurse( } } - /* delete following folds that end before the current line */ + // delete following folds that end before the current line for (;; ) { fp2 = fp + 1; if (fp2 >= (fold_T *)gap->ga_data + gap->ga_len - || fp2->fd_top > flp->lnum) + || fp2->fd_top > flp->lnum) { break; + } if (fp2->fd_top + fp2->fd_len > flp->lnum) { if (fp2->fd_top < flp->lnum) { // Make fold that includes lnum start at lnum. @@ -2603,19 +2641,20 @@ static linenr_T foldUpdateIEMSRecurse( /* Need to redraw the lines we inspected, which might be further down than * was asked for. */ - if (bot < flp->lnum - 1) + if (bot < flp->lnum - 1) { bot = flp->lnum - 1; + } return bot; } -/* foldInsert() {{{2 */ +// foldInsert() {{{2 /* * Insert a new fold in "gap" at position "i". */ static void foldInsert(garray_T *gap, int i) { - fold_T *fp; + fold_T *fp; ga_grow(gap, 1); @@ -2627,7 +2666,7 @@ static void foldInsert(garray_T *gap, int i) ga_init(&fp->fd_nested, (int)sizeof(fold_T), 10); } -/* foldSplit() {{{2 */ +// foldSplit() {{{2 /* * Split the "i"th fold in "gap", which starts before "top" and ends below * "bot" in two pieces, one ending above "top" and the other starting below @@ -2635,14 +2674,12 @@ static void foldInsert(garray_T *gap, int i) * The caller must first have taken care of any nested folds from "top" to * "bot"! */ -static void foldSplit(buf_T *buf, garray_T *const gap, - const int i, const linenr_T top, - const linenr_T bot - ) +static void foldSplit(buf_T *buf, garray_T *const gap, const int i, const linenr_T top, + const linenr_T bot) { - fold_T *fp2; + fold_T *fp2; - /* The fold continues below bot, need to split it. */ + // The fold continues below bot, need to split it. foldInsert(gap, i + 1); fold_T *const fp = (fold_T *)gap->ga_data + i; @@ -2675,7 +2712,7 @@ static void foldSplit(buf_T *buf, garray_T *const gap, fold_changed = true; } -/* foldRemove() {{{2 */ +// foldRemove() {{{2 /* * Remove folds within the range "top" to and including "bot". * Check for these situations: @@ -2694,11 +2731,9 @@ static void foldSplit(buf_T *buf, garray_T *const gap, * 5: made to start below "bot". * 6: not changed */ -static void foldRemove( - win_T *const wp, garray_T *gap, linenr_T top, linenr_T bot -) +static void foldRemove(win_T *const wp, garray_T *gap, linenr_T top, linenr_T bot) { - fold_T *fp = NULL; + fold_T *fp = NULL; if (bot < top) { return; // nothing to do @@ -2731,10 +2766,9 @@ static void foldRemove( fold_changed = true; if (fp->fd_top + fp->fd_len - 1 > bot) { // 5: Make fold that includes bot start below bot. - foldMarkAdjustRecurse( - wp, &fp->fd_nested, - (linenr_T)0, (long)(bot - fp->fd_top), - (linenr_T)MAXLNUM, (long)(fp->fd_top - bot - 1)); + foldMarkAdjustRecurse(wp, &fp->fd_nested, + (linenr_T)0, (long)(bot - fp->fd_top), + (linenr_T)MAXLNUM, (long)(fp->fd_top - bot - 1)); fp->fd_len -= bot - fp->fd_top + 1; fp->fd_top = bot + 1; break; @@ -2747,10 +2781,7 @@ static void foldRemove( } // foldReverseOrder() {{{2 -static void foldReverseOrder( - garray_T *gap, - const linenr_T start_arg, - const linenr_T end_arg) +static void foldReverseOrder(garray_T *gap, const linenr_T start_arg, const linenr_T end_arg) { linenr_T start = start_arg; linenr_T end = end_arg; @@ -2805,11 +2836,8 @@ static void truncate_fold(win_T *const wp, fold_T *fp, linenr_T end) #define VALID_FOLD(fp, gap) \ ((gap)->ga_len > 0 && (fp) < ((fold_T *)(gap)->ga_data + (gap)->ga_len)) #define FOLD_INDEX(fp, gap) ((size_t)(fp - ((fold_T *)(gap)->ga_data))) -void foldMoveRange( - win_T *const wp, garray_T *gap, - const linenr_T line1, const linenr_T line2, - const linenr_T dest -) +void foldMoveRange(win_T *const wp, garray_T *gap, const linenr_T line1, const linenr_T line2, + const linenr_T dest) { fold_T *fp; const linenr_T range_len = line2 - line1 + 1; @@ -2909,7 +2937,7 @@ void foldMoveRange( #undef VALID_FOLD #undef FOLD_INDEX -/* foldMerge() {{{2 */ +// foldMerge() {{{2 /* * Merge two adjacent folds (and the nested ones in them). * This only works correctly when the folds are really adjacent! Thus "fp1" @@ -2919,11 +2947,11 @@ void foldMoveRange( */ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) { - fold_T *fp3; - fold_T *fp4; + fold_T *fp3; + fold_T *fp4; int idx; - garray_T *gap1 = &fp1->fd_nested; - garray_T *gap2 = &fp2->fd_nested; + garray_T *gap1 = &fp1->fd_nested; + garray_T *gap2 = &fp2->fd_nested; /* If the last nested fold in fp1 touches the first nested fold in fp2, * merge them recursively. */ @@ -2931,7 +2959,7 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) foldMerge(wp, fp3, gap2, fp4); } - /* Move nested folds in fp2 to the end of fp1. */ + // Move nested folds in fp2 to the end of fp1. if (!GA_EMPTY(gap2)) { ga_grow(gap1, gap2->ga_len); for (idx = 0; idx < gap2->ga_len; ++idx) { @@ -2948,7 +2976,7 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) fold_changed = true; } -/* foldlevelIndent() {{{2 */ +// foldlevelIndent() {{{2 /* * Low level function to get the foldlevel for the "indent" method. * Doesn't use any caching. @@ -2956,8 +2984,8 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) */ static void foldlevelIndent(fline_T *flp) { - char_u *s; - buf_T *buf; + char_u *s; + buf_T *buf; linenr_T lnum = flp->lnum + flp->off; buf = flp->wp->w_buffer; @@ -2966,33 +2994,35 @@ static void foldlevelIndent(fline_T *flp) /* empty line or lines starting with a character in 'foldignore': level * depends on surrounding lines */ if (*s == NUL || vim_strchr(flp->wp->w_p_fdi, *s) != NULL) { - /* first and last line can't be undefined, use level 0 */ - if (lnum == 1 || lnum == buf->b_ml.ml_line_count) + // first and last line can't be undefined, use level 0 + if (lnum == 1 || lnum == buf->b_ml.ml_line_count) { flp->lvl = 0; - else + } else { flp->lvl = -1; + } } else { flp->lvl = get_indent_buf(buf, lnum) / get_sw_value(buf); } if (flp->lvl > flp->wp->w_p_fdn) { - flp->lvl = (int) MAX(0, flp->wp->w_p_fdn); + flp->lvl = (int)MAX(0, flp->wp->w_p_fdn); } } -/* foldlevelDiff() {{{2 */ +// foldlevelDiff() {{{2 /* * Low level function to get the foldlevel for the "diff" method. * Doesn't use any caching. */ static void foldlevelDiff(fline_T *flp) { - if (diff_infold(flp->wp, flp->lnum + flp->off)) + if (diff_infold(flp->wp, flp->lnum + flp->off)) { flp->lvl = 1; - else + } else { flp->lvl = 0; + } } -/* foldlevelExpr() {{{2 */ +// foldlevelExpr() {{{2 /* * Low level function to get the foldlevel for the "expr" method. * Doesn't use any caching. @@ -3000,20 +3030,21 @@ static void foldlevelDiff(fline_T *flp) */ static void foldlevelExpr(fline_T *flp) { - win_T *win; + win_T *win; int c; linenr_T lnum = flp->lnum + flp->off; win = curwin; curwin = flp->wp; curbuf = flp->wp->w_buffer; - set_vim_var_nr(VV_LNUM, (varnumber_T) lnum); + set_vim_var_nr(VV_LNUM, (varnumber_T)lnum); flp->start = 0; flp->had_end = flp->end; flp->end = MAX_LEVEL + 1; - if (lnum <= 1) + if (lnum <= 1) { flp->lvl = 0; + } /* KeyTyped may be reset to 0 when calling a function which invokes * do_cmdline(). To make 'foldopen' work correctly restore KeyTyped. */ @@ -3022,46 +3053,54 @@ static void foldlevelExpr(fline_T *flp) KeyTyped = save_keytyped; switch (c) { - /* "a1", "a2", .. : add to the fold level */ - case 'a': if (flp->lvl >= 0) { + // "a1", "a2", .. : add to the fold level + case 'a': + if (flp->lvl >= 0) { flp->lvl += n; flp->lvl_next = flp->lvl; - } + } flp->start = n; break; - /* "s1", "s2", .. : subtract from the fold level */ - case 's': if (flp->lvl >= 0) { - if (n > flp->lvl) + // "s1", "s2", .. : subtract from the fold level + case 's': + if (flp->lvl >= 0) { + if (n > flp->lvl) { flp->lvl_next = 0; - else + } else { flp->lvl_next = flp->lvl - n; + } flp->end = flp->lvl_next + 1; - } + } break; - /* ">1", ">2", .. : start a fold with a certain level */ - case '>': flp->lvl = n; + // ">1", ">2", .. : start a fold with a certain level + case '>': + flp->lvl = n; flp->lvl_next = n; flp->start = 1; break; - /* "<1", "<2", .. : end a fold with a certain level */ - case '<': flp->lvl_next = n - 1; + // "<1", "<2", .. : end a fold with a certain level + case '<': + flp->lvl_next = n - 1; flp->end = n; break; - /* "=": No change in level */ - case '=': flp->lvl_next = flp->lvl; + // "=": No change in level + case '=': + flp->lvl_next = flp->lvl; break; - /* "-1", "0", "1", ..: set fold level */ - default: if (n < 0) + // "-1", "0", "1", ..: set fold level + default: + if (n < 0) { /* Use the current level for the next line, so that "a1" * will work there. */ flp->lvl_next = flp->lvl; - else + } else { flp->lvl_next = n; + } flp->lvl = n; break; } @@ -3073,15 +3112,16 @@ static void foldlevelExpr(fline_T *flp) flp->lvl = 0; flp->lvl_next = 0; } - if (lnum == curbuf->b_ml.ml_line_count) + if (lnum == curbuf->b_ml.ml_line_count) { flp->lvl_next = 0; + } } curwin = win; curbuf = curwin->w_buffer; } -/* parseMarker() {{{2 */ +// parseMarker() {{{2 /* * Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and * "foldendmarkerlen". @@ -3094,7 +3134,7 @@ static void parseMarker(win_T *wp) foldendmarkerlen = STRLEN(foldendmarker); } -/* foldlevelMarker() {{{2 */ +// foldlevelMarker() {{{2 /* * Low level function to get the foldlevel for the "marker" method. * "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been @@ -3106,20 +3146,20 @@ static void parseMarker(win_T *wp) */ static void foldlevelMarker(fline_T *flp) { - char_u *startmarker; + char_u *startmarker; int cstart; int cend; int start_lvl = flp->lvl; - char_u *s; + char_u *s; int n; - /* cache a few values for speed */ + // cache a few values for speed startmarker = flp->wp->w_p_fmr; cstart = *startmarker; ++startmarker; cend = *foldendmarker; - /* Default: no start found, next level is same as current level */ + // Default: no start found, next level is same as current level flp->start = 0; flp->lvl_next = flp->lvl; @@ -3127,17 +3167,18 @@ static void foldlevelMarker(fline_T *flp) while (*s) { if (*s == cstart && STRNCMP(s + 1, startmarker, foldstartmarkerlen - 1) == 0) { - /* found startmarker: set flp->lvl */ + // found startmarker: set flp->lvl s += foldstartmarkerlen; if (ascii_isdigit(*s)) { n = atoi((char *)s); if (n > 0) { flp->lvl = n; flp->lvl_next = n; - if (n <= start_lvl) + if (n <= start_lvl) { flp->start = 1; - else + } else { flp->start = n - start_lvl; + } } } else { ++flp->lvl; @@ -3146,16 +3187,17 @@ static void foldlevelMarker(fline_T *flp) } } else if (*s == cend && STRNCMP(s + 1, foldendmarker + 1, foldendmarkerlen - 1) == 0) { - /* found endmarker: set flp->lvl_next */ + // found endmarker: set flp->lvl_next s += foldendmarkerlen; if (ascii_isdigit(*s)) { n = atoi((char *)s); if (n > 0) { flp->lvl = n; flp->lvl_next = n - 1; - /* never start a fold with an end marker */ - if (flp->lvl_next > start_lvl) + // never start a fold with an end marker + if (flp->lvl_next > start_lvl) { flp->lvl_next = start_lvl; + } } } else { flp->lvl_next--; @@ -3165,12 +3207,13 @@ static void foldlevelMarker(fline_T *flp) } } - /* The level can't go negative, must be missing a start marker. */ - if (flp->lvl_next < 0) + // The level can't go negative, must be missing a start marker. + if (flp->lvl_next < 0) { flp->lvl_next = 0; + } } -/* foldlevelSyntax() {{{2 */ +// foldlevelSyntax() {{{2 /* * Low level function to get the foldlevel for the "syntax" method. * Doesn't use any caching. @@ -3180,20 +3223,20 @@ static void foldlevelSyntax(fline_T *flp) linenr_T lnum = flp->lnum + flp->off; int n; - /* Use the maximum fold level at the start of this line and the next. */ + // Use the maximum fold level at the start of this line and the next. flp->lvl = syn_get_foldlevel(flp->wp, lnum); flp->start = 0; if (lnum < flp->wp->w_buffer->b_ml.ml_line_count) { n = syn_get_foldlevel(flp->wp, lnum + 1); if (n > flp->lvl) { - flp->start = n - flp->lvl; /* fold(s) start here */ + flp->start = n - flp->lvl; // fold(s) start here flp->lvl = n; } } } -/* functions for storing the fold state in a View {{{1 */ -/* put_folds() {{{2 */ +// functions for storing the fold state in a View {{{1 +// put_folds() {{{2 /* * Write commands to "fd" to restore the manual folds in window "wp". @@ -3209,14 +3252,15 @@ int put_folds(FILE *fd, win_T *wp) } } - /* If some folds are manually opened/closed, need to restore that. */ - if (wp->w_fold_manual) + // If some folds are manually opened/closed, need to restore that. + if (wp->w_fold_manual) { return put_foldopen_recurse(fd, wp, &wp->w_folds, (linenr_T)0); + } return OK; } -/* put_folds_recurse() {{{2 */ +// put_folds_recurse() {{{2 /* * Write commands to "fd" to recreate manually created folds. * Returns FAIL when writing failed. @@ -3225,20 +3269,22 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off) { fold_T *fp = (fold_T *)gap->ga_data; for (int i = 0; i < gap->ga_len; i++) { - /* Do nested folds first, they will be created closed. */ - if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) + // Do nested folds first, they will be created closed. + if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) { return FAIL; + } if (fprintf(fd, "%" PRId64 ",%" PRId64 "fold", (int64_t)(fp->fd_top + off), (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0 - || put_eol(fd) == FAIL) + || put_eol(fd) == FAIL) { return FAIL; + } ++fp; } return OK; } -/* put_foldopen_recurse() {{{2 */ +// put_foldopen_recurse() {{{2 /* * Write commands to "fd" to open and close manually opened/closed folds. * Returns FAIL when writing failed. @@ -3251,19 +3297,22 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off for (int i = 0; i < gap->ga_len; i++) { if (fp->fd_flags != FD_LEVEL) { if (!GA_EMPTY(&fp->fd_nested)) { - /* open nested folds while this fold is open */ + // open nested folds while this fold is open if (fprintf(fd, "%" PRId64, (int64_t)(fp->fd_top + off)) < 0 || put_eol(fd) == FAIL - || put_line(fd, "normal! zo") == FAIL) + || put_line(fd, "normal! zo") == FAIL) { return FAIL; + } if (put_foldopen_recurse(fd, wp, &fp->fd_nested, - off + fp->fd_top) - == FAIL) + off + fp->fd_top) + == FAIL) { return FAIL; - /* close the parent when needed */ + } + // close the parent when needed if (fp->fd_flags == FD_CLOSED) { - if (put_fold_open_close(fd, fp, off) == FAIL) + if (put_fold_open_close(fd, fp, off) == FAIL) { return FAIL; + } } } else { /* Open or close the leaf according to the window foldlevel. @@ -3271,9 +3320,11 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off * the parent. */ level = foldLevelWin(wp, off + fp->fd_top); if ((fp->fd_flags == FD_CLOSED && wp->w_p_fdl >= level) - || (fp->fd_flags != FD_CLOSED && wp->w_p_fdl < level)) - if (put_fold_open_close(fd, fp, off) == FAIL) + || (fp->fd_flags != FD_CLOSED && wp->w_p_fdl < level)) { + if (put_fold_open_close(fd, fp, off) == FAIL) { return FAIL; + } + } } } ++fp; @@ -3282,7 +3333,7 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off return OK; } -/* put_fold_open_close() {{{2 */ +// put_fold_open_close() {{{2 /* * Write the open or close command to "fd". * Returns FAIL when writing failed. @@ -3292,11 +3343,12 @@ static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off) if (fprintf(fd, "%" PRId64, (int64_t)(fp->fd_top + off)) < 0 || put_eol(fd) == FAIL || fprintf(fd, "normal! z%c", - fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 - || put_eol(fd) == FAIL) + fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 + || put_eol(fd) == FAIL) { return FAIL; + } return OK; } -/* }}}1 */ +// }}}1 diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index cba372b9d3..fea1ab77a2 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -31,30 +31,30 @@ #include #include -#include "nvim/vim.h" #include "nvim/ascii.h" +#include "nvim/vim.h" #ifdef HAVE_LOCALE_H # include #endif -#include "nvim/eval.h" -#include "nvim/path.h" -#include "nvim/iconv.h" -#include "nvim/mbyte.h" +#include "nvim/arabic.h" #include "nvim/charset.h" #include "nvim/cursor.h" +#include "nvim/eval.h" #include "nvim/fileio.h" #include "nvim/func_attr.h" +#include "nvim/iconv.h" +#include "nvim/mark.h" +#include "nvim/mbyte.h" #include "nvim/memline.h" +#include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/memory.h" #include "nvim/option.h" +#include "nvim/os/os.h" +#include "nvim/path.h" #include "nvim/screen.h" #include "nvim/spell.h" #include "nvim/strings.h" -#include "nvim/os/os.h" -#include "nvim/arabic.h" -#include "nvim/mark.h" typedef struct { int rangeStart; @@ -70,6 +70,7 @@ struct interval { #ifdef INCLUDE_GENERATED_DECLARATIONS # include "mbyte.c.generated.h" + # include "unicode_tables.generated.h" #endif @@ -127,131 +128,131 @@ static struct enc_canon_table[] = { #define IDX_LATIN_1 0 - {"latin1", ENC_8BIT + ENC_LATIN1, 1252}, + { "latin1", ENC_8BIT + ENC_LATIN1, 1252 }, #define IDX_ISO_2 1 - {"iso-8859-2", ENC_8BIT, 0}, + { "iso-8859-2", ENC_8BIT, 0 }, #define IDX_ISO_3 2 - {"iso-8859-3", ENC_8BIT, 0}, + { "iso-8859-3", ENC_8BIT, 0 }, #define IDX_ISO_4 3 - {"iso-8859-4", ENC_8BIT, 0}, + { "iso-8859-4", ENC_8BIT, 0 }, #define IDX_ISO_5 4 - {"iso-8859-5", ENC_8BIT, 0}, + { "iso-8859-5", ENC_8BIT, 0 }, #define IDX_ISO_6 5 - {"iso-8859-6", ENC_8BIT, 0}, + { "iso-8859-6", ENC_8BIT, 0 }, #define IDX_ISO_7 6 - {"iso-8859-7", ENC_8BIT, 0}, + { "iso-8859-7", ENC_8BIT, 0 }, #define IDX_ISO_8 7 - {"iso-8859-8", ENC_8BIT, 0}, + { "iso-8859-8", ENC_8BIT, 0 }, #define IDX_ISO_9 8 - {"iso-8859-9", ENC_8BIT, 0}, + { "iso-8859-9", ENC_8BIT, 0 }, #define IDX_ISO_10 9 - {"iso-8859-10", ENC_8BIT, 0}, + { "iso-8859-10", ENC_8BIT, 0 }, #define IDX_ISO_11 10 - {"iso-8859-11", ENC_8BIT, 0}, + { "iso-8859-11", ENC_8BIT, 0 }, #define IDX_ISO_13 11 - {"iso-8859-13", ENC_8BIT, 0}, + { "iso-8859-13", ENC_8BIT, 0 }, #define IDX_ISO_14 12 - {"iso-8859-14", ENC_8BIT, 0}, + { "iso-8859-14", ENC_8BIT, 0 }, #define IDX_ISO_15 13 - {"iso-8859-15", ENC_8BIT + ENC_LATIN9, 0}, + { "iso-8859-15", ENC_8BIT + ENC_LATIN9, 0 }, #define IDX_KOI8_R 14 - {"koi8-r", ENC_8BIT, 0}, + { "koi8-r", ENC_8BIT, 0 }, #define IDX_KOI8_U 15 - {"koi8-u", ENC_8BIT, 0}, + { "koi8-u", ENC_8BIT, 0 }, #define IDX_UTF8 16 - {"utf-8", ENC_UNICODE, 0}, + { "utf-8", ENC_UNICODE, 0 }, #define IDX_UCS2 17 - {"ucs-2", ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0}, + { "ucs-2", ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0 }, #define IDX_UCS2LE 18 - {"ucs-2le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0}, + { "ucs-2le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0 }, #define IDX_UTF16 19 - {"utf-16", ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0}, + { "utf-16", ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0 }, #define IDX_UTF16LE 20 - {"utf-16le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0}, + { "utf-16le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0 }, #define IDX_UCS4 21 - {"ucs-4", ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0}, + { "ucs-4", ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0 }, #define IDX_UCS4LE 22 - {"ucs-4le", ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0}, + { "ucs-4le", ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0 }, - /* For debugging DBCS encoding on Unix. */ + // For debugging DBCS encoding on Unix. #define IDX_DEBUG 23 - {"debug", ENC_DBCS, DBCS_DEBUG}, + { "debug", ENC_DBCS, DBCS_DEBUG }, #define IDX_EUC_JP 24 - {"euc-jp", ENC_DBCS, DBCS_JPNU}, + { "euc-jp", ENC_DBCS, DBCS_JPNU }, #define IDX_SJIS 25 - {"sjis", ENC_DBCS, DBCS_JPN}, + { "sjis", ENC_DBCS, DBCS_JPN }, #define IDX_EUC_KR 26 - {"euc-kr", ENC_DBCS, DBCS_KORU}, + { "euc-kr", ENC_DBCS, DBCS_KORU }, #define IDX_EUC_CN 27 - {"euc-cn", ENC_DBCS, DBCS_CHSU}, + { "euc-cn", ENC_DBCS, DBCS_CHSU }, #define IDX_EUC_TW 28 - {"euc-tw", ENC_DBCS, DBCS_CHTU}, + { "euc-tw", ENC_DBCS, DBCS_CHTU }, #define IDX_BIG5 29 - {"big5", ENC_DBCS, DBCS_CHT}, + { "big5", ENC_DBCS, DBCS_CHT }, /* MS-DOS and MS-Windows codepages are included here, so that they can be * used on Unix too. Most of them are similar to ISO-8859 encodings, but * not exactly the same. */ #define IDX_CP437 30 - {"cp437", ENC_8BIT, 437}, /* like iso-8859-1 */ + { "cp437", ENC_8BIT, 437 }, // like iso-8859-1 #define IDX_CP737 31 - {"cp737", ENC_8BIT, 737}, /* like iso-8859-7 */ + { "cp737", ENC_8BIT, 737 }, // like iso-8859-7 #define IDX_CP775 32 - {"cp775", ENC_8BIT, 775}, /* Baltic */ + { "cp775", ENC_8BIT, 775 }, // Baltic #define IDX_CP850 33 - {"cp850", ENC_8BIT, 850}, /* like iso-8859-4 */ + { "cp850", ENC_8BIT, 850 }, // like iso-8859-4 #define IDX_CP852 34 - {"cp852", ENC_8BIT, 852}, /* like iso-8859-1 */ + { "cp852", ENC_8BIT, 852 }, // like iso-8859-1 #define IDX_CP855 35 - {"cp855", ENC_8BIT, 855}, /* like iso-8859-2 */ + { "cp855", ENC_8BIT, 855 }, // like iso-8859-2 #define IDX_CP857 36 - {"cp857", ENC_8BIT, 857}, /* like iso-8859-5 */ + { "cp857", ENC_8BIT, 857 }, // like iso-8859-5 #define IDX_CP860 37 - {"cp860", ENC_8BIT, 860}, /* like iso-8859-9 */ + { "cp860", ENC_8BIT, 860 }, // like iso-8859-9 #define IDX_CP861 38 - {"cp861", ENC_8BIT, 861}, /* like iso-8859-1 */ + { "cp861", ENC_8BIT, 861 }, // like iso-8859-1 #define IDX_CP862 39 - {"cp862", ENC_8BIT, 862}, /* like iso-8859-1 */ + { "cp862", ENC_8BIT, 862 }, // like iso-8859-1 #define IDX_CP863 40 - {"cp863", ENC_8BIT, 863}, /* like iso-8859-8 */ + { "cp863", ENC_8BIT, 863 }, // like iso-8859-8 #define IDX_CP865 41 - {"cp865", ENC_8BIT, 865}, /* like iso-8859-1 */ + { "cp865", ENC_8BIT, 865 }, // like iso-8859-1 #define IDX_CP866 42 - {"cp866", ENC_8BIT, 866}, /* like iso-8859-5 */ + { "cp866", ENC_8BIT, 866 }, // like iso-8859-5 #define IDX_CP869 43 - {"cp869", ENC_8BIT, 869}, /* like iso-8859-7 */ + { "cp869", ENC_8BIT, 869 }, // like iso-8859-7 #define IDX_CP874 44 - {"cp874", ENC_8BIT, 874}, /* Thai */ + { "cp874", ENC_8BIT, 874 }, // Thai #define IDX_CP932 45 - {"cp932", ENC_DBCS, DBCS_JPN}, + { "cp932", ENC_DBCS, DBCS_JPN }, #define IDX_CP936 46 - {"cp936", ENC_DBCS, DBCS_CHS}, + { "cp936", ENC_DBCS, DBCS_CHS }, #define IDX_CP949 47 - {"cp949", ENC_DBCS, DBCS_KOR}, + { "cp949", ENC_DBCS, DBCS_KOR }, #define IDX_CP950 48 - {"cp950", ENC_DBCS, DBCS_CHT}, + { "cp950", ENC_DBCS, DBCS_CHT }, #define IDX_CP1250 49 - {"cp1250", ENC_8BIT, 1250}, /* Czech, Polish, etc. */ + { "cp1250", ENC_8BIT, 1250 }, // Czech, Polish, etc. #define IDX_CP1251 50 - {"cp1251", ENC_8BIT, 1251}, /* Cyrillic */ - /* cp1252 is considered to be equal to latin1 */ + { "cp1251", ENC_8BIT, 1251 }, // Cyrillic + // cp1252 is considered to be equal to latin1 #define IDX_CP1253 51 - {"cp1253", ENC_8BIT, 1253}, /* Greek */ + { "cp1253", ENC_8BIT, 1253 }, // Greek #define IDX_CP1254 52 - {"cp1254", ENC_8BIT, 1254}, /* Turkish */ + { "cp1254", ENC_8BIT, 1254 }, // Turkish #define IDX_CP1255 53 - {"cp1255", ENC_8BIT, 1255}, /* Hebrew */ + { "cp1255", ENC_8BIT, 1255 }, // Hebrew #define IDX_CP1256 54 - {"cp1256", ENC_8BIT, 1256}, /* Arabic */ + { "cp1256", ENC_8BIT, 1256 }, // Arabic #define IDX_CP1257 55 - {"cp1257", ENC_8BIT, 1257}, /* Baltic */ + { "cp1257", ENC_8BIT, 1257 }, // Baltic #define IDX_CP1258 56 - {"cp1258", ENC_8BIT, 1258}, /* Vietnamese */ + { "cp1258", ENC_8BIT, 1258 }, // Vietnamese #define IDX_MACROMAN 57 - {"macroman", ENC_8BIT + ENC_MACROMAN, 0}, /* Mac OS */ + { "macroman", ENC_8BIT + ENC_MACROMAN, 0 }, // Mac OS #define IDX_HPROMAN8 58 - {"hp-roman8", ENC_8BIT, 0}, /* HP Roman8 */ + { "hp-roman8", ENC_8BIT, 0 }, // HP Roman8 #define IDX_COUNT 59 }; @@ -336,9 +337,11 @@ static int enc_canon_search(const char_u *name) { int i; - for (i = 0; i < IDX_COUNT; ++i) - if (STRCMP(name, enc_canon_table[i].name) == 0) + for (i = 0; i < IDX_COUNT; ++i) { + if (STRCMP(name, enc_canon_table[i].name) == 0) { return i; + } + } return -1; } @@ -353,12 +356,13 @@ int enc_canon_props(const char_u *name) int i; i = enc_canon_search(name); - if (i >= 0) + if (i >= 0) { return enc_canon_table[i].prop; - if (STRNCMP(name, "2byte-", 6) == 0) + } else if (STRNCMP(name, "2byte-", 6) == 0) { return ENC_DBCS; - if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0) + } else if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0) { return ENC_8BIT; + } return 0; } @@ -436,21 +440,23 @@ static bool intable(const struct interval *table, size_t n_items, int c) { int mid, bot, top; - /* first quick check for Latin1 etc. characters */ - if (c < table[0].first) + // first quick check for Latin1 etc. characters + if (c < table[0].first) { return false; + } - /* binary search in table */ + // binary search in table bot = 0; top = (int)(n_items - 1); while (top >= bot) { mid = (bot + top) / 2; - if (table[mid].last < c) + if (table[mid].last < c) { bot = mid + 1; - else if (table[mid].first > c) + } else if (table[mid].first > c) { top = mid - 1; - else + } else { return true; + } } return false; } @@ -512,12 +518,14 @@ int utf_ptr2cells(const char_u *p) // Need to convert to a character number. if (*p >= 0x80) { c = utf_ptr2char(p); - /* An illegal byte is displayed as . */ - if (utf_ptr2len(p) == 1 || c == NUL) + // An illegal byte is displayed as . + if (utf_ptr2len(p) == 1 || c == NUL) { return 4; - /* If the char is ASCII it must be an overlong sequence. */ - if (c < 0x80) + } + // If the char is ASCII it must be an overlong sequence. + if (c < 0x80) { return char2cells(c); + } return utf_char2cells(c); } return 1; @@ -529,17 +537,20 @@ int utf_ptr2cells_len(const char_u *p, int size) { int c; - /* Need to convert to a wide character. */ + // Need to convert to a wide character. if (size > 0 && *p >= 0x80) { - if (utf_ptr2len_len(p, size) < utf8len_tab[*p]) - return 1; /* truncated */ + if (utf_ptr2len_len(p, size) < utf8len_tab[*p]) { + return 1; // truncated + } c = utf_ptr2char(p); - /* An illegal byte is displayed as . */ - if (utf_ptr2len(p) == 1 || c == NUL) + // An illegal byte is displayed as . + if (utf_ptr2len(p) == 1 || c == NUL) { return 4; - /* If the char is ASCII it must be an overlong sequence. */ - if (c < 0x80) + } + // If the char is ASCII it must be an overlong sequence. + if (c < 0x80) { return char2cells(c); + } return utf_char2cells(c); } return 1; @@ -651,13 +662,14 @@ static int utf_safe_read_char_adv(const char_u **s, size_t *n) { int c; - if (*n == 0) /* end of buffer */ + if (*n == 0) { // end of buffer return 0; + } uint8_t k = utf8len_tab_zero[**s]; if (k == 1) { - /* ASCII character or NUL */ + // ASCII character or NUL (*n)--; return *(*s)++; } @@ -674,14 +686,14 @@ static int utf_safe_read_char_adv(const char_u **s, size_t *n) * U+00C3 (UTF-8: 0xC3 0x83), so need to check that special case too. * It's safe even if n=1, else we would have k=2 > n. */ if (c != (int)(**s) || (c == 0xC3 && (*s)[1] == 0x83)) { - /* byte sequence was successfully decoded */ + // byte sequence was successfully decoded *s += k; *n -= k; return c; } } - /* byte sequence is incomplete or illegal */ + // byte sequence is incomplete or illegal return -1; } @@ -721,10 +733,12 @@ bool utf_composinglike(const char_u *p1, const char_u *p2) int c2; c2 = utf_ptr2char(p2); - if (utf_iscomposing(c2)) + if (utf_iscomposing(c2)) { return true; - if (!arabic_maycombine(c2)) + } + if (!arabic_maycombine(c2)) { return false; + } return arabic_combine(utf_ptr2char(p1), c2); } @@ -746,23 +760,26 @@ int utfc_ptr2char(const char_u *p, int *pcc) c = utf_ptr2char(p); len = utf_ptr2len(p); - /* Only accept a composing char when the first char isn't illegal. */ + // Only accept a composing char when the first char isn't illegal. if ((len > 1 || *p < 0x80) && p[len] >= 0x80 && UTF_COMPOSINGLIKE(p, p + len)) { cc = utf_ptr2char(p + len); for (;; ) { pcc[i++] = cc; - if (i == MAX_MCO) + if (i == MAX_MCO) { break; + } len += utf_ptr2len(p + len); - if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len))) + if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len))) { break; + } } } - if (i < MAX_MCO) /* last composing char must be 0 */ + if (i < MAX_MCO) { // last composing char must be 0 pcc[i] = 0; + } return c; } @@ -855,15 +872,19 @@ int utf_ptr2len_len(const char_u *p, int size) int m; len = utf8len_tab[*p]; - if (len == 1) - return 1; /* NUL, ascii or illegal lead byte */ - if (len > size) - m = size; /* incomplete byte sequence. */ - else + if (len == 1) { + return 1; // NUL, ascii or illegal lead byte + } + if (len > size) { + m = size; // incomplete byte sequence. + } else { m = len; - for (i = 1; i < m; ++i) - if ((p[i] & 0xc0) != 0x80) + } + for (i = 1; i < m; ++i) { + if ((p[i] & 0xc0) != 0x80) { return 1; + } + } return len; } @@ -915,17 +936,20 @@ int utfc_ptr2len_len(const char_u *p, int size) int len; int prevlen; - if (size < 1 || *p == NUL) + if (size < 1 || *p == NUL) { return 0; - if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) /* be quick for ASCII */ + } + if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) { // be quick for ASCII return 1; + } - /* Skip over first UTF-8 char, stopping at a NUL byte. */ + // Skip over first UTF-8 char, stopping at a NUL byte. len = utf_ptr2len_len(p, size); - /* Check for illegal byte and incomplete byte sequence. */ - if ((len == 1 && p[0] >= 0x80) || len > size) + // Check for illegal byte and incomplete byte sequence. + if ((len == 1 && p[0] >= 0x80) || len > size) { return 1; + } /* * Check for composing characters. We can handle only the first six, but @@ -935,21 +959,24 @@ int utfc_ptr2len_len(const char_u *p, int size) while (len < size) { int len_next_char; - if (p[len] < 0x80) + if (p[len] < 0x80) { break; + } /* * Next character length should not go beyond size to ensure that * UTF_COMPOSINGLIKE(...) does not read beyond size. */ len_next_char = utf_ptr2len_len(p + len, size - len); - if (len_next_char > size - len) + if (len_next_char > size - len) { break; + } - if (!UTF_COMPOSINGLIKE(p + prevlen, p + len)) + if (!UTF_COMPOSINGLIKE(p + prevlen, p + len)) { break; + } - /* Skip over composing char */ + // Skip over composing char prevlen = len; len += len_next_char; } @@ -1043,9 +1070,9 @@ bool utf_printable(int c) * 0xd800-0xdfff is reserved for UTF-16, actually illegal. */ static struct interval nonprint[] = { - {0x070f, 0x070f}, {0x180b, 0x180e}, {0x200b, 0x200f}, {0x202a, 0x202e}, - {0x206a, 0x206f}, {0xd800, 0xdfff}, {0xfeff, 0xfeff}, {0xfff9, 0xfffb}, - {0xfffe, 0xffff} + { 0x070f, 0x070f }, { 0x180b, 0x180e }, { 0x200b, 0x200f }, { 0x202a, 0x202e }, + { 0x206a, 0x206f }, { 0xd800, 0xdfff }, { 0xfeff, 0xfeff }, { 0xfff9, 0xfffb }, + { 0xfffe, 0xffff } }; return !intable(nonprint, ARRAY_SIZE(nonprint), c); @@ -1065,7 +1092,7 @@ int utf_class(const int c) int utf_class_tab(const int c, const uint64_t *const chartab) { - /* sorted list of non-overlapping intervals */ + // sorted list of non-overlapping intervals static struct clinterval { unsigned int first; unsigned int last; @@ -1147,7 +1174,7 @@ int utf_class_tab(const int c, const uint64_t *const chartab) int top = ARRAY_SIZE(classes) - 1; int mid; - /* First quick check for Latin1 characters, use 'iskeyword'. */ + // First quick check for Latin1 characters, use 'iskeyword'. if (c < 0x100) { if (c == ' ' || c == '\t' || c == NUL || c == 0xa0) { return 0; // blank @@ -1158,15 +1185,16 @@ int utf_class_tab(const int c, const uint64_t *const chartab) return 1; // punctuation } - /* binary search in table */ + // binary search in table while (top >= bot) { mid = (bot + top) / 2; - if (classes[mid].last < (unsigned int)c) + if (classes[mid].last < (unsigned int)c) { bot = mid + 1; - else if (classes[mid].first > (unsigned int)c) + } else if (classes[mid].first > (unsigned int)c) { top = mid - 1; - else + } else { return (int)classes[mid].class; + } } // emoji @@ -1174,7 +1202,7 @@ int utf_class_tab(const int c, const uint64_t *const chartab) return 3; } - /* most other characters are "word" characters */ + // most other characters are "word" characters return 2; } @@ -1191,25 +1219,27 @@ bool utf_ambiguous_width(int c) */ static int utf_convert(int a, const convertStruct *const table, size_t n_items) { - size_t start, mid, end; /* indices into table */ + size_t start, mid, end; // indices into table start = 0; end = n_items; while (start < end) { - /* need to search further */ + // need to search further mid = (end + start) / 2; - if (table[mid].rangeEnd < a) + if (table[mid].rangeEnd < a) { start = mid + 1; - else + } else { end = mid; + } } if (start < n_items && table[start].rangeStart <= a && a <= table[start].rangeEnd - && (a - table[start].rangeStart) % table[start].step == 0) + && (a - table[start].rangeStart) % table[start].step == 0) { return a + table[start].offset; - else + } else { return a; + } } /* @@ -1234,21 +1264,24 @@ int utf_fold(int a) /// simple case folding. int mb_toupper(int a) { - /* If 'casemap' contains "keepascii" use ASCII style toupper(). */ - if (a < 128 && (cmp_flags & CMP_KEEPASCII)) + // If 'casemap' contains "keepascii" use ASCII style toupper(). + if (a < 128 && (cmp_flags & CMP_KEEPASCII)) { return TOUPPER_ASC(a); + } #if defined(__STDC_ISO_10646__) - /* If towupper() is available and handles Unicode, use it. */ - if (!(cmp_flags & CMP_INTERNAL)) + // If towupper() is available and handles Unicode, use it. + if (!(cmp_flags & CMP_INTERNAL)) { return towupper(a); + } #endif - /* For characters below 128 use locale sensitive toupper(). */ - if (a < 128) + // For characters below 128 use locale sensitive toupper(). + if (a < 128) { return TOUPPER_LOC(a); + } - /* For any other characters use the above mapping table. */ + // For any other characters use the above mapping table. return utf_convert(a, toUpper, ARRAY_SIZE(toUpper)); } @@ -1262,21 +1295,24 @@ bool mb_islower(int a) /// simple case folding. int mb_tolower(int a) { - /* If 'casemap' contains "keepascii" use ASCII style tolower(). */ - if (a < 128 && (cmp_flags & CMP_KEEPASCII)) + // If 'casemap' contains "keepascii" use ASCII style tolower(). + if (a < 128 && (cmp_flags & CMP_KEEPASCII)) { return TOLOWER_ASC(a); + } #if defined(__STDC_ISO_10646__) - /* If towlower() is available and handles Unicode, use it. */ - if (!(cmp_flags & CMP_INTERNAL)) + // If towlower() is available and handles Unicode, use it. + if (!(cmp_flags & CMP_INTERNAL)) { return towlower(a); + } #endif - /* For characters below 128 use locale sensitive tolower(). */ - if (a < 128) + // For characters below 128 use locale sensitive tolower(). + if (a < 128) { return TOLOWER_LOC(a); + } - /* For any other characters use the above mapping table. */ + // For any other characters use the above mapping table. return utf_convert(a, toLower, ARRAY_SIZE(toLower)); } @@ -1285,8 +1321,7 @@ bool mb_isupper(int a) return mb_tolower(a) != a; } -static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, - size_t n2) +static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, size_t n2) { int c1, c2, cdiff; char_u buffer[6]; @@ -1295,23 +1330,27 @@ static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, c1 = utf_safe_read_char_adv(&s1, &n1); c2 = utf_safe_read_char_adv(&s2, &n2); - if (c1 <= 0 || c2 <= 0) + if (c1 <= 0 || c2 <= 0) { break; + } - if (c1 == c2) + if (c1 == c2) { continue; + } cdiff = utf_fold(c1) - utf_fold(c2); - if (cdiff != 0) + if (cdiff != 0) { return cdiff; + } } - /* some string ended or has an incomplete/illegal character sequence */ + // some string ended or has an incomplete/illegal character sequence if (c1 == 0 || c2 == 0) { - /* some string ended. shorter string is smaller */ - if (c1 == 0 && c2 == 0) + // some string ended. shorter string is smaller + if (c1 == 0 && c2 == 0) { return 0; + } return c1 == 0 ? -1 : 1; } @@ -1332,8 +1371,9 @@ static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, while (n1 > 0 && n2 > 0 && *s1 != NUL && *s2 != NUL) { cdiff = (int)(*s1) - (int)(*s2); - if (cdiff != 0) + if (cdiff != 0) { return cdiff; + } s1++; s2++; @@ -1341,19 +1381,22 @@ static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, n2--; } - if (n1 > 0 && *s1 == NUL) + if (n1 > 0 && *s1 == NUL) { n1 = 0; - if (n2 > 0 && *s2 == NUL) + } + if (n2 > 0 && *s2 == NUL) { n2 = 0; + } - if (n1 == 0 && n2 == 0) + if (n1 == 0 && n2 == 0) { return 0; + } return n1 == 0 ? -1 : 1; } #ifdef WIN32 #ifndef CP_UTF8 -# define CP_UTF8 65001 /* magic number from winnls.h */ +# define CP_UTF8 65001 // magic number from winnls.h #endif /// Converts string from UTF-8 to UTF-16. @@ -1453,8 +1496,7 @@ int utf16_to_utf8(const wchar_t *utf16, int utf16len, char **utf8) /// @param len maximum length (an earlier NUL terminates) /// @param[out] codepoints incremented with UTF-32 code point size /// @param[out] codeunits incremented with UTF-16 code unit size -void mb_utflen(const char_u *s, size_t len, size_t *codepoints, - size_t *codeunits) +void mb_utflen(const char_u *s, size_t len, size_t *codepoints, size_t *codeunits) FUNC_ATTR_NONNULL_ALL { size_t count = 0, extra = 0; @@ -1473,8 +1515,7 @@ void mb_utflen(const char_u *s, size_t len, size_t *codepoints, *codeunits += count + extra; } -ssize_t mb_utf_index_to_bytes(const char_u *s, size_t len, - size_t index, bool use_utf16_units) +ssize_t mb_utf_index_to_bytes(const char_u *s, size_t len, size_t index, bool use_utf16_units) FUNC_ATTR_NONNULL_ALL { size_t count = 0; @@ -1537,7 +1578,7 @@ void show_utf8(void) { int len; int rlen = 0; - char_u *line; + char_u *line; int clen; int i; @@ -1553,7 +1594,7 @@ void show_utf8(void) clen = 0; for (i = 0; i < len; ++i) { if (clen == 0) { - /* start of (composing) character, get its length */ + // start of (composing) character, get its length if (i > 0) { STRCPY(IObuff + rlen, "+ "); rlen += 2; @@ -1561,11 +1602,12 @@ void show_utf8(void) clen = utf_ptr2len(line + i); } sprintf((char *)IObuff + rlen, "%02x ", - (line[i] == NL) ? NUL : line[i]); /* NUL is stored as NL */ + (line[i] == NL) ? NUL : line[i]); // NUL is stored as NL --clen; rlen += (int)STRLEN(IObuff + rlen); - if (rlen > IOSIZE - 20) + if (rlen > IOSIZE - 20) { break; + } } msg(IObuff); @@ -1579,42 +1621,49 @@ int utf_head_off(const char_u *base, const char_u *p) int c; int len; - if (*p < 0x80) /* be quick for ASCII */ + if (*p < 0x80) { // be quick for ASCII return 0; + } /* Skip backwards over trailing bytes: 10xx.xxxx * Skip backwards again if on a composing char. */ const char_u *q; for (q = p;; --q) { - /* Move s to the last byte of this char. */ + // Move s to the last byte of this char. const char_u *s; for (s = q; (s[1] & 0xc0) == 0x80; ++s) {} - /* Move q to the first byte of this char. */ - while (q > base && (*q & 0xc0) == 0x80) + // Move q to the first byte of this char. + while (q > base && (*q & 0xc0) == 0x80) { --q; + } /* Check for illegal sequence. Do allow an illegal byte after where we * started. */ len = utf8len_tab[*q]; - if (len != (int)(s - q + 1) && len != (int)(p - q + 1)) + if (len != (int)(s - q + 1) && len != (int)(p - q + 1)) { return 0; + } - if (q <= base) + if (q <= base) { break; + } c = utf_ptr2char(q); - if (utf_iscomposing(c)) + if (utf_iscomposing(c)) { continue; + } if (arabic_maycombine(c)) { - /* Advance to get a sneak-peak at the next char */ + // Advance to get a sneak-peak at the next char const char_u *j = q; --j; - /* Move j to the first byte of this char. */ - while (j > base && (*j & 0xc0) == 0x80) + // Move j to the first byte of this char. + while (j > base && (*j & 0xc0) == 0x80) { --j; - if (arabic_combine(utf_ptr2char(j), c)) + } + if (arabic_combine(utf_ptr2char(j), c)) { continue; + } } break; } @@ -1627,12 +1676,12 @@ bool utf_eat_space(int cc) FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT { return (cc >= 0x2000 && cc <= 0x206F) // General punctuations - || (cc >= 0x2e00 && cc <= 0x2e7f) // Supplemental punctuations - || (cc >= 0x3000 && cc <= 0x303f) // CJK symbols and punctuations - || (cc >= 0xff01 && cc <= 0xff0f) // Full width ASCII punctuations - || (cc >= 0xff1a && cc <= 0xff20) // .. - || (cc >= 0xff3b && cc <= 0xff40) // .. - || (cc >= 0xff5b && cc <= 0xff65); // .. + || (cc >= 0x2e00 && cc <= 0x2e7f) // Supplemental punctuations + || (cc >= 0x3000 && cc <= 0x303f) // CJK symbols and punctuations + || (cc >= 0xff01 && cc <= 0xff0f) // Full width ASCII punctuations + || (cc >= 0xff1a && cc <= 0xff20) // .. + || (cc >= 0xff3b && cc <= 0xff40) // .. + || (cc >= 0xff5b && cc <= 0xff65); // .. } // Whether line break is allowed before "cc". @@ -1814,8 +1863,9 @@ int mb_tail_off(char_u *base, char_u *p) int i; int j; - if (*p == NUL) + if (*p == NUL) { return 0; + } // Find the last character that is 10xx.xxxx for (i = 0; (p[i + 1] & 0xc0) == 0x80; i++) {} @@ -1839,10 +1889,10 @@ int mb_tail_off(char_u *base, char_u *p) void utf_find_illegal(void) { pos_T pos = curwin->w_cursor; - char_u *p; + char_u *p; int len; vimconv_T vimconv; - char_u *tofree = NULL; + char_u *tofree = NULL; vimconv.vc_type = CONV_NONE; if (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT) { @@ -1858,8 +1908,9 @@ void utf_find_illegal(void) if (vimconv.vc_type != CONV_NONE) { xfree(tofree); tofree = string_convert(&vimconv, p, NULL); - if (tofree == NULL) + if (tofree == NULL) { break; + } p = tofree; } @@ -1868,10 +1919,10 @@ void utf_find_illegal(void) * utf_ptr2len()) or too many of them (overlong sequence). */ len = utf_ptr2len(p); if (*p >= 0x80 && (len == 1 - || utf_char2len(utf_ptr2char(p)) != len)) { - if (vimconv.vc_type == CONV_NONE) + || utf_char2len(utf_ptr2char(p)) != len)) { + if (vimconv.vc_type == CONV_NONE) { curwin->w_cursor.col += (colnr_T)(p - get_cursor_pos_ptr()); - else { + } else { int l; len = (int)(p - tofree); @@ -1884,13 +1935,14 @@ void utf_find_illegal(void) } p += len; } - if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) + if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) { break; + } ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; } - /* didn't find it: don't move and beep */ + // didn't find it: don't move and beep curwin->w_cursor = pos; beep_flush(); @@ -1944,13 +1996,10 @@ void mb_check_adjust_col(void *win_) } } -/* - * Return a pointer to the character before "*p", if there is one. - */ -char_u * mb_prevptr( - char_u *line, /* start of the string */ - char_u *p - ) +/// @param line start of the string +/// +/// @return a pointer to the character before "*p", if there is one. +char_u * mb_prevptr(char_u *line, char_u *p) { if (p > line) { MB_PTR_BACK(line, p); @@ -1964,14 +2013,16 @@ char_u * mb_prevptr( */ int mb_charlen(char_u *str) { - char_u *p = str; + char_u *p = str; int count; - if (p == NULL) + if (p == NULL) { return 0; + } - for (count = 0; *p != NUL; count++) + for (count = 0; *p != NUL; count++) { p += (*mb_ptr2len)(p); + } return count; } @@ -1981,11 +2032,12 @@ int mb_charlen(char_u *str) */ int mb_charlen_len(char_u *str, int len) { - char_u *p = str; + char_u *p = str; int count; - for (count = 0; *p != NUL && p < str + len; count++) + for (count = 0; *p != NUL && p < str + len; count++) { p += (*mb_ptr2len)(p); + } return count; } @@ -2049,10 +2101,12 @@ const char *mb_unescape(const char **const pp) */ char_u * enc_skip(char_u *p) { - if (STRNCMP(p, "2byte-", 6) == 0) + if (STRNCMP(p, "2byte-", 6) == 0) { return p + 6; - if (STRNCMP(p, "8bit-", 5) == 0) + } + if (STRNCMP(p, "8bit-", 5) == 0) { return p + 5; + } return p; } @@ -2064,7 +2118,7 @@ char_u * enc_skip(char_u *p) */ char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET { - char_u *p, *s; + char_u *p, *s; int i; if (STRCMP(enc, "default") == 0) { @@ -2072,47 +2126,51 @@ char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET return vim_strsave(fenc_default); } - /* copy "enc" to allocated memory, with room for two '-' */ + // copy "enc" to allocated memory, with room for two '-' char_u *r = xmalloc(STRLEN(enc) + 3); - /* Make it all lower case and replace '_' with '-'. */ + // Make it all lower case and replace '_' with '-'. p = r; for (s = enc; *s != NUL; ++s) { - if (*s == '_') + if (*s == '_') { *p++ = '-'; - else + } else { *p++ = TOLOWER_ASC(*s); + } } *p = NUL; - /* Skip "2byte-" and "8bit-". */ + // Skip "2byte-" and "8bit-". p = enc_skip(r); - /* Change "microsoft-cp" to "cp". Used in some spell files. */ - if (STRNCMP(p, "microsoft-cp", 12) == 0) + // Change "microsoft-cp" to "cp". Used in some spell files. + if (STRNCMP(p, "microsoft-cp", 12) == 0) { STRMOVE(p, p + 10); + } - /* "iso8859" -> "iso-8859" */ + // "iso8859" -> "iso-8859" if (STRNCMP(p, "iso8859", 7) == 0) { STRMOVE(p + 4, p + 3); p[3] = '-'; } - /* "iso-8859n" -> "iso-8859-n" */ + // "iso-8859n" -> "iso-8859-n" if (STRNCMP(p, "iso-8859", 8) == 0 && p[8] != '-') { STRMOVE(p + 9, p + 8); p[8] = '-'; } - /* "latin-N" -> "latinN" */ - if (STRNCMP(p, "latin-", 6) == 0) + // "latin-N" -> "latinN" + if (STRNCMP(p, "latin-", 6) == 0) { STRMOVE(p + 5, p + 6); + } if (enc_canon_search(p) >= 0) { - /* canonical name can be used unmodified */ - if (p != r) + // canonical name can be used unmodified + if (p != r) { STRMOVE(r, p); + } } else if ((i = enc_alias_search(p)) >= 0) { - /* alias recognized, get canonical name */ + // alias recognized, get canonical name xfree(r); r = vim_strsave((char_u *)enc_canon_table[i].name); } @@ -2127,9 +2185,11 @@ static int enc_alias_search(char_u *name) { int i; - for (i = 0; enc_alias_table[i].name != NULL; ++i) - if (STRCMP(name, enc_alias_table[i].name) == 0) + for (i = 0; enc_alias_table[i].name != NULL; ++i) { + if (STRCMP(name, enc_alias_table[i].name) == 0) { return enc_alias_table[i].canon; + } + } return -1; } @@ -2219,13 +2279,13 @@ void * my_iconv_open(char_u *to, char_u *from) iconv_t fd; #define ICONV_TESTLEN 400 char_u tobuf[ICONV_TESTLEN]; - char *p; + char *p; size_t tolen; static WorkingStatus iconv_working = kUnknown; - if (iconv_working == kBroken) - return (void *)-1; /* detected a broken iconv() previously */ - + if (iconv_working == kBroken) { + return (void *)-1; // detected a broken iconv() previously + } fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from)); if (fd != (iconv_t)-1 && iconv_working == kUnknown) { @@ -2243,8 +2303,9 @@ void * my_iconv_open(char_u *to, char_u *from) iconv_working = kBroken; iconv_close(fd); fd = (iconv_t)-1; - } else + } else { iconv_working = kWorking; + } } return (void *)fd; @@ -2257,17 +2318,17 @@ void * my_iconv_open(char_u *to, char_u *from) * Returns the converted string in allocated memory. NULL for an error. * If resultlenp is not NULL, sets it to the result length in bytes. */ -static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, - size_t slen, size_t *unconvlenp, size_t *resultlenp) +static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen, + size_t *unconvlenp, size_t *resultlenp) { - const char *from; + const char *from; size_t fromlen; - char *to; + char *to; size_t tolen; size_t len = 0; size_t done = 0; - char_u *result = NULL; - char_u *p; + char_u *result = NULL; + char_u *p; int l; from = (char *)str; @@ -2278,8 +2339,9 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, * increase the buffer size. */ len = len + fromlen * 2 + 40; p = xmalloc(len); - if (done > 0) + if (done > 0) { memmove(p, result, done); + } xfree(result); result = p; } @@ -2327,8 +2389,9 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, done = to - (char *)result; } - if (resultlenp != NULL && result != NULL) + if (resultlenp != NULL && result != NULL) { *resultlenp = (size_t)(to - (char *)result); + } return result; } @@ -2353,8 +2416,8 @@ int convert_setup(vimconv_T *vcp, char_u *from, char_u *to) /// As convert_setup(), but only when from_unicode_is_utf8 is true will all /// "from" unicode charsets be considered utf-8. Same for "to". -int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, - char_u *to, bool to_unicode_is_utf8) +int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, char_u *to, + bool to_unicode_is_utf8) { int from_prop; int to_prop; @@ -2369,51 +2432,54 @@ int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, # endif *vcp = (vimconv_T)MBYTE_NONE_CONV; - /* No conversion when one of the names is empty or they are equal. */ + // No conversion when one of the names is empty or they are equal. if (from == NULL || *from == NUL || to == NULL || *to == NUL - || STRCMP(from, to) == 0) + || STRCMP(from, to) == 0) { return OK; + } from_prop = enc_canon_props(from); to_prop = enc_canon_props(to); - if (from_unicode_is_utf8) + if (from_unicode_is_utf8) { from_is_utf8 = from_prop & ENC_UNICODE; - else + } else { from_is_utf8 = from_prop == ENC_UNICODE; - if (to_unicode_is_utf8) + } + if (to_unicode_is_utf8) { to_is_utf8 = to_prop & ENC_UNICODE; - else + } else { to_is_utf8 = to_prop == ENC_UNICODE; + } if ((from_prop & ENC_LATIN1) && to_is_utf8) { - /* Internal latin1 -> utf-8 conversion. */ + // Internal latin1 -> utf-8 conversion. vcp->vc_type = CONV_TO_UTF8; - vcp->vc_factor = 2; /* up to twice as long */ + vcp->vc_factor = 2; // up to twice as long } else if ((from_prop & ENC_LATIN9) && to_is_utf8) { - /* Internal latin9 -> utf-8 conversion. */ + // Internal latin9 -> utf-8 conversion. vcp->vc_type = CONV_9_TO_UTF8; - vcp->vc_factor = 3; /* up to three as long (euro sign) */ + vcp->vc_factor = 3; // up to three as long (euro sign) } else if (from_is_utf8 && (to_prop & ENC_LATIN1)) { - /* Internal utf-8 -> latin1 conversion. */ + // Internal utf-8 -> latin1 conversion. vcp->vc_type = CONV_TO_LATIN1; } else if (from_is_utf8 && (to_prop & ENC_LATIN9)) { - /* Internal utf-8 -> latin9 conversion. */ + // Internal utf-8 -> latin9 conversion. vcp->vc_type = CONV_TO_LATIN9; } # ifdef HAVE_ICONV else { // NOLINT(readability/braces) // Use iconv() for conversion. - vcp->vc_fd = (iconv_t)my_iconv_open( - to_is_utf8 ? (char_u *)"utf-8" : to, - from_is_utf8 ? (char_u *)"utf-8" : from); + vcp->vc_fd = (iconv_t)my_iconv_open(to_is_utf8 ? (char_u *)"utf-8" : to, + from_is_utf8 ? (char_u *)"utf-8" : from); if (vcp->vc_fd != (iconv_t)-1) { vcp->vc_type = CONV_ICONV; - vcp->vc_factor = 4; /* could be longer too... */ + vcp->vc_factor = 4; // could be longer too... } } # endif - if (vcp->vc_type == CONV_NONE) + if (vcp->vc_type == CONV_NONE) { return FAIL; + } return OK; } @@ -2435,129 +2501,153 @@ char_u *string_convert(const vimconv_T *const vcp, char_u *ptr, size_t *lenp) * an incomplete sequence at the end it is not converted and "*unconvlenp" is * set to the number of remaining bytes. */ -char_u * string_convert_ext(const vimconv_T *const vcp, char_u *ptr, - size_t *lenp, size_t *unconvlenp) +char_u * string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp, + size_t *unconvlenp) { - char_u *retval = NULL; - char_u *d; + char_u *retval = NULL; + char_u *d; int l; int c; size_t len; - if (lenp == NULL) + if (lenp == NULL) { len = STRLEN(ptr); - else + } else { len = *lenp; - if (len == 0) + } + if (len == 0) { return vim_strsave((char_u *)""); + } switch (vcp->vc_type) { - case CONV_TO_UTF8: /* latin1 to utf-8 conversion */ - retval = xmalloc(len * 2 + 1); - d = retval; - for (size_t i = 0; i < len; ++i) { - c = ptr[i]; - if (c < 0x80) - *d++ = c; - else { - *d++ = 0xc0 + ((unsigned)c >> 6); - *d++ = 0x80 + (c & 0x3f); - } + case CONV_TO_UTF8: // latin1 to utf-8 conversion + retval = xmalloc(len * 2 + 1); + d = retval; + for (size_t i = 0; i < len; ++i) { + c = ptr[i]; + if (c < 0x80) { + *d++ = c; + } else { + *d++ = 0xc0 + ((unsigned)c >> 6); + *d++ = 0x80 + (c & 0x3f); } - *d = NUL; - if (lenp != NULL) - *lenp = (size_t)(d - retval); - break; + } + *d = NUL; + if (lenp != NULL) { + *lenp = (size_t)(d - retval); + } + break; - case CONV_9_TO_UTF8: /* latin9 to utf-8 conversion */ - retval = xmalloc(len * 3 + 1); - d = retval; - for (size_t i = 0; i < len; ++i) { - c = ptr[i]; - switch (c) { - case 0xa4: c = 0x20ac; break; /* euro */ - case 0xa6: c = 0x0160; break; /* S hat */ - case 0xa8: c = 0x0161; break; /* S -hat */ - case 0xb4: c = 0x017d; break; /* Z hat */ - case 0xb8: c = 0x017e; break; /* Z -hat */ - case 0xbc: c = 0x0152; break; /* OE */ - case 0xbd: c = 0x0153; break; /* oe */ - case 0xbe: c = 0x0178; break; /* Y */ - } - d += utf_char2bytes(c, d); + case CONV_9_TO_UTF8: // latin9 to utf-8 conversion + retval = xmalloc(len * 3 + 1); + d = retval; + for (size_t i = 0; i < len; ++i) { + c = ptr[i]; + switch (c) { + case 0xa4: + c = 0x20ac; break; // euro + case 0xa6: + c = 0x0160; break; // S hat + case 0xa8: + c = 0x0161; break; // S -hat + case 0xb4: + c = 0x017d; break; // Z hat + case 0xb8: + c = 0x017e; break; // Z -hat + case 0xbc: + c = 0x0152; break; // OE + case 0xbd: + c = 0x0153; break; // oe + case 0xbe: + c = 0x0178; break; // Y } - *d = NUL; - if (lenp != NULL) - *lenp = (size_t)(d - retval); - break; + d += utf_char2bytes(c, d); + } + *d = NUL; + if (lenp != NULL) { + *lenp = (size_t)(d - retval); + } + break; - case CONV_TO_LATIN1: /* utf-8 to latin1 conversion */ - case CONV_TO_LATIN9: /* utf-8 to latin9 conversion */ - retval = xmalloc(len + 1); - d = retval; - for (size_t i = 0; i < len; ++i) { - l = utf_ptr2len_len(ptr + i, len - i); - if (l == 0) - *d++ = NUL; - else if (l == 1) { - uint8_t l_w = utf8len_tab_zero[ptr[i]]; + case CONV_TO_LATIN1: // utf-8 to latin1 conversion + case CONV_TO_LATIN9: // utf-8 to latin9 conversion + retval = xmalloc(len + 1); + d = retval; + for (size_t i = 0; i < len; ++i) { + l = utf_ptr2len_len(ptr + i, len - i); + if (l == 0) { + *d++ = NUL; + } else if (l == 1) { + uint8_t l_w = utf8len_tab_zero[ptr[i]]; - if (l_w == 0) { - /* Illegal utf-8 byte cannot be converted */ + if (l_w == 0) { + // Illegal utf-8 byte cannot be converted + xfree(retval); + return NULL; + } + if (unconvlenp != NULL && l_w > len - i) { + // Incomplete sequence at the end. + *unconvlenp = len - i; + break; + } + *d++ = ptr[i]; + } else { + c = utf_ptr2char(ptr + i); + if (vcp->vc_type == CONV_TO_LATIN9) { + switch (c) { + case 0x20ac: + c = 0xa4; break; // euro + case 0x0160: + c = 0xa6; break; // S hat + case 0x0161: + c = 0xa8; break; // S -hat + case 0x017d: + c = 0xb4; break; // Z hat + case 0x017e: + c = 0xb8; break; // Z -hat + case 0x0152: + c = 0xbc; break; // OE + case 0x0153: + c = 0xbd; break; // oe + case 0x0178: + c = 0xbe; break; // Y + case 0xa4: + case 0xa6: + case 0xa8: + case 0xb4: + case 0xb8: + case 0xbc: + case 0xbd: + case 0xbe: + c = 0x100; break; // not in latin9 + } + } + if (!utf_iscomposing(c)) { // skip composing chars + if (c < 0x100) { + *d++ = c; + } else if (vcp->vc_fail) { xfree(retval); return NULL; - } - if (unconvlenp != NULL && l_w > len - i) { - /* Incomplete sequence at the end. */ - *unconvlenp = len - i; - break; - } - *d++ = ptr[i]; - } else { - c = utf_ptr2char(ptr + i); - if (vcp->vc_type == CONV_TO_LATIN9) - switch (c) { - case 0x20ac: c = 0xa4; break; /* euro */ - case 0x0160: c = 0xa6; break; /* S hat */ - case 0x0161: c = 0xa8; break; /* S -hat */ - case 0x017d: c = 0xb4; break; /* Z hat */ - case 0x017e: c = 0xb8; break; /* Z -hat */ - case 0x0152: c = 0xbc; break; /* OE */ - case 0x0153: c = 0xbd; break; /* oe */ - case 0x0178: c = 0xbe; break; /* Y */ - case 0xa4: - case 0xa6: - case 0xa8: - case 0xb4: - case 0xb8: - case 0xbc: - case 0xbd: - case 0xbe: c = 0x100; break; /* not in latin9 */ - } - if (!utf_iscomposing(c)) { /* skip composing chars */ - if (c < 0x100) - *d++ = c; - else if (vcp->vc_fail) { - xfree(retval); - return NULL; - } else { - *d++ = 0xbf; - if (utf_char2cells(c) > 1) - *d++ = '?'; + } else { + *d++ = 0xbf; + if (utf_char2cells(c) > 1) { + *d++ = '?'; } } - i += l - 1; } + i += l - 1; } - *d = NUL; - if (lenp != NULL) - *lenp = (size_t)(d - retval); - break; + } + *d = NUL; + if (lenp != NULL) { + *lenp = (size_t)(d - retval); + } + break; # ifdef HAVE_ICONV - case CONV_ICONV: // conversion with vcp->vc_fd - retval = iconv_string(vcp, ptr, len, unconvlenp, lenp); - break; + case CONV_ICONV: // conversion with vcp->vc_fd + retval = iconv_string(vcp, ptr, len, unconvlenp, lenp); + break; # endif } diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 85897bac12..165629a6e0 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -618,7 +618,7 @@ static void normal_redraw_mode_message(NormalState *s) // If need to redraw, and there is a "keep_msg", redraw before the // delay if (must_redraw && keep_msg != NULL && !emsg_on_display) { - char_u *kmsg; + char_u *kmsg; kmsg = keep_msg; keep_msg = NULL; @@ -1456,7 +1456,7 @@ static void set_vcount_ca(cmdarg_T *cap, bool *set_prevcount) // "gui_yank" is true when yanking text for the clipboard. void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) { - oparg_T *oap = cap->oap; + oparg_T *oap = cap->oap; pos_T old_cursor; bool empty_region_error; int restart_edit_save; @@ -2267,7 +2267,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent) bool in_sep_line; // mouse in vertical separator line int c1, c2; pos_T save_cursor; - win_T *old_curwin = curwin; + win_T *old_curwin = curwin; static pos_T orig_cursor; colnr_T leftcol, rightcol; pos_T end_visual; @@ -2886,7 +2886,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent) * A double click selects a word or a block. */ if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) { - pos_T *pos = NULL; + pos_T *pos = NULL; int gc; if (is_click) { @@ -2961,7 +2961,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent) */ static void find_start_of_word(pos_T *pos) { - char_u *line; + char_u *line; int cclass; int col; @@ -2984,7 +2984,7 @@ static void find_start_of_word(pos_T *pos) */ static void find_end_of_word(pos_T *pos) { - char_u *line; + char_u *line; int cclass; int col; @@ -3418,7 +3418,7 @@ void clear_showcmd(void) } else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum) { snprintf((char *)showcmd_buf, SHOWCMD_BUFLEN, "%" PRId64, (int64_t)lines); } else { - char_u *s, *e; + char_u *s, *e; int l; int bytes = 0; int chars = 0; @@ -3469,7 +3469,7 @@ void clear_showcmd(void) */ bool add_to_showcmd(int c) { - char_u *p; + char_u *p; int i; static int ignore[] = { @@ -3615,10 +3615,10 @@ static void display_showcmd(void) */ void do_check_scrollbind(bool check) { - static win_T *old_curwin = NULL; + static win_T *old_curwin = NULL; static linenr_T old_topline = 0; static int old_topfill = 0; - static buf_T *old_buf = NULL; + static buf_T *old_buf = NULL; static colnr_T old_leftcol = 0; if (check && curwin->w_p_scb) { @@ -3673,8 +3673,8 @@ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) { bool want_ver; bool want_hor; - win_T *old_curwin = curwin; - buf_T *old_curbuf = curbuf; + win_T *old_curwin = curwin; + buf_T *old_curbuf = curbuf; int old_VIsual_select = VIsual_select; int old_VIsual_active = VIsual_active; colnr_T tgt_leftcol = curwin->w_leftcol; @@ -3878,7 +3878,7 @@ static bool is_ident(char_u *line, int offset) /// @return fail when not found. bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_arg) { - char_u *pat; + char_u *pat; pos_T old_pos; pos_T par_pos; pos_T found_pos; @@ -4699,7 +4699,7 @@ dozet: case 'G': // "zG": add good word to temp word list case 'W': // "zW": add wrong word to temp word list { - char_u *ptr = NULL; + char_u *ptr = NULL; size_t len; if (checkclearop(cap->oap)) { @@ -4958,13 +4958,13 @@ void do_nv_ident(int c1, int c2) */ static void nv_ident(cmdarg_T *cap) { - char_u *ptr = NULL; - char_u *p; + char_u *ptr = NULL; + char_u *p; size_t n = 0; // init for GCC int cmdchar; bool g_cmd; // "g" command bool tag_cmd = false; - char_u *aux_ptr; + char_u *aux_ptr; if (cap->cmdchar == 'g') { // "g*", "g#", "g]" and "gCTRL-]" cmdchar = cap->nchar; @@ -5513,7 +5513,7 @@ static void nv_down(cmdarg_T *cap) */ static void nv_gotofile(cmdarg_T *cap) { - char_u *ptr; + char_u *ptr; linenr_T lnum = -1; if (text_locked()) { @@ -5588,7 +5588,7 @@ static void nv_dollar(cmdarg_T *cap) */ static void nv_search(cmdarg_T *cap) { - oparg_T *oap = cap->oap; + oparg_T *oap = cap->oap; pos_T save_cursor = curwin->w_cursor; if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13) { @@ -5719,7 +5719,7 @@ static void nv_brackets(cmdarg_T *cap) { pos_T new_pos = { 0, 0, 0 }; pos_T prev_pos; - pos_T *pos = NULL; // init for GCC + pos_T *pos = NULL; // init for GCC pos_T old_pos; // cursor position before command int flag; long n; @@ -5749,7 +5749,7 @@ static void nv_brackets(cmdarg_T *cap) if (vim_strchr((char_u *) "iI\011dD\004", cap->nchar) != NULL) { - char_u *ptr; + char_u *ptr; size_t len; if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) { @@ -5993,7 +5993,7 @@ static void nv_brackets(cmdarg_T *cap) */ static void nv_percent(cmdarg_T *cap) { - pos_T *pos; + pos_T *pos; linenr_T lnum = curwin->w_cursor.lnum; cap->oap->inclusive = true; @@ -6135,7 +6135,7 @@ static void nv_kundo(cmdarg_T *cap) */ static void nv_replace(cmdarg_T *cap) { - char_u *ptr; + char_u *ptr; int had_ctrl_v; if (checkclearop(cap->oap)) { @@ -6554,7 +6554,7 @@ static void nv_optrans(cmdarg_T *cap) */ static void nv_gomark(cmdarg_T *cap) { - pos_T *pos; + pos_T *pos; int c; pos_T old_cursor = curwin->w_cursor; const bool old_KeyTyped = KeyTyped; // getting file may reset it @@ -6593,7 +6593,7 @@ static void nv_gomark(cmdarg_T *cap) // Handle CTRL-O, CTRL-I, "g;", "g,", and "CTRL-Tab" commands. static void nv_pcmark(cmdarg_T *cap) { - pos_T *pos; + pos_T *pos; linenr_T lnum = curwin->w_cursor.lnum; const bool old_KeyTyped = KeyTyped; // getting file may reset it @@ -6841,7 +6841,7 @@ static void nv_suspend(cmdarg_T *cap) */ static void nv_g_cmd(cmdarg_T *cap) { - oparg_T *oap = cap->oap; + oparg_T *oap = cap->oap; pos_T tpos; int i; bool flag = false; @@ -7076,7 +7076,7 @@ static void nv_g_cmd(cmdarg_T *cap) cap->oap->op_type == OP_NOP) == false) { clearopbeep(cap->oap); } else { - char_u *ptr = get_cursor_line_ptr(); + char_u *ptr = get_cursor_line_ptr(); // In Visual mode we may end up after the line. if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) { @@ -7734,7 +7734,7 @@ static void adjust_for_sel(cmdarg_T *cap) */ static bool unadjust_for_sel(void) { - pos_T *pp; + pos_T *pp; if (*p_sel == 'e' && !equalpos(VIsual, curwin->w_cursor)) { if (lt(VIsual, curwin->w_cursor)) { @@ -8002,7 +8002,7 @@ static void nv_object(cmdarg_T *cap) { bool flag; bool include; - char_u *mps_save; + char_u *mps_save; if (cap->cmdchar == 'i') { include = false; // "ix" = inner object: exclude white space diff --git a/src/nvim/ops.c b/src/nvim/ops.c index b493200005..12c3681089 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -73,7 +73,7 @@ struct block_def { int startspaces; // 'extra' cols before first char int endspaces; // 'extra' cols after last char int textlen; // chars in block - char_u *textstart; // pointer to 1st char (partially) in block + char_u *textstart; // pointer to 1st char (partially) in block colnr_T textcol; // index of chars (partially) in block colnr_T start_vcol; // start col of 1st char wholly inside block colnr_T end_vcol; // start col of 1st char wholly after block @@ -210,7 +210,7 @@ void op_shift(oparg_T *oap, int curs_top, int amount) { long i; int first_char; - char_u *s; + char_u *s; int block_col = 0; if (u_save((linenr_T)(oap->start.lnum - 1), @@ -425,7 +425,7 @@ static void shift_block(oparg_T *oap, int amount) size_t fill; // nr of spaces that replace a TAB size_t new_line_len; // the length of the line after the // block shift - char_u *non_white = bd.textstart; + char_u *non_white = bd.textstart; /* * Firstly, let's find the first non-whitespace character that is @@ -526,7 +526,7 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def int spaces = 0; // non-zero if cutting a TAB colnr_T offset; // pointer along new line size_t s_len = STRLEN(s); - char_u *newp, *oldp; // new, old lines + char_u *newp, *oldp; // new, old lines linenr_T lnum; // loop var int oldstate = State; State = INSERT; // don't want REPLACE for State @@ -632,7 +632,7 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def void op_reindent(oparg_T *oap, Indenter how) { long i; - char_u *l; + char_u *l; int amount; linenr_T first_changed = 0; linenr_T last_changed = 0; @@ -709,7 +709,7 @@ void op_reindent(oparg_T *oap, Indenter how) /* * Keep the last expression line here, for repeating. */ -static char_u *expr_line = NULL; +static char_u *expr_line = NULL; /* * Get an expression for the "\"=expr1" or "CTRL-R =expr1" @@ -717,7 +717,7 @@ static char_u *expr_line = NULL; */ int get_expr_register(void) { - char_u *new_line; + char_u *new_line; new_line = getcmdline('=', 0L, 0, true); if (new_line == NULL) { @@ -747,8 +747,8 @@ void set_expr_line(char_u *new_line) */ char_u *get_expr_line(void) { - char_u *expr_copy; - char_u *rv; + char_u *expr_copy; + char_u *rv; static int nested = 0; if (expr_line == NULL) { @@ -910,9 +910,9 @@ bool yank_register_mline(int regname) */ int do_record(int c) { - char_u *p; + char_u *p; static int regname; - yankreg_T *old_y_previous; + yankreg_T *old_y_previous; int retval; if (reg_recording == 0) { @@ -1152,7 +1152,7 @@ static int put_in_typebuf(char_u *s, bool esc, bool colon, int silent) retval = ins_typebuf((char_u *)"\n", REMAP_NONE, 0, true, silent); } if (retval == OK) { - char_u *p; + char_u *p; if (esc) { p = vim_strsave_escape_csi(s); @@ -1417,8 +1417,8 @@ int op_delete(oparg_T *oap) { int n; linenr_T lnum; - char_u *ptr; - char_u *newp, *oldp; + char_u *ptr; + char_u *newp, *oldp; struct block_def bd = { 0 }; linenr_T old_lcount = curbuf->b_ml.ml_line_count; @@ -1670,7 +1670,7 @@ int op_delete(oparg_T *oap) /* fix up things for virtualedit-delete: * break the tabs which are going to get in our way */ - char_u *curline = get_cursor_line_ptr(); + char_u *curline = get_cursor_line_ptr(); int len = (int)STRLEN(curline); if (oap->end.coladd != 0 @@ -1748,7 +1748,7 @@ setmarks: */ static void mb_adjust_opend(oparg_T *oap) { - char_u *p; + char_u *p; if (oap->inclusive) { p = ml_get(oap->end.lnum); @@ -1788,10 +1788,10 @@ int op_replace(oparg_T *oap, int c) { int n, numc; int num_chars; - char_u *newp, *oldp; + char_u *newp, *oldp; colnr_T oldlen; struct block_def bd; - char_u *after_p = NULL; + char_u *after_p = NULL; int had_ctrl_v_cr = false; if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty) { @@ -2180,7 +2180,7 @@ bool swapchar(int op_type, pos_T *pos) void op_insert(oparg_T *oap, long count1) { long ins_len, pre_textlen = 0; - char_u *firstline, *ins_text; + char_u *firstline, *ins_text; colnr_T ind_pre = 0; struct block_def bd; int i; @@ -2881,7 +2881,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) int delcount; int incr = 0; struct block_def bd; - char_u **y_array = NULL; + char_u **y_array = NULL; long nr_lines = 0; pos_T new_cursor; int indent; @@ -2890,7 +2890,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) int first_indent = TRUE; int lendiff = 0; pos_T old_pos; - char_u *insert_string = NULL; + char_u *insert_string = NULL; bool allocated = false; long cnt; @@ -3762,7 +3762,7 @@ void ex_display(exarg_T *eap) * display alternate file name */ if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int) { - char_u *fname; + char_u *fname; linenr_T dummy; if (buflist_name_nr(0, &fname, &dummy) != FAIL) { @@ -3892,11 +3892,11 @@ char_u *skip_comment(char_u *line, bool process, bool include_space, bool *is_co // return FAIL for failure, OK otherwise int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions, bool setmark) { - char_u *curr = NULL; - char_u *curr_start = NULL; - char_u *cend; - char_u *newp; - char_u *spaces; // number of spaces inserted before a line + char_u *curr = NULL; + char_u *curr_start = NULL; + char_u *cend; + char_u *newp; + char_u *spaces; // number of spaces inserted before a line int endcurr1 = NUL; int endcurr2 = NUL; int currsize = 0; // size of the current line @@ -3904,7 +3904,7 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions linenr_T t; colnr_T col = 0; int ret = OK; - int *comments = NULL; + int *comments = NULL; int remove_comments = (use_formatoptions == TRUE) && has_format_option(FO_REMOVE_COMS); bool prev_was_comment = false; @@ -4099,9 +4099,9 @@ static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, in char_u *leader2_flags) { int idx1 = 0, idx2 = 0; - char_u *p; - char_u *line1; - char_u *line2; + char_u *p; + char_u *line1; + char_u *line2; if (leader1_len == 0) { return leader2_len == 0; @@ -4507,7 +4507,7 @@ void format_lines(linenr_T line_count, int avoid_fex) */ static int ends_in_white(linenr_T lnum) { - char_u *s = ml_get(lnum); + char_u *s = ml_get(lnum); size_t l; if (*s == NUL) { @@ -4527,8 +4527,8 @@ static int ends_in_white(linenr_T lnum) */ static int fmt_check_par(linenr_T lnum, int *leader_len, char_u **leader_flags, int do_comments) { - char_u *flags = NULL; // init for GCC - char_u *ptr; + char_u *flags = NULL; // init for GCC + char_u *ptr; ptr = ml_get(lnum); if (do_comments) { @@ -4609,11 +4609,11 @@ int paragraph_start(linenr_T lnum) static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool is_del) { int incr = 0; - char_u *pend; - char_u *pstart; - char_u *line; - char_u *prev_pstart; - char_u *prev_pend; + char_u *pend; + char_u *pstart; + char_u *line; + char_u *prev_pstart; + char_u *prev_pend; const int lbr_saved = curwin->w_p_lbr; // Avoid a problem with unwanted linebreaks in block mode. @@ -4833,13 +4833,13 @@ void op_addsub(oparg_T *oap, linenr_T Prenum1, bool g_cmd) int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) { int col; - char_u *buf1 = NULL; + char_u *buf1 = NULL; char_u buf2[NUMBUFLEN]; int pre; // 'X' or 'x': hex; '0': octal; 'B' or 'b': bin static bool hexupper = false; // 0xABC uvarnumber_T n; uvarnumber_T oldn; - char_u *ptr; + char_u *ptr; int c; int todel; int firstdigit; @@ -5400,7 +5400,7 @@ void write_reg_contents_lst(int name, char_u **strings, bool must_append, Motion colnr_T block_len) { if (name == '/' || name == '=') { - char_u *s = strings[0]; + char_u *s = strings[0]; if (strings[0] == NULL) { s = (char_u *)""; } else if (strings[1] != NULL) { @@ -5417,7 +5417,7 @@ void write_reg_contents_lst(int name, char_u **strings, bool must_append, Motion return; } - yankreg_T *old_y_previous, *reg; + yankreg_T *old_y_previous, *reg; if (!(reg = init_write_reg(name, &old_y_previous, must_append))) { return; } @@ -5506,7 +5506,7 @@ void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_a return; } - yankreg_T *old_y_previous, *reg; + yankreg_T *old_y_previous, *reg; if (!(reg = init_write_reg(name, &old_y_previous, must_append))) { return; } @@ -5680,7 +5680,7 @@ static varnumber_T line_count_info(char_u *line, varnumber_T *wc, varnumber_T *c /// When "dict" is not NULL store the info there instead of showing it. void cursor_pos_info(dict_T *dict) { - char_u *p; + char_u *p; char_u buf1[50]; char_u buf2[40]; linenr_T lnum; @@ -5762,7 +5762,7 @@ void cursor_pos_info(dict_T *dict) // Do extra processing for VIsual mode. if (l_VIsual_active && lnum >= min_pos.lnum && lnum <= max_pos.lnum) { - char_u *s = NULL; + char_u *s = NULL; long len = 0L; switch (l_VIsual_mode) { @@ -6155,7 +6155,7 @@ static bool get_clipboard(int name, yankreg_T **target, bool quiet) reg->y_array[tv_idx++] = (char_u *)xstrdupnul((const char *)TV_LIST_ITEM_TV(li)->vval.v_string); }); - if (reg->y_size > 0 && strlen((char*)reg->y_array[reg->y_size-1]) == 0) { + if (reg->y_size > 0 && strlen((char *)reg->y_array[reg->y_size-1]) == 0) { // a known-to-be charwise yank might have a final linebreak // but otherwise there is no line after the final newline if (reg->y_type != kMTCharWise) { diff --git a/src/nvim/screen.c b/src/nvim/screen.c index cc0f0feef7..c0b6f002b2 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -741,7 +741,7 @@ bool win_cursorline_standout(const win_T *wp) */ static void win_update(win_T *wp, Providers *providers) { - buf_T *buf = wp->w_buffer; + buf_T *buf = wp->w_buffer; int type; int top_end = 0; /* Below last row of the top area that needs updating. 0 when no top area updating. */ @@ -1999,16 +1999,16 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc long vcol = 0; // virtual column (for tabs) long vcol_sbr = -1; // virtual column after showbreak long vcol_prev = -1; // "vcol" of previous character - char_u *line; // current line - char_u *ptr; // current position in "line" + char_u *line; // current line + char_u *ptr; // current position in "line" int row; // row in the window, excl w_winrow ScreenGrid *grid = &wp->w_grid; // grid specific to the window char_u extra[57]; // sign, line number and 'fdc' must // fit in here int n_extra = 0; // number of extra chars - char_u *p_extra = NULL; // string of extra chars, plus NUL - char_u *p_extra_free = NULL; // p_extra needs to be freed + char_u *p_extra = NULL; // string of extra chars, plus NUL + char_u *p_extra_free = NULL; // p_extra needs to be freed int c_extra = NUL; // extra chars, all the same int c_final = NUL; // final char, mandatory if set int extra_attr = 0; // attributes when n_extra != 0 @@ -2021,7 +2021,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc // saved "extra" items for when draw_state becomes WL_LINE (again) int saved_n_extra = 0; - char_u *saved_p_extra = NULL; + char_u *saved_p_extra = NULL; int saved_c_extra = 0; int saved_c_final = 0; int saved_char_attr = 0; @@ -2090,7 +2090,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc int line_attr_lowprio = 0; // low-priority attribute for the line int line_attr_lowprio_save; matchitem_T *cur; // points to the match list - match_T *shl; // points to search_hl or a match + match_T *shl; // points to search_hl or a match bool shl_flag; // flag to indicate whether search_hl // has been processed or not bool prevcol_hl_flag; // flag to indicate whether prevcol @@ -2502,7 +2502,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc v = wp->w_leftcol; } if (v > 0 && !number_only) { - char_u *prev_ptr = ptr; + char_u *prev_ptr = ptr; while (vcol < v && *ptr != NUL) { c = win_lbr_chartabsize(wp, line, ptr, (colnr_T)vcol, NULL); vcol += c; @@ -4802,7 +4802,7 @@ static void grid_put_linebuf(ScreenGrid *grid, int row, int coloff, int endcol, */ void rl_mirror(char_u *str) { - char_u *p1, *p2; + char_u *p1, *p2; int t; for (p1 = str, p2 = str + STRLEN(str) - 1; p1 < p2; ++p1, --p2) { @@ -4953,19 +4953,19 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, in { #define L_MATCH(m) (showtail ? sm_gettail(matches[m], false) : matches[m]) int row; - char_u *buf; + char_u *buf; int len; int clen; // length in screen cells int fillchar; int attr; int i; bool highlight = true; - char_u *selstart = NULL; + char_u *selstart = NULL; int selstart_col = 0; - char_u *selend = NULL; + char_u *selend = NULL; static int first_match = 0; bool add_left = false; - char_u *s; + char_u *s; int emenu; int l; @@ -5135,7 +5135,7 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, in static void win_redr_status(win_T *wp) { int row; - char_u *p; + char_u *p; int len; int fillchar; int attr; @@ -5283,7 +5283,7 @@ static void redraw_custom_statusline(win_T *wp) /// line of the window right of it. If not, then it's a vertical separator. bool stl_connected(win_T *wp) { - frame_T *fr; + frame_T *fr; fr = wp->w_frame; while (fr->fr_parent != NULL) { @@ -5309,16 +5309,16 @@ bool stl_connected(win_T *wp) /// @param len length of buffer bool get_keymap_str(win_T *wp, char_u *fmt, char_u *buf, int len) { - char_u *p; + char_u *p; if (wp->w_buffer->b_p_iminsert != B_IMODE_LMAP) { return false; } { - buf_T *old_curbuf = curbuf; - win_T *old_curwin = curwin; - char_u *s; + buf_T *old_curbuf = curbuf; + win_T *old_curwin = curwin; + char_u *s; curbuf = wp->w_buffer; curwin = wp; @@ -5360,12 +5360,12 @@ static void win_redr_custom(win_T *wp, bool draw_ruler) int len; int fillchar; char_u buf[MAXPATHL]; - char_u *stl; - char_u *p; + char_u *stl; + char_u *p; stl_hlrec_t *hltab; StlClickRecord *tabtab; int use_sandbox = false; - win_T *ewp; + win_T *ewp; int p_crb_save; ScreenGrid *grid = &default_grid; @@ -5734,7 +5734,7 @@ void grid_put_schar(ScreenGrid *grid, int row, int col, char_u *schar, int attr) void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col, int attr) { unsigned off; - char_u *ptr = text; + char_u *ptr = text; int len = textlen; int c; unsigned max_off; @@ -5962,7 +5962,7 @@ static void prepare_search_hl(win_T *wp, linenr_T lnum) FUNC_ATTR_NONNULL_ALL { matchitem_T *cur; // points to the match list - match_T *shl; // points to search_hl or a match + match_T *shl; // points to search_hl or a match bool shl_flag; // flag to indicate whether search_hl // has been processed or not @@ -6077,7 +6077,7 @@ static void next_search_hl(win_T *win, match_T *shl, linenr_T lnum, colnr_T minc } else if (vim_strchr(p_cpo, CPO_SEARCH) == NULL || (shl->rm.endpos[0].lnum == 0 && shl->rm.endpos[0].col <= shl->rm.startpos[0].col)) { - char_u *ml; + char_u *ml; matchcol = shl->rm.startpos[0].col; ml = ml_get_buf(shl->buf, lnum, false) + matchcol; @@ -7082,15 +7082,15 @@ void draw_tabline(void) int col = 0; int scol = 0; int attr; - win_T *wp; - win_T *cwp; + win_T *wp; + win_T *cwp; int wincount; int modified; int c; int len; int attr_nosel = HL_ATTR(HLF_TP); int attr_fill = HL_ATTR(HLF_TPF); - char_u *p; + char_u *p; int room; int use_sep_chars = (t_colors < 8 ); diff --git a/src/nvim/search.c b/src/nvim/search.c index b0ee41b245..4be2402f1d 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -7,13 +7,11 @@ #include #include +#include // for INT_MAX on MSVC #include #include -#include /* for INT_MAX on MSVC */ #include "nvim/ascii.h" -#include "nvim/vim.h" -#include "nvim/search.h" #include "nvim/buffer.h" #include "nvim/charset.h" #include "nvim/cursor.h" @@ -34,17 +32,19 @@ #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/move.h" #include "nvim/mouse.h" +#include "nvim/move.h" #include "nvim/normal.h" #include "nvim/option.h" +#include "nvim/os/time.h" #include "nvim/path.h" #include "nvim/regexp.h" #include "nvim/screen.h" +#include "nvim/search.h" #include "nvim/strings.h" #include "nvim/ui.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/os/time.h" #ifdef INCLUDE_GENERATED_DECLARATIONS # include "search.c.generated.h" @@ -79,12 +79,12 @@ static struct spat spats[2] = { // Last used search pattern - [0] = {NULL, true, false, 0, {'/', false, false, 0L}, NULL}, + [0] = { NULL, true, false, 0, { '/', false, false, 0L }, NULL }, // Last used substitute pattern - [1] = {NULL, true, false, 0, {'/', false, false, 0L}, NULL} + [1] = { NULL, true, false, 0, { '/', false, false, 0L }, NULL } }; -static int last_idx = 0; /* index in spats[] for RE_LAST */ +static int last_idx = 0; // index in spats[] for RE_LAST static char_u lastc[2] = { NUL, NUL }; // last character searched for static Direction lastcdir = FORWARD; // last direction of character search @@ -97,7 +97,7 @@ static struct spat saved_spats[2]; static int saved_spats_last_idx = 0; static bool saved_spats_no_hlsearch = false; -static char_u *mr_pattern = NULL; // pattern used by search_regcomp() +static char_u *mr_pattern = NULL; // pattern used by search_regcomp() static bool mr_pattern_alloced = false; // mr_pattern was allocated /* @@ -105,34 +105,27 @@ static bool mr_pattern_alloced = false; // mr_pattern was allocated * been searched already. */ typedef struct SearchedFile { - FILE *fp; /* File pointer */ - char_u *name; /* Full name of file */ - linenr_T lnum; /* Line we were up to in file */ - int matched; /* Found a match in this file */ + FILE *fp; // File pointer + char_u *name; // Full name of file + linenr_T lnum; // Line we were up to in file + int matched; // Found a match in this file } SearchedFile; -/* - * translate search pattern for vim_regcomp() - * - * pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd) - * pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command) - * pat_save == RE_BOTH: save pat in both patterns (:global command) - * pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL - * pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL - * pat_use == RE_LAST: use last used pattern if "pat" is NULL - * options & SEARCH_HIS: put search string in history - * options & SEARCH_KEEP: keep previous search pattern - * - * returns FAIL if failed, OK otherwise. - */ -int -search_regcomp( - char_u *pat, - int pat_save, - int pat_use, - int options, - regmmatch_T *regmatch /* return: pattern and ignore-case flag */ -) +/// translate search pattern for vim_regcomp() +/// +/// pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd) +/// pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command) +/// pat_save == RE_BOTH: save pat in both patterns (:global command) +/// pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL +/// pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL +/// pat_use == RE_LAST: use last used pattern if "pat" is NULL +/// options & SEARCH_HIS: put search string in history +/// options & SEARCH_KEEP: keep previous search pattern +/// +/// @param regmatch return: pattern and ignore-case flag +/// +/// @return FAIL if failed, OK otherwise. +int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatch_T *regmatch) { int magic; int i; @@ -144,15 +137,17 @@ search_regcomp( * If no pattern given, use a previously defined pattern. */ if (pat == NULL || *pat == NUL) { - if (pat_use == RE_LAST) + if (pat_use == RE_LAST) { i = last_idx; - else + } else { i = pat_use; - if (spats[i].pat == NULL) { /* pattern was never defined */ - if (pat_use == RE_SUBST) + } + if (spats[i].pat == NULL) { // pattern was never defined + if (pat_use == RE_SUBST) { EMSG(_(e_nopresub)); - else + } else { EMSG(_(e_noprevre)); + } rc_did_emsg = true; return FAIL; } @@ -180,19 +175,22 @@ search_regcomp( * unless the pattern should not be remembered. */ if (!(options & SEARCH_KEEP) && !cmdmod.keeppatterns) { - /* search or global command */ - if (pat_save == RE_SEARCH || pat_save == RE_BOTH) + // search or global command + if (pat_save == RE_SEARCH || pat_save == RE_BOTH) { save_re_pat(RE_SEARCH, pat, magic); - /* substitute or global command */ - if (pat_save == RE_SUBST || pat_save == RE_BOTH) + } + // substitute or global command + if (pat_save == RE_SUBST || pat_save == RE_BOTH) { save_re_pat(RE_SUBST, pat, magic); + } } regmatch->rmm_ic = ignorecase(pat); regmatch->rmm_maxcol = 0; regmatch->regprog = vim_regcomp(pat, magic ? RE_MAGIC : 0); - if (regmatch->regprog == NULL) + if (regmatch->regprog == NULL) { return FAIL; + } return OK; } @@ -239,9 +237,10 @@ void save_re_pat(int idx, char_u *pat, int magic) spats[idx].timestamp = os_time(); spats[idx].additional_data = NULL; last_idx = idx; - /* If 'hlsearch' set and search pat changed: need redraw. */ - if (p_hls) + // If 'hlsearch' set and search pat changed: need redraw. + if (p_hls) { redraw_all_later(SOME_VALID); + } set_no_hlsearch(false); } } @@ -256,11 +255,13 @@ void save_search_patterns(void) { if (save_level++ == 0) { saved_spats[0] = spats[0]; - if (spats[0].pat != NULL) + if (spats[0].pat != NULL) { saved_spats[0].pat = vim_strsave(spats[0].pat); + } saved_spats[1] = spats[1]; - if (spats[1].pat != NULL) + if (spats[1].pat != NULL) { saved_spats[1].pat = vim_strsave(spats[1].pat); + } saved_spats_last_idx = last_idx; saved_spats_no_hlsearch = no_hlsearch; } @@ -369,8 +370,8 @@ int ignorecase_opt(char_u *pat, int ic_in, int scs) { int ic = ic_in; if (ic && !no_smartcase && scs - && !(ctrl_x_mode_not_default() && curbuf->b_p_inf) - ) { + && !(ctrl_x_mode_not_default() && + curbuf->b_p_inf)) { ic = !pat_has_uppercase(pat); } no_smartcase = false; @@ -431,10 +432,11 @@ void set_last_csearch(int c, char_u *s, int len) { *lastc = c; lastc_bytelen = len; - if (len) + if (len) { memcpy(lastc_bytes, s, len); - else + } else { memset(lastc_bytes, 0, sizeof(lastc_bytes)); + } } void set_csearch_direction(Direction cdir) @@ -468,11 +470,12 @@ void reset_search_dir(void) void set_last_search_pat(const char_u *s, int idx, int magic, int setlast) { free_spat(&spats[idx]); - /* An empty string means that nothing should be matched. */ - if (*s == NUL) + // An empty string means that nothing should be matched. + if (*s == NUL) { spats[idx].pat = NULL; - else - spats[idx].pat = (char_u *) xstrdup((char *) s); + } else { + spats[idx].pat = (char_u *)xstrdup((char *)s); + } spats[idx].timestamp = os_time(); spats[idx].additional_data = NULL; spats[idx].magic = magic; @@ -482,20 +485,23 @@ void set_last_search_pat(const char_u *s, int idx, int magic, int setlast) spats[idx].off.line = FALSE; spats[idx].off.end = FALSE; spats[idx].off.off = 0; - if (setlast) + if (setlast) { last_idx = idx; + } if (save_level) { free_spat(&saved_spats[idx]); saved_spats[idx] = spats[0]; - if (spats[idx].pat == NULL) + if (spats[idx].pat == NULL) { saved_spats[idx].pat = NULL; - else + } else { saved_spats[idx].pat = vim_strsave(spats[idx].pat); + } saved_spats_last_idx = last_idx; } - /* If 'hlsearch' set and search pat changed: need redraw. */ - if (p_hls && idx == last_idx && !no_hlsearch) + // If 'hlsearch' set and search pat changed: need redraw. + if (p_hls && idx == last_idx && !no_hlsearch) { redraw_all_later(SOME_VALID); + } } /* @@ -509,7 +515,7 @@ void last_pat_prog(regmmatch_T *regmatch) regmatch->regprog = NULL; return; } - ++emsg_off; /* So it doesn't beep if bad expr */ + ++emsg_off; // So it doesn't beep if bad expr (void)search_regcomp((char_u *)"", 0, last_idx, SEARCH_KEEP, regmatch); --emsg_off; } @@ -529,27 +535,21 @@ void last_pat_prog(regmmatch_T *regmatch) /// if (options & SEARCH_PEEK) check for typed char, cancel search /// if (options & SEARCH_COL) start at pos->col instead of zero /// -/// @returns FAIL (zero) for failure, non-zero for success. -/// the index of the first matching -/// subpattern plus one; one if there was none. -int searchit( - win_T *win, // window to search in; can be NULL for a - // buffer without a window! - buf_T *buf, - pos_T *pos, - pos_T *end_pos, // set to end of the match, unless NULL - Direction dir, - char_u *pat, - long count, - int options, - int pat_use, // which pattern to use when "pat" is empty - searchit_arg_T *extra_arg // optional extra arguments, can be NULL -) +/// @param win window to search in; can be NULL for a buffer without a window! +/// @param end_pos set to end of the match, unless NULL +/// @param pat_use which pattern to use when "pat" is empty +/// @param extra_arg optional extra arguments, can be NULL +/// +/// @returns FAIL (zero) for failure, non-zero for success. +/// the index of the first matching +/// subpattern plus one; one if there was none. +int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, char_u *pat, + long count, int options, int pat_use, searchit_arg_T *extra_arg) { int found; - linenr_T lnum; /* no init to shut up Apollo cc */ + linenr_T lnum; // no init to shut up Apollo cc regmmatch_T regmatch; - char_u *ptr; + char_u *ptr; colnr_T matchcol; lpos_T endpos; lpos_T matchpos; @@ -569,15 +569,16 @@ int searchit( int *timed_out = NULL; // set when timed out or NULL if (extra_arg != NULL) { - stop_lnum = extra_arg->sa_stop_lnum; - tm = extra_arg->sa_tm; - timed_out = &extra_arg->sa_timed_out; + stop_lnum = extra_arg->sa_stop_lnum; + tm = extra_arg->sa_tm; + timed_out = &extra_arg->sa_timed_out; } if (search_regcomp(pat, RE_SEARCH, pat_use, - (options & (SEARCH_HIS + SEARCH_KEEP)), ®match) == FAIL) { - if ((options & SEARCH_MSG) && !rc_did_emsg) + (options & (SEARCH_HIS + SEARCH_KEEP)), ®match) == FAIL) { + if ((options & SEARCH_MSG) && !rc_did_emsg) { EMSG2(_("E383: Invalid search string: %s"), mr_pattern); + } return FAIL; } @@ -585,7 +586,7 @@ int searchit( * find the string */ called_emsg = FALSE; - do { /* loop for count */ + do { // loop for count // When not accepting a match at the start position set "extra_col" to a // non-zero value. Don't do that when starting at MAXCOL, since MAXCOL + 1 // is zero. @@ -610,13 +611,13 @@ int searchit( extra_col = (options & SEARCH_START) ? start_char_len : 0; } - start_pos = *pos; /* remember start pos for detecting no match */ - found = 0; /* default: not found */ - at_first_line = TRUE; /* default: start in first line */ - if (pos->lnum == 0) { /* correct lnum for when starting in line 0 */ + start_pos = *pos; // remember start pos for detecting no match + found = 0; // default: not found + at_first_line = TRUE; // default: start in first line + if (pos->lnum == 0) { // correct lnum for when starting in line 0 pos->lnum = 1; pos->col = 0; - at_first_line = FALSE; /* not in first line now */ + at_first_line = FALSE; // not in first line now } /* @@ -630,19 +631,22 @@ int searchit( && (options & SEARCH_START) == 0) { lnum = pos->lnum - 1; at_first_line = FALSE; - } else + } else { lnum = pos->lnum; + } - for (loop = 0; loop <= 1; ++loop) { /* loop twice if 'wrapscan' set */ + for (loop = 0; loop <= 1; ++loop) { // loop twice if 'wrapscan' set for (; lnum > 0 && lnum <= buf->b_ml.ml_line_count; lnum += dir, at_first_line = FALSE) { - /* Stop after checking "stop_lnum", if it's set. */ + // Stop after checking "stop_lnum", if it's set. if (stop_lnum != 0 && (dir == FORWARD - ? lnum > stop_lnum : lnum < stop_lnum)) + ? lnum > stop_lnum : lnum < stop_lnum)) { break; - /* Stop after passing the "tm" time limit. */ - if (tm != NULL && profile_passed_limit(*tm)) + } + // Stop after passing the "tm" time limit. + if (tm != NULL && profile_passed_limit(*tm)) { break; + } // Look for a match somewhere in line "lnum". colnr_T col = at_first_line && (options & SEARCH_COL) ? pos->col : 0; @@ -657,7 +661,7 @@ int searchit( break; } if (nmatched > 0) { - /* match may actually be in another line when using \zs */ + // match may actually be in another line when using \zs matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; submatch = first_submatch(®match); @@ -740,8 +744,9 @@ int searchit( // have made it invalid. ptr = ml_get_buf(buf, lnum, false); } - if (!match_ok) + if (!match_ok) { continue; + } } if (dir == BACKWARD) { /* @@ -775,8 +780,9 @@ int searchit( matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; submatch = first_submatch(®match); - } else + } else { break; + } // We found a valid match, now check if there is // another one after it. @@ -804,16 +810,16 @@ int searchit( } } if (ptr[matchcol] == NUL - || (nmatched = vim_regexec_multi( - ®match, win, buf, lnum + matchpos.lnum, matchcol, - tm, timed_out)) == 0) { - // If the search timed out, we did find a match - // but it might be the wrong one, so that's not - // OK. - if (tm != NULL && profile_passed_limit(*tm)) { - match_ok = false; - } - break; + || (nmatched = + vim_regexec_multi(®match, win, buf, lnum + matchpos.lnum, matchcol, + tm, timed_out)) == 0) { + // If the search timed out, we did find a match + // but it might be the wrong one, so that's not + // OK. + if (tm != NULL && profile_passed_limit(*tm)) { + match_ok = false; + } + break; } // vim_regexec_multi() may clear "regprog" if (regmatch.regprog == NULL) { @@ -828,8 +834,9 @@ int searchit( * If there is only a match after the cursor, skip * this match. */ - if (!match_ok) + if (!match_ok) { continue; + } } /* With the SEARCH_END option move to the last character @@ -873,14 +880,15 @@ int searchit( found = 1; first_match = false; - /* Set variables used for 'incsearch' highlighting. */ + // Set variables used for 'incsearch' highlighting. search_match_lines = endpos.lnum - matchpos.lnum; search_match_endcol = endpos.col; break; } - line_breakcheck(); /* stop if ctrl-C typed */ - if (got_int) + line_breakcheck(); // stop if ctrl-C typed + if (got_int) { break; + } /* Cancel searching if a character was typed. Used for * 'incsearch'. Don't check too often, that would slowdown @@ -892,8 +900,9 @@ int searchit( break; } - if (loop && lnum == start_pos.lnum) - break; /* if second loop, stop where started */ + if (loop && lnum == start_pos.lnum) { + break; // if second loop, stop where started + } } at_first_line = FALSE; @@ -933,8 +942,7 @@ int searchit( } if (got_int || called_emsg || (timed_out != NULL && *timed_out) - || break_loop - ) { + || break_loop) { break; } } while (--count > 0 && found); // stop after count matches or no match @@ -943,23 +951,24 @@ int searchit( called_emsg |= save_called_emsg; - if (!found) { /* did not find it */ - if (got_int) + if (!found) { // did not find it + if (got_int) { EMSG(_(e_interr)); - else if ((options & SEARCH_MSG) == SEARCH_MSG) { - if (p_ws) + } else if ((options & SEARCH_MSG) == SEARCH_MSG) { + if (p_ws) { EMSG2(_(e_patnotf2), mr_pattern); - else if (lnum == 0) + } else if (lnum == 0) { EMSG2(_("E384: search hit TOP without match for: %s"), - mr_pattern); - else + mr_pattern); + } else { EMSG2(_("E385: search hit BOTTOM without match for: %s"), - mr_pattern); + mr_pattern); + } } return FAIL; } - /* A pattern like "\n\zs" may go past the last line. */ + // A pattern like "\n\zs" may go past the last line. if (pos->lnum > buf->b_ml.ml_line_count) { pos->lnum = buf->b_ml.ml_line_count; pos->col = (int)STRLEN(ml_get_buf(buf, pos->lnum, false)); @@ -988,8 +997,9 @@ static int first_submatch(regmmatch_T *rp) int submatch; for (submatch = 1;; ++submatch) { - if (rp->startpos[submatch].lnum >= 0) + if (rp->startpos[submatch].lnum >= 0) { break; + } if (submatch == 9) { submatch = 0; break; @@ -998,47 +1008,44 @@ static int first_submatch(regmmatch_T *rp) return submatch; } -/* - * Highest level string search function. - * Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc' - * If 'dirc' is 0: use previous dir. - * If 'pat' is NULL or empty : use previous string. - * If 'options & SEARCH_REV' : go in reverse of previous dir. - * If 'options & SEARCH_ECHO': echo the search command and handle options - * If 'options & SEARCH_MSG' : may give error message - * If 'options & SEARCH_OPT' : interpret optional flags - * If 'options & SEARCH_HIS' : put search pattern in history - * If 'options & SEARCH_NOOF': don't add offset to position - * If 'options & SEARCH_MARK': set previous context mark - * If 'options & SEARCH_KEEP': keep previous search pattern - * If 'options & SEARCH_START': accept match at curpos itself - * If 'options & SEARCH_PEEK': check for typed char, cancel search - * - * Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this - * makes the movement linewise without moving the match position. - * - * Return 0 for failure, 1 for found, 2 for found and line offset added. - */ -int do_search( - oparg_T *oap, // can be NULL - int dirc, // '/' or '?' - int search_delim, // delimiter for search, e.g. '%' in s%regex%replacement - char_u *pat, - long count, - int options, - searchit_arg_T *sia // optional arguments or NULL -) +/// Highest level string search function. +/// Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc' +/// +/// Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this +/// makes the movement linewise without moving the match position. +/// +/// @param dirc if 0: use previous dir. +/// @param pat NULL or empty : use previous string. +/// @param options if TRUE and +/// SEARCH_REV == TRUE : go in reverse of previous dir. +/// SEARCH_ECHO == TRUE : echo the search command and handle options +/// SEARCH_MSG == TRUE : may give error message +/// SEARCH_OPT == TRUE : interpret optional flags +/// SEARCH_HIS == TRUE : put search pattern in history +/// SEARCH_NOOF == TRUE : don't add offset to position +/// SEARCH_MARK == TRUE : set previous context mark +/// SEARCH_KEEP == TRUE : keep previous search pattern +/// SEARCH_START == TRUE : accept match at curpos itself +/// SEARCH_PEEK == TRUE : check for typed char, cancel search +/// @param oap can be NULL +/// @param dirc '/' or '?' +/// @param search_delim delimiter for search, e.g. '%' in s%regex%replacement +/// @param sia optional arguments or NULL +/// +/// @return 0 for failure, 1 for found, 2 for found and line offset added. +int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, int options, + searchit_arg_T *sia) { - pos_T pos; /* position of the last match */ - char_u *searchstr; + pos_T pos; // position of the last match + char_u *searchstr; struct soffset old_off; - int retval; /* Return value */ - char_u *p; + int retval; // Return value + char_u *p; long c; - char_u *dircp; - char_u *strcopy = NULL; - char_u *ps; - char_u *msgbuf = NULL; + char_u *dircp; + char_u *strcopy = NULL; + char_u *ps; + char_u *msgbuf = NULL; size_t len; bool has_offset = false; @@ -1056,32 +1063,35 @@ int do_search( */ old_off = spats[0].off; - pos = curwin->w_cursor; /* start searching at the cursor position */ + pos = curwin->w_cursor; // start searching at the cursor position /* * Find out the direction of the search. */ - if (dirc == 0) + if (dirc == 0) { dirc = spats[0].off.dir; - else { + } else { spats[0].off.dir = dirc; set_vv_searchforward(); } if (options & SEARCH_REV) { - if (dirc == '/') + if (dirc == '/') { dirc = '?'; - else + } else { dirc = '/'; + } } /* If the cursor is in a closed fold, don't find another match in the same * fold. */ if (dirc == '/') { - if (hasFolding(pos.lnum, NULL, &pos.lnum)) - pos.col = MAXCOL - 2; /* avoid overflow when adding 1 */ + if (hasFolding(pos.lnum, NULL, &pos.lnum)) { + pos.col = MAXCOL - 2; // avoid overflow when adding 1 + } } else { - if (hasFolding(pos.lnum, &pos.lnum, NULL)) + if (hasFolding(pos.lnum, &pos.lnum, NULL)) { pos.col = 0; + } } /* @@ -1110,12 +1120,12 @@ int do_search( goto end_do_search; } } else { - /* make search_regcomp() use spats[RE_SEARCH].pat */ + // make search_regcomp() use spats[RE_SEARCH].pat searchstr = (char_u *)""; } } - if (pat != NULL && *pat != NUL) { /* look for (new) offset */ + if (pat != NULL && *pat != NUL) { // look for (new) offset /* * Find end of regular expression. * If there is a matching '/' or '?', toss it. @@ -1123,7 +1133,7 @@ int do_search( ps = strcopy; p = skip_regexp(pat, search_delim, p_magic, &strcopy); if (strcopy != ps) { - /* made a copy of "pat" to change "\?" to "?" */ + // made a copy of "pat" to change "\?" to "?" searchcmdlen += (int)(STRLEN(pat) - STRLEN(strcopy)); pat = strcopy; searchstr = strcopy; @@ -1148,28 +1158,30 @@ int do_search( } p++; } - if (ascii_isdigit(*p) || *p == '+' || *p == '-') { /* got an offset */ - /* 'nr' or '+nr' or '-nr' */ - if (ascii_isdigit(*p) || ascii_isdigit(*(p + 1))) + if (ascii_isdigit(*p) || *p == '+' || *p == '-') { // got an offset + // 'nr' or '+nr' or '-nr' + if (ascii_isdigit(*p) || ascii_isdigit(*(p + 1))) { spats[0].off.off = atol((char *)p); - else if (*p == '-') /* single '-' */ + } else if (*p == '-') { // single '-' spats[0].off.off = -1; - else /* single '+' */ + } else { // single '+' spats[0].off.off = 1; + } ++p; - while (ascii_isdigit(*p)) /* skip number */ + while (ascii_isdigit(*p)) { // skip number ++p; + } } - /* compute length of search command for get_address() */ + // compute length of search command for get_address() searchcmdlen += (int)(p - pat); - pat = p; /* put pat after search command */ + pat = p; // put pat after search command } if ((options & SEARCH_ECHO) && messaging() && !msg_silent && (!cmd_silent || !shortmess(SHM_SEARCHCOUNT))) { - char_u *trunc; + char_u *trunc; char_u off_buf[40]; size_t off_len = 0; @@ -1291,18 +1303,22 @@ int do_search( */ if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2) { if (spats[0].off.off > 0) { - for (c = spats[0].off.off; c; --c) - if (decl(&pos) == -1) + for (c = spats[0].off.off; c; --c) { + if (decl(&pos) == -1) { break; - if (c) { /* at start of buffer */ - pos.lnum = 0; /* allow lnum == 0 here */ + } + } + if (c) { // at start of buffer + pos.lnum = 0; // allow lnum == 0 here pos.col = MAXCOL; } } else { - for (c = spats[0].off.off; c; ++c) - if (incl(&pos) == -1) + for (c = spats[0].off.off; c; ++c) { + if (incl(&pos) == -1) { break; - if (c) { /* at end of buffer */ + } + } + if (c) { // at end of buffer pos.lnum = curbuf->b_ml.ml_line_count + 1; pos.col = 0; } @@ -1332,10 +1348,10 @@ int do_search( retval = 0; goto end_do_search; } - if (spats[0].off.end && oap != NULL) - oap->inclusive = true; /* 'e' includes last character */ - - retval = 1; /* pattern found */ + if (spats[0].off.end && oap != NULL) { + oap->inclusive = true; // 'e' includes last character + } + retval = 1; // pattern found /* * Add character and/or line offset @@ -1345,28 +1361,33 @@ int do_search( if (spats[0].off.line) { // Add the offset to the line number. c = pos.lnum + spats[0].off.off; - if (c < 1) + if (c < 1) { pos.lnum = 1; - else if (c > curbuf->b_ml.ml_line_count) + } else if (c > curbuf->b_ml.ml_line_count) { pos.lnum = curbuf->b_ml.ml_line_count; - else + } else { pos.lnum = c; + } pos.col = 0; - retval = 2; /* pattern found, line offset added */ - } else if (pos.col < MAXCOL - 2) { /* just in case */ - /* to the right, check for end of file */ + retval = 2; // pattern found, line offset added + } else if (pos.col < MAXCOL - 2) { // just in case + // to the right, check for end of file c = spats[0].off.off; if (c > 0) { - while (c-- > 0) - if (incl(&pos) == -1) + while (c-- > 0) { + if (incl(&pos) == -1) { break; + } + } } - /* to the left, check for start of file */ + // to the left, check for start of file else { - while (c++ < 0) - if (decl(&pos) == -1) + while (c++ < 0) { + if (decl(&pos) == -1) { break; + } + } } } if (!equalpos(pos, org_pos)) { @@ -1411,14 +1432,16 @@ int do_search( ++pat; } - if (options & SEARCH_MARK) + if (options & SEARCH_MARK) { setpcmark(); + } curwin->w_cursor = pos; curwin->w_set_curswant = TRUE; end_do_search: - if ((options & SEARCH_KEEP) || cmdmod.keeppatterns) + if ((options & SEARCH_KEEP) || cmdmod.keeppatterns) { spats[0].off = old_off; + } xfree(msgbuf); return retval; @@ -1436,18 +1459,20 @@ end_do_search: int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) { linenr_T start = 0; - char_u *ptr; - char_u *p; + char_u *ptr; + char_u *p; - if (buf->b_ml.ml_line_count == 0) + if (buf->b_ml.ml_line_count == 0) { return FAIL; + } for (;; ) { pos->lnum += dir; if (pos->lnum < 1) { if (p_ws) { pos->lnum = buf->b_ml.ml_line_count; - if (!shortmess(SHM_SEARCH)) + if (!shortmess(SHM_SEARCH)) { give_warning((char_u *)_(top_bot_msg), true); + } } else { pos->lnum = 1; break; @@ -1455,20 +1480,23 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) } else if (pos->lnum > buf->b_ml.ml_line_count) { if (p_ws) { pos->lnum = 1; - if (!shortmess(SHM_SEARCH)) + if (!shortmess(SHM_SEARCH)) { give_warning((char_u *)_(bot_top_msg), true); + } } else { pos->lnum = 1; break; } } - if (pos->lnum == start) + if (pos->lnum == start) { break; - if (start == 0) + } + if (start == 0) { start = pos->lnum; + } ptr = ml_get_buf(buf, pos->lnum, false); p = skipwhite(ptr); - pos->col = (colnr_T) (p - ptr); + pos->col = (colnr_T)(p - ptr); /* when adding lines the matching line may be empty but it is not * ignored because we are interested in the next line -- Acevedo */ @@ -1481,8 +1509,9 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) // Expanding lines or words. assert(compl_length >= 0); if ((p_ic ? mb_strnicmp(p, pat, (size_t)compl_length) - : STRNCMP(p, pat, compl_length)) == 0) + : STRNCMP(p, pat, compl_length)) == 0) { return OK; + } } } return FAIL; @@ -1505,12 +1534,12 @@ int searchc(cmdarg_T *cap, int t_cmd) int dir = cap->arg; // true for searching forward long count = cap->count1; // repeat count int col; - char_u *p; + char_u *p; int len; bool stop = true; - if (c != NUL) { /* normal search: remember args for repeat */ - if (!KeyStuffed) { /* don't remember when redoing */ + if (c != NUL) { // normal search: remember args for repeat + if (!KeyStuffed) { // don't remember when redoing *lastc = c; set_csearch_direction(dir); set_csearch_until(t_cmd); @@ -1535,7 +1564,7 @@ int searchc(cmdarg_T *cap, int t_cmd) } t_cmd = last_t_cmd; c = *lastc; - /* For multi-byte re-use last lastc_bytes[] and lastc_bytelen. */ + // For multi-byte re-use last lastc_bytes[] and lastc_bytelen. /* Force a move of at least one char, so ";" and "," will move the * cursor, even if the cursor is right in front of char we are looking @@ -1545,10 +1574,11 @@ int searchc(cmdarg_T *cap, int t_cmd) } } - if (dir == BACKWARD) + if (dir == BACKWARD) { cap->oap->inclusive = false; - else + } else { cap->oap->inclusive = true; + } p = get_cursor_line_ptr(); col = curwin->w_cursor.col; @@ -1667,8 +1697,7 @@ static bool find_rawstring_end(char_u *linep, pos_T *startpos, pos_T *endpos) /// If there is a match set "*initc" to the matching character and "*findc" to /// the opposite character. Set "*backwards" to the direction. /// When "switchit" is true swap the direction. -static void find_mps_values(int *initc, int *findc, bool *backwards, - bool switchit) +static void find_mps_values(int *initc, int *findc, bool *backwards, bool switchit) FUNC_ATTR_NONNULL_ALL { char_u *ptr = curbuf->b_p_mps; @@ -1734,7 +1763,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) bool backwards = false; // init for gcc bool raw_string = false; // search for raw string bool inquote = false; // true when inside quotes - char_u *ptr; + char_u *ptr; int hash_dir = 0; // Direction searched for # things int comment_dir = 0; // Direction searched for comments int traveled = 0; // how far we've searched so far @@ -1754,13 +1783,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) // don't recognize backslashes bool cpo_bsl = (vim_strchr(p_cpo, CPO_MATCHBSL) != NULL); - /* Direction to search when initc is '/', '*' or '#' */ - if (flags & FM_BACKWARD) + // Direction to search when initc is '/', '*' or '#' + if (flags & FM_BACKWARD) { dir = BACKWARD; - else if (flags & FM_FORWARD) + } else if (flags & FM_FORWARD) { dir = FORWARD; - else + } else { dir = 0; + } /* * if initc given, look in the table for the matching character @@ -1770,8 +1800,9 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) */ if (initc == '/' || initc == '*' || initc == 'R') { comment_dir = dir; - if (initc == '/') + if (initc == '/') { ignore_cend = true; + } backwards = (dir == FORWARD) ? false : true; raw_string = (initc == 'R'); initc = NUL; @@ -1794,16 +1825,17 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * Only check for special things when 'cpo' doesn't have '%'. */ if (!cpo_match) { - /* Are we before or at #if, #else etc.? */ + // Are we before or at #if, #else etc.? ptr = skipwhite(linep); if (*ptr == '#' && pos.col <= (colnr_T)(ptr - linep)) { ptr = skipwhite(ptr + 1); - if ( STRNCMP(ptr, "if", 2) == 0 - || STRNCMP(ptr, "endif", 5) == 0 - || STRNCMP(ptr, "el", 2) == 0) + if (STRNCMP(ptr, "if", 2) == 0 + || STRNCMP(ptr, "endif", 5) == 0 + || STRNCMP(ptr, "el", 2) == 0) { hash_dir = 1; + } } - /* Are we on a comment? */ + // Are we on a comment? else if (linep[pos.col] == '/') { if (linep[pos.col + 1] == '*') { comment_dir = FORWARD; @@ -1835,12 +1867,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * If beyond the end of the line, use the last character in * the line. */ - if (linep[pos.col] == NUL && pos.col) + if (linep[pos.col] == NUL && pos.col) { --pos.col; + } for (;; ) { initc = PTR2CHAR(linep + pos.col); - if (initc == NUL) + if (initc == NUL) { break; + } find_mps_values(&initc, &findc, &backwards, false); if (findc) { @@ -1849,18 +1883,20 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos.col += utfc_ptr2len(linep + pos.col); } if (!findc) { - /* no brace in the line, maybe use " #if" then */ - if (!cpo_match && *skipwhite(linep) == '#') + // no brace in the line, maybe use " #if" then + if (!cpo_match && *skipwhite(linep) == '#') { hash_dir = 1; - else + } else { return NULL; + } } else if (!cpo_bsl) { int col, bslcnt = 0; /* Set "match_escaped" if there are an odd number of * backslashes. */ - for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) + for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) { bslcnt++; + } match_escaped = (bslcnt & 1); } } @@ -1874,49 +1910,58 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } if (initc != '#') { ptr = skipwhite(skipwhite(linep) + 1); - if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0) + if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0) { hash_dir = 1; - else if (STRNCMP(ptr, "endif", 5) == 0) + } else if (STRNCMP(ptr, "endif", 5) == 0) { hash_dir = -1; - else + } else { return NULL; + } } pos.col = 0; while (!got_int) { if (hash_dir > 0) { - if (pos.lnum == curbuf->b_ml.ml_line_count) + if (pos.lnum == curbuf->b_ml.ml_line_count) { break; - } else if (pos.lnum == 1) + } + } else if (pos.lnum == 1) { break; + } pos.lnum += hash_dir; linep = ml_get(pos.lnum); - line_breakcheck(); /* check for CTRL-C typed */ + line_breakcheck(); // check for CTRL-C typed ptr = skipwhite(linep); - if (*ptr != '#') + if (*ptr != '#') { continue; - pos.col = (colnr_T) (ptr - linep); + } + pos.col = (colnr_T)(ptr - linep); ptr = skipwhite(ptr + 1); if (hash_dir > 0) { - if (STRNCMP(ptr, "if", 2) == 0) + if (STRNCMP(ptr, "if", 2) == 0) { count++; - else if (STRNCMP(ptr, "el", 2) == 0) { - if (count == 0) + } else if (STRNCMP(ptr, "el", 2) == 0) { + if (count == 0) { return &pos; + } } else if (STRNCMP(ptr, "endif", 5) == 0) { - if (count == 0) + if (count == 0) { return &pos; + } count--; } } else { if (STRNCMP(ptr, "if", 2) == 0) { - if (count == 0) + if (count == 0) { return &pos; + } count--; } else if (initc == '#' && STRNCMP(ptr, "el", 2) == 0) { - if (count == 0) + if (count == 0) { return &pos; - } else if (STRNCMP(ptr, "endif", 5) == 0) + } + } else if (STRNCMP(ptr, "endif", 5) == 0) { count++; + } } } return NULL; @@ -1935,11 +1980,11 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos_T match_pos; // Where last slash-star was found clearpos(&match_pos); - /* backward search: Check if this line contains a single-line comment */ + // backward search: Check if this line contains a single-line comment if ((backwards && comment_dir) - || lisp - ) + || lisp) { comment_col = check_linecomment(linep); + } if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col) { lispcomm = true; // find match inside this comment } @@ -1949,58 +1994,63 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * inc() and dec() here, but that is much slower */ if (backwards) { - /* char to match is inside of comment, don't search outside */ - if (lispcomm && pos.col < (colnr_T)comment_col) + // char to match is inside of comment, don't search outside + if (lispcomm && pos.col < (colnr_T)comment_col) { break; - if (pos.col == 0) { /* at start of line, go to prev. one */ - if (pos.lnum == 1) /* start of file */ + } + if (pos.col == 0) { // at start of line, go to prev. one + if (pos.lnum == 1) { // start of file break; + } --pos.lnum; - if (maxtravel > 0 && ++traveled > maxtravel) + if (maxtravel > 0 && ++traveled > maxtravel) { break; + } linep = ml_get(pos.lnum); - pos.col = (colnr_T)STRLEN(linep); /* pos.col on trailing NUL */ + pos.col = (colnr_T)STRLEN(linep); // pos.col on trailing NUL do_quotes = -1; line_breakcheck(); - /* Check if this line contains a single-line comment */ + // Check if this line contains a single-line comment if (comment_dir - || lisp - ) + || lisp) { comment_col = check_linecomment(linep); - /* skip comment */ - if (lisp && comment_col != MAXCOL) + } + // skip comment + if (lisp && comment_col != MAXCOL) { pos.col = comment_col; + } } else { pos.col--; pos.col -= utf_head_off(linep, linep + pos.col); } - } else { /* forward search */ + } else { // forward search if (linep[pos.col] == NUL - /* at end of line, go to next one */ - /* don't search for match in comment */ + // at end of line, go to next one + // don't search for match in comment || (lisp && comment_col != MAXCOL - && pos.col == (colnr_T)comment_col) - ) { - if (pos.lnum == curbuf->b_ml.ml_line_count /* end of file */ + && pos.col == (colnr_T)comment_col)) { + if (pos.lnum == curbuf->b_ml.ml_line_count // end of file /* line is exhausted and comment with it, * don't search for match in code */ - || lispcomm - ) + || lispcomm) { break; + } ++pos.lnum; - if (maxtravel && traveled++ > maxtravel) + if (maxtravel && traveled++ > maxtravel) { break; + } linep = ml_get(pos.lnum); pos.col = 0; do_quotes = -1; line_breakcheck(); - if (lisp) /* find comment pos in new line */ + if (lisp) { // find comment pos in new line comment_col = check_linecomment(linep); + } } else { pos.col += utfc_ptr2len(linep + pos.col); } @@ -2016,40 +2066,37 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } if (comment_dir) { - /* Note: comments do not nest, and we ignore quotes in them */ - /* TODO: ignore comment brackets inside strings */ + // Note: comments do not nest, and we ignore quotes in them + // TODO: ignore comment brackets inside strings if (comment_dir == FORWARD) { if (linep[pos.col] == '*' && linep[pos.col + 1] == '/') { pos.col++; return &pos; } - } else { /* Searching backwards */ + } else { // Searching backwards /* * A comment may contain / * or / /, it may also start or end * with / * /. Ignore a / * after / / and after *. */ - if (pos.col == 0) + if (pos.col == 0) { continue; - else if (raw_string) - { + } else if (raw_string) { if (linep[pos.col - 1] == 'R' && linep[pos.col] == '"' - && vim_strchr(linep + pos.col + 1, '(') != NULL) - { + && vim_strchr(linep + pos.col + 1, '(') != NULL) { /* Possible start of raw string. Now that we have the * delimiter we can check if it ends before where we * started searching, or before the previously found * raw string start. */ if (!find_rawstring_end(linep, &pos, - count > 0 ? &match_pos : &curwin->w_cursor)) - { + count > 0 ? &match_pos : &curwin->w_cursor)) { count++; match_pos = pos; match_pos.col--; } - linep = ml_get(pos.lnum); /* may have been released */ + linep = ml_get(pos.lnum); // may have been released } - } else if ( linep[pos.col - 1] == '/' + } else if (linep[pos.col - 1] == '/' && linep[pos.col] == '*' && (pos.col == 1 || linep[pos.col - 2] != '*') && (int)pos.col < comment_col) { @@ -2057,15 +2104,16 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) match_pos = pos; match_pos.col--; } else if (linep[pos.col - 1] == '*' && linep[pos.col] == '/') { - if (count > 0) + if (count > 0) { pos = match_pos; - else if (pos.col > 1 && linep[pos.col - 2] == '/' - && (int)pos.col <= comment_col) + } else if (pos.col > 1 && linep[pos.col - 2] == '/' + && (int)pos.col <= comment_col) { pos.col -= 2; - else if (ignore_cend) + } else if (ignore_cend) { continue; - else + } else { return NULL; + } return &pos; } } @@ -2077,24 +2125,27 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * of quotes are ignored, but only if there is an even number of * quotes in the line. */ - if (cpo_match) + if (cpo_match) { do_quotes = 0; - else if (do_quotes == -1) { + } else if (do_quotes == -1) { /* * Count the number of quotes in the line, skipping \" and '"'. * Watch out for "\\". */ at_start = do_quotes; for (ptr = linep; *ptr; ++ptr) { - if (ptr == linep + pos.col + backwards) + if (ptr == linep + pos.col + backwards) { at_start = (do_quotes & 1); + } if (*ptr == '"' - && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) + && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) { ++do_quotes; - if (*ptr == '\\' && ptr[1] != NUL) + } + if (*ptr == '\\' && ptr[1] != NUL) { ++ptr; + } } - do_quotes &= 1; /* result is 1 with even number of quotes */ + do_quotes &= 1; // result is 1 with even number of quotes /* * If we find an uneven count, check current line and previous @@ -2126,7 +2177,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } } - /* ml_get() only keeps one line, need to get linep again */ + // ml_get() only keeps one line, need to get linep again linep = ml_get(pos.lnum); } } @@ -2149,7 +2200,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) const int c = PTR2CHAR(linep + pos.col); switch (c) { case NUL: - /* at end of line without trailing backslash, reset inquote */ + // at end of line without trailing backslash, reset inquote if (pos.col == 0 || linep[pos.col - 1] != '\\') { inquote = false; start_in_quotes = kFalse; @@ -2162,9 +2213,11 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) if (do_quotes) { int col; - for (col = pos.col - 1; col >= 0; --col) - if (linep[col] != '\\') + for (col = pos.col - 1; col >= 0; --col) { + if (linep[col] != '\\') { break; + } + } if ((((int)pos.col - 1 - col) & 1) == 0) { inquote = !inquote; start_in_quotes = kFalse; @@ -2214,8 +2267,9 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) && vim_strchr((char_u *)"(){}[]", c) != NULL && pos.col > 1 && check_prevcol(linep, pos.col, '\\', NULL) - && check_prevcol(linep, pos.col - 1, '#', NULL)) + && check_prevcol(linep, pos.col - 1, '#', NULL)) { break; + } /* Check for match outside of quotes, and inside of * quotes when the start is also inside of quotes. */ @@ -2224,17 +2278,19 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) int col, bslcnt = 0; if (!cpo_bsl) { - for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) + for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) { bslcnt++; + } } /* Only accept a match when 'M' is in 'cpo' or when escaping * is what we expect. */ if (cpo_bsl || (bslcnt & 1) == match_escaped) { - if (c == initc) + if (c == initc) { count++; - else { - if (count == 0) + } else { + if (count == 0) { return &pos; + } count--; } } @@ -2246,7 +2302,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos = match_pos; return &pos; } - return (pos_T *)NULL; /* never found it */ + return (pos_T *)NULL; // never found it } /* @@ -2279,34 +2335,35 @@ static int check_linecomment(const char_u *line) } p++; } - } else + } else { p = NULL; - } else + } + } else { while ((p = vim_strchr(p, '/')) != NULL) { /* accept a double /, unless it's preceded with * and followed by *, * because * / / * is an end and start of a C comment */ - if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*')) + if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*')) { break; + } ++p; } + } - if (p == NULL) + if (p == NULL) { return MAXCOL; + } return (int)(p - line); } -/* - * Move cursor briefly to character matching the one under the cursor. - * Used for Insert mode and "r" command. - * Show the match only if it is visible on the screen. - * If there isn't a match, then beep. - */ -void -showmatch( - int c // char to show match for -) +/// Move cursor briefly to character matching the one under the cursor. +/// Used for Insert mode and "r" command. +/// Show the match only if it is visible on the screen. +/// If there isn't a match, then beep. +/// +/// @param c char to show match for +void showmatch(int c) { - pos_T *lpos, save_cursor; + pos_T *lpos, save_cursor; pos_T mpos; colnr_T vcol; long *so = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so; @@ -2315,15 +2372,16 @@ showmatch( long save_siso; int save_state; colnr_T save_dollar_vcol; - char_u *p; + char_u *p; /* * Only show match for chars in the 'matchpairs' option. */ - /* 'matchpairs' is "x:y,x:y" */ + // 'matchpairs' is "x:y,x:y" for (p = curbuf->b_p_mps; *p != NUL; ++p) { - if (PTR2CHAR(p) == c && (curwin->w_p_rl ^ p_ri)) + if (PTR2CHAR(p) == c && (curwin->w_p_rl ^ p_ri)) { break; + } p += utfc_ptr2len(p) + 1; if (PTR2CHAR(p) == c && !(curwin->w_p_rl ^ p_ri)) { break; @@ -2340,7 +2398,7 @@ showmatch( if ((lpos = findmatch(NULL, NUL)) == NULL) { // no match, so beep vim_beep(BO_MATCH); } else if (lpos->lnum >= curwin->w_topline - && lpos->lnum < curwin->w_botline) { + && lpos->lnum < curwin->w_botline) { if (!curwin->w_p_wrap) { getvcol(curwin, lpos, NULL, &vcol, NULL); } @@ -2405,10 +2463,11 @@ int findsent(Direction dir, long count) bool noskip = false; // do not skip blanks pos = curwin->w_cursor; - if (dir == FORWARD) + if (dir == FORWARD) { func = incl; - else + } else { func = decl; + } while (count--) { const pos_T prev_pos = pos; @@ -2423,8 +2482,8 @@ int findsent(Direction dir, long count) if (dir == FORWARD) { goto found; } - // if on the start of a paragraph or a section and searching forward, - // go to the next line + // if on the start of a paragraph or a section and searching forward, + // go to the next line } else if (dir == FORWARD && pos.col == 0 && startPS(pos.lnum, NUL, false)) { if (pos.lnum == curbuf->b_ml.ml_line_count) { @@ -2447,11 +2506,11 @@ int findsent(Direction dir, long count) if (found_dot) { break; } - if (vim_strchr((char_u *) ".!?", c) != NULL) { + if (vim_strchr((char_u *)".!?", c) != NULL) { found_dot = true; } - if (vim_strchr((char_u *) ")]\"'", c) != NULL - && vim_strchr((char_u *) ".!?)]\"'", gchar_pos(&tpos)) == NULL) { + if (vim_strchr((char_u *)")]\"'", c) != NULL + && vim_strchr((char_u *)".!?)]\"'", gchar_pos(&tpos)) == NULL) { break; } decl(&pos); @@ -2461,41 +2520,47 @@ int findsent(Direction dir, long count) const int startlnum = pos.lnum; const bool cpo_J = vim_strchr(p_cpo, CPO_ENDOFSENT) != NULL; - for (;; ) { /* find end of sentence */ + for (;; ) { // find end of sentence c = gchar_pos(&pos); if (c == NUL || (pos.col == 0 && startPS(pos.lnum, NUL, FALSE))) { - if (dir == BACKWARD && pos.lnum != startlnum) + if (dir == BACKWARD && pos.lnum != startlnum) { ++pos.lnum; + } break; } if (c == '.' || c == '!' || c == '?') { tpos = pos; do - if ((c = inc(&tpos)) == -1) + if ((c = inc(&tpos)) == -1) { break; + } while (vim_strchr((char_u *)")]\"'", c = gchar_pos(&tpos)) != NULL); if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL || (cpo_J && (c == ' ' && inc(&tpos) >= 0 && gchar_pos(&tpos) == ' '))) { pos = tpos; - if (gchar_pos(&pos) == NUL) /* skip NUL at EOL */ + if (gchar_pos(&pos) == NUL) { // skip NUL at EOL inc(&pos); + } break; } } if ((*func)(&pos) == -1) { - if (count) + if (count) { return FAIL; + } noskip = true; break; } } found: - /* skip white space */ - while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t')) - if (incl(&pos) == -1) + // skip white space + while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t')) { + if (incl(&pos) == -1) { break; + } + } if (equalpos(prev_pos, pos)) { // didn't actually move, advance one character and try again @@ -2514,28 +2579,22 @@ found: return OK; } -/* - * Find the next paragraph or section in direction 'dir'. - * Paragraphs are currently supposed to be separated by empty lines. - * If 'what' is NUL we go to the next paragraph. - * If 'what' is '{' or '}' we go to the next section. - * If 'both' is TRUE also stop at '}'. - * Return TRUE if the next paragraph or section was found. - */ -bool -findpar ( - bool *pincl, /* Return: true if last char is to be included */ - int dir, - long count, - int what, - int both -) +/// Find the next paragraph or section in direction 'dir'. +/// Paragraphs are currently supposed to be separated by empty lines. +/// If 'what' is NUL we go to the next paragraph. +/// If 'what' is '{' or '}' we go to the next section. +/// If 'both' is TRUE also stop at '}'. +/// +/// @param pincl Return: true if last char is to be included +/// +/// @return TRUE if the next paragraph or section was found. +bool findpar(bool *pincl, int dir, long count, int what, int both) { linenr_T curr; - bool did_skip; /* true after separating lines have been skipped */ - bool first; /* true on first line */ - linenr_T fold_first; /* first line of a closed fold */ - linenr_T fold_last; /* last line of a closed fold */ + bool did_skip; // true after separating lines have been skipped + bool first; // true on first line + linenr_T fold_first; // first line of a closed fold + linenr_T fold_last; // last line of a closed fold bool fold_skipped; /* true if a closed fold was skipped this iteration */ @@ -2544,32 +2603,37 @@ findpar ( while (count--) { did_skip = false; for (first = true;; first = false) { - if (*ml_get(curr) != NUL) + if (*ml_get(curr) != NUL) { did_skip = true; + } - /* skip folded lines */ + // skip folded lines fold_skipped = false; if (first && hasFolding(curr, &fold_first, &fold_last)) { curr = ((dir > 0) ? fold_last : fold_first) + dir; fold_skipped = true; } - if (!first && did_skip && startPS(curr, what, both)) + if (!first && did_skip && startPS(curr, what, both)) { break; + } - if (fold_skipped) + if (fold_skipped) { curr -= dir; + } if ((curr += dir) < 1 || curr > curbuf->b_ml.ml_line_count) { - if (count) + if (count) { return false; + } curr -= dir; break; } } } setpcmark(); - if (both && *ml_get(curr) == '}') /* include line with '}' */ + if (both && *ml_get(curr) == '}') { // include line with '}' ++curr; + } curwin->w_cursor.lnum = curr; if (curr == curbuf->b_ml.ml_line_count && what != '}') { char_u *line = ml_get(curr); @@ -2581,8 +2645,9 @@ findpar ( curwin->w_cursor.col -= utf_head_off(line, line + curwin->w_cursor.col); *pincl = true; } - } else + } else { curwin->w_cursor.col = 0; + } return true; } @@ -2591,7 +2656,7 @@ findpar ( */ static int inmacro(char_u *opt, char_u *s) { - char_u *macro; + char_u *macro; for (macro = opt; macro[0]; ++macro) { /* Accept two characters in the option being equal to two characters @@ -2602,11 +2667,13 @@ static int inmacro(char_u *opt, char_u *s) && (s[0] == NUL || s[0] == ' '))) && (macro[1] == s[1] || ((macro[1] == NUL || macro[1] == ' ') - && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) + && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) { break; + } ++macro; - if (macro[0] == NUL) + if (macro[0] == NUL) { break; + } } return macro[0] != NUL; } @@ -2618,7 +2685,7 @@ static int inmacro(char_u *opt, char_u *s) */ int startPS(linenr_T lnum, int para, int both) { - char_u *s; + char_u *s; s = ml_get(lnum); if (*s == para || *s == '\f' || (both && *s == '}')) { @@ -2647,7 +2714,7 @@ int startPS(linenr_T lnum, int para, int both) * 2 or higher - keyword characters (letters, digits and underscore) */ -static int cls_bigword; /* TRUE for "W", "B" or "E" */ +static int cls_bigword; // TRUE for "W", "B" or "E" /* * cls() - returns the class of character at curwin->w_cursor @@ -2674,20 +2741,15 @@ static int cls(void) return c; } -/* - * fwd_word(count, type, eol) - move forward one word - * - * Returns FAIL if the cursor was already at the end of the file. - * If eol is TRUE, last word stops at end of line (for operators). - */ -int -fwd_word( - long count, - int bigword, /* "W", "E" or "B" */ - int eol -) +/// fwd_word(count, type, eol) - move forward one word +/// +/// @return FAIL if the cursor was already at the end of the file. +/// If eol is TRUE, last word stops at end of line (for operators). +/// +/// @param bigword "W", "E" or "B" +int fwd_word(long count, int bigword, int eol) { - int sclass; /* starting class */ + int sclass; // starting class int i; int last_line; @@ -2707,20 +2769,24 @@ fwd_word( */ last_line = (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count); i = inc_cursor(); - if (i == -1 || (i >= 1 && last_line)) /* started at last char in file */ + if (i == -1 || (i >= 1 && last_line)) { // started at last char in file return FAIL; - if (i >= 1 && eol && count == 0) /* started at last char in line */ + } + if (i >= 1 && eol && count == 0) { // started at last char in line return OK; + } /* * Go one char past end of current word (if any) */ - if (sclass != 0) + if (sclass != 0) { while (cls() == sclass) { i = inc_cursor(); - if (i == -1 || (i >= 1 && eol && count == 0)) + if (i == -1 || (i >= 1 && eol && count == 0)) { return OK; + } } + } /* * go to next non-white @@ -2729,12 +2795,14 @@ fwd_word( /* * We'll stop if we land on a blank line */ - if (curwin->w_cursor.col == 0 && *get_cursor_line_ptr() == NUL) + if (curwin->w_cursor.col == 0 && *get_cursor_line_ptr() == NUL) { break; + } i = inc_cursor(); - if (i == -1 || (i >= 1 && eol && count == 0)) + if (i == -1 || (i >= 1 && eol && count == 0)) { return OK; + } } } return OK; @@ -2749,18 +2817,20 @@ fwd_word( */ int bck_word(long count, int bigword, int stop) { - int sclass; /* starting class */ + int sclass; // starting class curwin->w_cursor.coladd = 0; cls_bigword = bigword; while (--count >= 0) { /* When inside a range of folded lines, move to the first char of the * first line. */ - if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) + if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) { curwin->w_cursor.col = 0; + } sclass = cls(); - if (dec_cursor() == -1) /* started at start of file */ + if (dec_cursor() == -1) { // started at start of file return FAIL; + } if (!stop || sclass == cls() || sclass == 0) { /* @@ -2780,11 +2850,12 @@ int bck_word(long count, int bigword, int stop) /* * Move backward to start of this word. */ - if (skip_chars(cls(), BACKWARD)) + if (skip_chars(cls(), BACKWARD)) { return OK; + } } - inc_cursor(); /* overshot - forward one */ + inc_cursor(); // overshot - forward one finished: stop = FALSE; } @@ -2808,7 +2879,7 @@ finished: */ int end_word(long count, int bigword, int stop, int empty) { - int sclass; /* starting class */ + int sclass; // starting class curwin->w_cursor.coladd = 0; cls_bigword = bigword; @@ -2819,8 +2890,9 @@ int end_word(long count, int bigword, int stop, int empty) coladvance(MAXCOL); } sclass = cls(); - if (inc_cursor() == -1) + if (inc_cursor() == -1) { return FAIL; + } /* * If we're in the middle of a word, we just have to move to the end @@ -2830,8 +2902,9 @@ int end_word(long count, int bigword, int stop, int empty) /* * Move forward to end of the current word */ - if (skip_chars(sclass, FORWARD)) + if (skip_chars(sclass, FORWARD)) { return FAIL; + } } else if (!stop || sclass == 0) { /* * We were at the end of a word. Go to the end of the next word. @@ -2850,12 +2923,13 @@ int end_word(long count, int bigword, int stop, int empty) /* * Move forward to the end of this word. */ - if (skip_chars(cls(), FORWARD)) + if (skip_chars(cls(), FORWARD)) { return FAIL; + } } - dec_cursor(); /* overshot - one char backward */ + dec_cursor(); // overshot - one char backward finished: - stop = FALSE; /* we move only one word less */ + stop = FALSE; // we move only one word less } return OK; } @@ -2868,25 +2942,29 @@ finished: /// @return FAIL if start of the file was reached. int bckend_word(long count, int bigword, bool eol) { - int sclass; /* starting class */ + int sclass; // starting class int i; curwin->w_cursor.coladd = 0; cls_bigword = bigword; while (--count >= 0) { sclass = cls(); - if ((i = dec_cursor()) == -1) + if ((i = dec_cursor()) == -1) { return FAIL; - if (eol && i == 1) + } + if (eol && i == 1) { return OK; + } /* * Move backward to before the start of this word. */ if (sclass != 0) { - while (cls() == sclass) - if ((i = dec_cursor()) == -1 || (eol && i == 1)) + while (cls() == sclass) { + if ((i = dec_cursor()) == -1 || (eol && i == 1)) { return OK; + } + } } /* @@ -2922,14 +3000,15 @@ static bool skip_chars(int cclass, int dir) */ static void back_in_line(void) { - int sclass; /* starting class */ + int sclass; // starting class sclass = cls(); for (;; ) { - if (curwin->w_cursor.col == 0) /* stop at start of line */ + if (curwin->w_cursor.col == 0) { // stop at start of line break; + } dec_cursor(); - if (cls() != sclass) { /* stop at start of word */ + if (cls() != sclass) { // stop at start of word inc_cursor(); break; } @@ -2956,25 +3035,22 @@ static void findsent_forward(long count, bool at_start_sent) { while (count--) { findsent(FORWARD, 1L); - if (at_start_sent) + if (at_start_sent) { find_first_blank(&curwin->w_cursor); - if (count == 0 || at_start_sent) + } + if (count == 0 || at_start_sent) { decl(&curwin->w_cursor); + } at_start_sent = !at_start_sent; } } -/* - * Find word under cursor, cursor at end. - * Used while an operator is pending, and in Visual mode. - */ -int -current_word( - oparg_T *oap, - long count, - int include, /* TRUE: include word and white space */ - int bigword /* FALSE == word, TRUE == WORD */ -) +/// Find word under cursor, cursor at end. +/// Used while an operator is pending, and in Visual mode. +/// +/// @param include TRUE: include word and white space +/// @param bigword FALSE == word, TRUE == WORD +int current_word(oparg_T *oap, long count, int include, int bigword) { pos_T start_pos; pos_T pos; @@ -2984,9 +3060,10 @@ current_word( cls_bigword = bigword; clearpos(&start_pos); - /* Correct cursor when 'selection' is exclusive */ - if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) + // Correct cursor when 'selection' is exclusive + if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) { dec_cursor(); + } /* * When Visual mode is not active, or when the VIsual area is only one @@ -3005,8 +3082,9 @@ current_word( * not be included ("word"), find end of word. */ if ((cls() == 0) == include) { - if (end_word(1L, bigword, TRUE, TRUE) == FAIL) + if (end_word(1L, bigword, TRUE, TRUE) == FAIL) { return FAIL; + } } else { /* * If the start is not on white space, and white space should be @@ -3016,19 +3094,21 @@ current_word( * word) back up to end of the line. */ fwd_word(1L, bigword, TRUE); - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { decl(&curwin->w_cursor); - else + } else { oneleft(); + } - if (include) + if (include) { include_white = TRUE; + } } if (VIsual_active) { - /* should do something when inclusive == false ! */ + // should do something when inclusive == false ! VIsual = start_pos; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion } else { oap->start = start_pos; oap->motion_type = kMTCharWise; @@ -3045,11 +3125,13 @@ current_word( /* * In Visual mode, with cursor at start: move cursor back. */ - if (decl(&curwin->w_cursor) == -1) + if (decl(&curwin->w_cursor) == -1) { return FAIL; + } if (include != (cls() != 0)) { - if (bck_word(1L, bigword, TRUE) == FAIL) + if (bck_word(1L, bigword, TRUE) == FAIL) { return FAIL; + } } else { if (bckend_word(1L, bigword, true) == FAIL) { return FAIL; @@ -3060,21 +3142,25 @@ current_word( /* * Move cursor forward one word and/or white area. */ - if (incl(&curwin->w_cursor) == -1) + if (incl(&curwin->w_cursor) == -1) { return FAIL; + } if (include != (cls() == 0)) { - if (fwd_word(1L, bigword, TRUE) == FAIL && count > 1) + if (fwd_word(1L, bigword, TRUE) == FAIL && count > 1) { return FAIL; + } /* * If end is just past a new-line, we don't want to include * the first character on the line. * Put cursor on last char of white. */ - if (oneleft() == FAIL) + if (oneleft() == FAIL) { inclusive = false; + } } else { - if (end_word(1L, bigword, TRUE, TRUE) == FAIL) + if (end_word(1L, bigword, TRUE, TRUE) == FAIL) { return FAIL; + } } } --count; @@ -3090,29 +3176,32 @@ current_word( * (cursor is at start of next line). * But don't delete white space at start of line (indent). */ - pos = curwin->w_cursor; /* save cursor position */ + pos = curwin->w_cursor; // save cursor position curwin->w_cursor = start_pos; if (oneleft() == OK) { back_in_line(); if (cls() == 0 && curwin->w_cursor.col > 0) { - if (VIsual_active) + if (VIsual_active) { VIsual = curwin->w_cursor; - else + } else { oap->start = curwin->w_cursor; + } } } - curwin->w_cursor = pos; /* put cursor back at end */ + curwin->w_cursor = pos; // put cursor back at end } if (VIsual_active) { - if (*p_sel == 'e' && inclusive && ltoreq(VIsual, curwin->w_cursor)) + if (*p_sel == 'e' && inclusive && ltoreq(VIsual, curwin->w_cursor)) { inc_cursor(); + } if (VIsual_mode == 'V') { VIsual_mode = 'v'; redraw_cmdline = true; // show mode later } - } else + } else { oap->inclusive = inclusive; + } return OK; } @@ -3132,7 +3221,7 @@ int current_sent(oparg_T *oap, long count, int include) start_pos = curwin->w_cursor; pos = start_pos; - findsent(FORWARD, 1L); /* Find start of next sentence. */ + findsent(FORWARD, 1L); // Find start of next sentence. /* * When the Visual area is bigger than one character: Extend it. @@ -3166,14 +3255,17 @@ extend: findsent(FORWARD, 1L); } } - if (include) /* "as" gets twice as much as "is" */ + if (include) { // "as" gets twice as much as "is" count *= 2; + } while (count--) { - if (at_start_sent) + if (at_start_sent) { find_first_blank(&curwin->w_cursor); + } c = gchar_cursor(); - if (!at_start_sent || (!include && !ascii_iswhite(c))) + if (!at_start_sent || (!include && !ascii_iswhite(c))) { findsent(BACKWARD, 1L); + } at_start_sent = !at_start_sent; } } else { @@ -3196,17 +3288,20 @@ extend: } incl(&pos); } - if (at_start_sent) /* in the sentence */ + if (at_start_sent) { // in the sentence findsent(BACKWARD, 1L); - else /* in/before white before a sentence */ + } else { // in/before white before a sentence curwin->w_cursor = start_pos; + } } - if (include) /* "as" gets twice as much as "is" */ + if (include) { // "as" gets twice as much as "is" count *= 2; + } findsent_forward(count, at_start_sent); - if (*p_sel == 'e') + if (*p_sel == 'e') { ++curwin->w_cursor.col; + } } return OK; } @@ -3215,8 +3310,9 @@ extend: * If the cursor started on a blank, check if it is just before the start * of the next sentence. */ - while (c = gchar_pos(&pos), ascii_iswhite(c)) + while (c = gchar_pos(&pos), ascii_iswhite(c)) { incl(&pos); + } if (equalpos(pos, curwin->w_cursor)) { start_blank = true; find_first_blank(&start_pos); // go back to first blank @@ -3225,12 +3321,13 @@ extend: findsent(BACKWARD, 1L); start_pos = curwin->w_cursor; } - if (include) + if (include) { ncount = count * 2; - else { + } else { ncount = count; - if (start_blank) + if (start_blank) { --ncount; + } } if (ncount > 0) { findsent_forward(ncount, true); @@ -3247,57 +3344,57 @@ extend: if (start_blank) { find_first_blank(&curwin->w_cursor); c = gchar_pos(&curwin->w_cursor); - if (ascii_iswhite(c)) + if (ascii_iswhite(c)) { decl(&curwin->w_cursor); - } else if (c = gchar_cursor(), !ascii_iswhite(c)) + } + } else if (c = gchar_cursor(), !ascii_iswhite(c)) { find_first_blank(&start_pos); + } } if (VIsual_active) { - /* Avoid getting stuck with "is" on a single space before a sentence. */ - if (equalpos(start_pos, curwin->w_cursor)) + // Avoid getting stuck with "is" on a single space before a sentence. + if (equalpos(start_pos, curwin->w_cursor)) { goto extend; - if (*p_sel == 'e') + } + if (*p_sel == 'e') { ++curwin->w_cursor.col; + } VIsual = start_pos; VIsual_mode = 'v'; redraw_cmdline = true; // show mode later redraw_curbuf_later(INVERTED); // update the inversion } else { - /* include a newline after the sentence, if there is one */ - if (incl(&curwin->w_cursor) == -1) + // include a newline after the sentence, if there is one + if (incl(&curwin->w_cursor) == -1) { oap->inclusive = true; - else + } else { oap->inclusive = false; + } oap->start = start_pos; oap->motion_type = kMTCharWise; } return OK; } -/* - * Find block under the cursor, cursor at end. - * "what" and "other" are two matching parenthesis/brace/etc. - */ -int -current_block( - oparg_T *oap, - long count, - int include, /* TRUE == include white space */ - int what, /* '(', '{', etc. */ - int other /* ')', '}', etc. */ -) +/// Find block under the cursor, cursor at end. +/// "what" and "other" are two matching parenthesis/brace/etc. +/// +/// @param include TRUE == include white space +/// @param what '(', '{', etc. +/// @param other ')', '}', etc. +int current_block(oparg_T *oap, long count, int include, int what, int other) { pos_T old_pos; - pos_T *pos = NULL; + pos_T *pos = NULL; pos_T start_pos; - pos_T *end_pos; + pos_T *end_pos; pos_T old_start, old_end; - char_u *save_cpo; + char_u *save_cpo; bool sol = false; // '{' at start of line old_pos = curwin->w_cursor; - old_end = curwin->w_cursor; /* remember where we started */ + old_end = curwin->w_cursor; // remember where we started old_start = old_end; /* @@ -3305,18 +3402,23 @@ current_block( */ if (!VIsual_active || equalpos(VIsual, curwin->w_cursor)) { setpcmark(); - if (what == '{') /* ignore indent */ - while (inindent(1)) - if (inc_cursor() != 0) + if (what == '{') { // ignore indent + while (inindent(1)) { + if (inc_cursor() != 0) { break; - if (gchar_cursor() == what) - /* cursor on '(' or '{', move cursor just after it */ + } + } + } + if (gchar_cursor() == what) { + // cursor on '(' or '{', move cursor just after it ++curwin->w_cursor.col; + } } else if (lt(VIsual, curwin->w_cursor)) { old_start = VIsual; - curwin->w_cursor = VIsual; /* cursor at low end of Visual */ - } else + curwin->w_cursor = VIsual; // cursor at low end of Visual + } else { old_end = VIsual; + } // Search backwards for unclosed '(', '{', etc.. // Put this position in start_pos. @@ -3377,8 +3479,9 @@ current_block( return FAIL; } curwin->w_cursor = *end_pos; - } else + } else { break; + } } if (VIsual_active) { @@ -3390,21 +3493,22 @@ current_block( } VIsual = start_pos; VIsual_mode = 'v'; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion showmode(); } else { oap->start = start_pos; oap->motion_type = kMTCharWise; oap->inclusive = false; - if (sol) + if (sol) { incl(&curwin->w_cursor); - else if (ltoreq(start_pos, curwin->w_cursor)) - /* Include the character under the cursor. */ + } else if (ltoreq(start_pos, curwin->w_cursor)) { + // Include the character under the cursor. oap->inclusive = true; - else + } else { /* End is before the start (no text in between <>, [], etc.): don't * operate on any text. */ curwin->w_cursor = start_pos; + } } return OK; @@ -3416,8 +3520,8 @@ current_block( /// @return true if the cursor is on a "" tag. Ignore "". static bool in_html_tag(bool end_tag) { - char_u *line = get_cursor_line_ptr(); - char_u *p; + char_u *line = get_cursor_line_ptr(); + char_u *p; int c; int lc = NUL; pos_T pos; @@ -3449,36 +3553,32 @@ static bool in_html_tag(bool end_tag) return false; } - /* check that the matching '>' is not preceded by '/' */ + // check that the matching '>' is not preceded by '/' for (;; ) { if (inc(&pos) < 0) { return false; } c = *ml_get_pos(&pos); - if (c == '>') + if (c == '>') { break; + } lc = c; } return lc != '/'; } -/* - * Find tag block under the cursor, cursor at end. - */ -int -current_tagblock( - oparg_T *oap, - long count_arg, - bool include // true == include white space -) +/// Find tag block under the cursor, cursor at end. +/// +/// @param include true == include white space +int current_tagblock(oparg_T *oap, long count_arg, bool include) { long count = count_arg; pos_T old_pos; pos_T start_pos; pos_T end_pos; pos_T old_start, old_end; - char_u *p; - char_u *cp; + char_u *p; + char_u *cp; int len; bool do_include = include; bool save_p_ws = p_ws; @@ -3488,21 +3588,23 @@ current_tagblock( p_ws = false; old_pos = curwin->w_cursor; - old_end = curwin->w_cursor; /* remember where we started */ + old_end = curwin->w_cursor; // remember where we started old_start = old_end; - if (!VIsual_active || *p_sel == 'e') - decl(&old_end); /* old_end is inclusive */ - + if (!VIsual_active || *p_sel == 'e') { + decl(&old_end); // old_end is inclusive + } /* * If we start on "" select that block. */ if (!VIsual_active || equalpos(VIsual, curwin->w_cursor)) { setpcmark(); - /* ignore indent */ - while (inindent(1)) - if (inc_cursor() != 0) + // ignore indent + while (inindent(1)) { + if (inc_cursor() != 0) { break; + } + } if (in_html_tag(false)) { // cursor on start tag, move to its '>' @@ -3523,9 +3625,10 @@ current_tagblock( } } else if (lt(VIsual, curwin->w_cursor)) { old_start = VIsual; - curwin->w_cursor = VIsual; /* cursor at low end of Visual */ - } else + curwin->w_cursor = VIsual; // cursor at low end of Visual + } else { old_end = VIsual; + } again: /* @@ -3533,11 +3636,10 @@ again: * Put this position in start_pos. */ for (long n = 0; n < count; n++) { - if (do_searchpair( - "<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", - "", - "]*>", BACKWARD, NULL, 0, - NULL, (linenr_T)0, 0L) <= 0) { + if (do_searchpair("<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", + "", + "]*>", BACKWARD, NULL, 0, + NULL, (linenr_T)0, 0L) <= 0) { curwin->w_cursor = old_pos; goto theend; } @@ -3603,14 +3705,15 @@ again: end_pos = curwin->w_cursor; if (!do_include) { - /* Exclude the start tag. */ + // Exclude the start tag. curwin->w_cursor = start_pos; - while (inc_cursor() >= 0) + while (inc_cursor() >= 0) { if (*get_cursor_pos_ptr() == '>') { inc_cursor(); start_pos = curwin->w_cursor; break; } + } curwin->w_cursor = end_pos; // If we are in Visual mode and now have the same text as before set @@ -3635,7 +3738,7 @@ again: } VIsual = start_pos; VIsual_mode = 'v'; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion showmode(); } else { oap->start = start_pos; @@ -3656,13 +3759,9 @@ theend: return retval; } -int -current_par( - oparg_T *oap, - long count, - int include, /* TRUE == include white space */ - int type /* 'p' for paragraph, 'S' for section */ -) +/// @param include TRUE == include white space +/// @param type 'p' for paragraph, 'S' for section +int current_par(oparg_T *oap, long count, int include, int type) { linenr_T start_lnum; linenr_T end_lnum; @@ -3675,8 +3774,9 @@ current_par( int t; int i; - if (type == 'S') /* not implemented yet */ + if (type == 'S') { // not implemented yet return FAIL; + } start_lnum = curwin->w_cursor.lnum; @@ -3685,10 +3785,11 @@ current_par( */ if (VIsual_active && start_lnum != VIsual.lnum) { extend: - if (start_lnum < VIsual.lnum) + if (start_lnum < VIsual.lnum) { dir = BACKWARD; - else + } else { dir = FORWARD; + } for (i = count; --i >= 0; ) { if (start_lnum == (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count)) { @@ -3706,20 +3807,24 @@ extend: } for (;; ) { if (start_lnum == (dir == BACKWARD - ? 1 : curbuf->b_ml.ml_line_count)) + ? 1 : curbuf->b_ml.ml_line_count)) { break; + } if (start_is_white != linewhite(start_lnum + dir) || (!start_is_white && startPS(start_lnum + (dir > 0 - ? 1 : 0), 0, 0))) + ? 1 : 0), 0, 0))) { break; + } start_lnum += dir; } - if (!include) + if (!include) { break; + } if (start_lnum == (dir == BACKWARD - ? 1 : curbuf->b_ml.ml_line_count)) + ? 1 : curbuf->b_ml.ml_line_count)) { break; + } prev_start_is_white = start_is_white; } } @@ -3733,12 +3838,14 @@ extend: */ white_in_front = linewhite(start_lnum); while (start_lnum > 1) { - if (white_in_front) { /* stop at first white line */ - if (!linewhite(start_lnum - 1)) + if (white_in_front) { // stop at first white line + if (!linewhite(start_lnum - 1)) { break; - } else { /* stop at first non-white line of start of paragraph */ - if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0)) + } + } else { // stop at first non-white line of start of paragraph + if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0)) { break; + } } --start_lnum; } @@ -3747,19 +3854,23 @@ extend: * Move past the end of any white lines. */ end_lnum = start_lnum; - while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum)) + while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum)) { ++end_lnum; + } --end_lnum; i = count; - if (!include && white_in_front) + if (!include && white_in_front) { --i; + } while (i--) { - if (end_lnum == curbuf->b_ml.ml_line_count) + if (end_lnum == curbuf->b_ml.ml_line_count) { return FAIL; + } - if (!include) + if (!include) { do_white = linewhite(end_lnum + 1); + } if (include || !do_white) { ++end_lnum; @@ -3768,29 +3879,35 @@ extend: */ while (end_lnum < curbuf->b_ml.ml_line_count && !linewhite(end_lnum + 1) - && !startPS(end_lnum + 1, 0, 0)) + && !startPS(end_lnum + 1, 0, 0)) { ++end_lnum; + } } - if (i == 0 && white_in_front && include) + if (i == 0 && white_in_front && include) { break; + } /* * skip to end of white lines after paragraph */ - if (include || do_white) + if (include || do_white) { while (end_lnum < curbuf->b_ml.ml_line_count - && linewhite(end_lnum + 1)) + && linewhite(end_lnum + 1)) { ++end_lnum; + } + } } /* * If there are no empty lines at the end, try to find some empty lines at * the start (unless that has been done already). */ - if (!white_in_front && !linewhite(end_lnum) && include) - while (start_lnum > 1 && linewhite(start_lnum - 1)) + if (!white_in_front && !linewhite(end_lnum) && include) { + while (start_lnum > 1 && linewhite(start_lnum - 1)) { --start_lnum; + } + } if (VIsual_active) { // Problem: when doing "Vipipip" nothing happens in a single white @@ -3799,11 +3916,11 @@ extend: goto extend; } if (VIsual.lnum != start_lnum) { - VIsual.lnum = start_lnum; - VIsual.col = 0; + VIsual.lnum = start_lnum; + VIsual.col = 0; } VIsual_mode = 'V'; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion showmode(); } else { oap->start.lnum = start_lnum; @@ -3817,19 +3934,14 @@ extend: } -/* - * Search quote char from string line[col]. - * Quote character escaped by one of the characters in "escape" is not counted - * as a quote. - * Returns column number of "quotechar" or -1 when not found. - */ -static int -find_next_quote( - char_u *line, - int col, - int quotechar, - char_u *escape /* escape characters, can be NULL */ -) +/// Search quote char from string line[col]. +/// Quote character escaped by one of the characters in "escape" is not counted +/// as a quote. +/// +/// @param escape escape characters, can be NULL +/// +/// @return column number of "quotechar" or -1 when not found. +static int find_next_quote(char_u *line, int col, int quotechar, char_u *escape) { int c; @@ -3847,19 +3959,14 @@ find_next_quote( return col; } -/* - * Search backwards in "line" from column "col_start" to find "quotechar". - * Quote character escaped by one of the characters in "escape" is not counted - * as a quote. - * Return the found column or zero. - */ -static int -find_prev_quote( - char_u *line, - int col_start, - int quotechar, - char_u *escape /* escape characters, can be NULL */ -) +/// Search backwards in "line" from column "col_start" to find "quotechar". +/// Quote character escaped by one of the characters in "escape" is not counted +/// as a quote. +/// +/// @param escape escape characters, can be NULL +/// +/// @return the found column or zero. +static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *escape) { int n; @@ -3867,29 +3974,32 @@ find_prev_quote( col_start--; col_start -= utf_head_off(line, line + col_start); n = 0; - if (escape != NULL) + if (escape != NULL) { while (col_start - n > 0 && vim_strchr(escape, - line[col_start - n - 1]) != NULL) + line[col_start - n - 1]) != NULL) { ++n; - if (n & 1) - col_start -= n; /* uneven number of escape chars, skip it */ - else if (line[col_start] == quotechar) + } + } + if (n & 1) { + col_start -= n; // uneven number of escape chars, skip it + } else if (line[col_start] == + quotechar) { break; + } } return col_start; } -// Find quote under the cursor, cursor at end. -// Returns true if found, else false. -bool current_quote( - oparg_T *oap, - long count, - bool include, // true == include quote char - int quotechar // Quote character -) +/// Find quote under the cursor, cursor at end. +/// +/// @param include true == include quote char +/// @param quotechar Quote character +/// +/// @return true if found, else false. +bool current_quote(oparg_T *oap, long count, bool include, int quotechar) FUNC_ATTR_NONNULL_ALL { - char_u *line = get_cursor_line_ptr(); + char_u *line = get_cursor_line_ptr(); int col_end; int col_start = curwin->w_cursor.col; bool inclusive = false; @@ -3907,7 +4017,7 @@ bool current_quote( if (VIsual_active) { // this only works within one line if (VIsual.lnum != curwin->w_cursor.lnum) { - return false; + return false; } vis_bef_curs = lt(VIsual, curwin->w_cursor); @@ -3952,12 +4062,13 @@ bool current_quote( col_end = VIsual.col; } - /* Find out if we have a quote in the selection. */ - while (i <= col_end) + // Find out if we have a quote in the selection. + while (i <= col_end) { if (line[i++] == quotechar) { selected_quote = true; break; } + } } if (!vis_empty && line[col_start] == quotechar) { @@ -3971,9 +4082,9 @@ bool current_quote( goto abort_search; } col_end = find_next_quote(line, col_start + 1, quotechar, - curbuf->b_p_qe); + curbuf->b_p_qe); if (col_end < 0) { - /* We were on a starting quote perhaps? */ + // We were on a starting quote perhaps? col_end = col_start; col_start = curwin->w_cursor.col; } @@ -3983,23 +4094,23 @@ bool current_quote( goto abort_search; } col_start = find_prev_quote(line, col_end, quotechar, - curbuf->b_p_qe); + curbuf->b_p_qe); if (line[col_start] != quotechar) { - /* We were on an ending quote perhaps? */ + // We were on an ending quote perhaps? col_start = col_end; col_end = curwin->w_cursor.col; } } } else if (line[col_start] == quotechar - || !vis_empty - ) { + || !vis_empty) { int first_col = col_start; if (!vis_empty) { - if (vis_bef_curs) + if (vis_bef_curs) { first_col = find_next_quote(line, col_start, quotechar, NULL); - else + } else { first_col = find_prev_quote(line, col_start, quotechar, NULL); + } } /* The cursor is on a quote, we don't know if it's the opening or * closing quote. Search from the start of the line to find out. @@ -4007,14 +4118,14 @@ bool current_quote( * in between two strings. */ col_start = 0; for (;; ) { - /* Find open quote character. */ + // Find open quote character. col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0 || col_start > first_col) { goto abort_search; } // Find close quote character. col_end = find_next_quote(line, col_start + 1, quotechar, - curbuf->b_p_qe); + curbuf->b_p_qe); if (col_end < 0) { goto abort_search; } @@ -4026,17 +4137,17 @@ bool current_quote( col_start = col_end + 1; } } else { - /* Search backward for a starting quote. */ + // Search backward for a starting quote. col_start = find_prev_quote(line, col_start, quotechar, curbuf->b_p_qe); if (line[col_start] != quotechar) { - /* No quote before the cursor, look after the cursor. */ + // No quote before the cursor, look after the cursor. col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0) { goto abort_search; } } - /* Find close quote character. */ + // Find close quote character. col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) { @@ -4047,20 +4158,23 @@ bool current_quote( // When "include" is true, include spaces after closing quote or before // the starting quote. if (include) { - if (ascii_iswhite(line[col_end + 1])) - while (ascii_iswhite(line[col_end + 1])) + if (ascii_iswhite(line[col_end + 1])) { + while (ascii_iswhite(line[col_end + 1])) { ++col_end; - else - while (col_start > 0 && ascii_iswhite(line[col_start - 1])) + } + } else { + while (col_start > 0 && ascii_iswhite(line[col_start - 1])) { --col_start; + } + } } /* Set start position. After vi" another i" must include the ". * For v2i" include the quotes. */ if (!include && count < 2 - && (vis_empty || !inside_quotes) - ) + && (vis_empty || !inside_quotes)) { ++col_start; + } curwin->w_cursor.col = col_start; if (VIsual_active) { /* Set the start of the Visual area when the Visual area was empty, we @@ -4082,13 +4196,14 @@ bool current_quote( oap->motion_type = kMTCharWise; } - /* Set end position. */ + // Set end position. curwin->w_cursor.col = col_end; if ((include || count > 1 - /* After vi" another i" must include the ". */ + // After vi" another i" must include the ". || (!vis_empty && inside_quotes) - ) && inc_cursor() == 2) + ) && inc_cursor() == 2) { inclusive = true; + } if (VIsual_active) { if (vis_empty || vis_bef_curs) { // decrement cursor when 'selection' is not exclusive @@ -4114,7 +4229,7 @@ bool current_quote( redraw_cmdline = true; // show mode later } } else { - /* Set inclusive and other oap's flags. */ + // Set inclusive and other oap's flags. oap->inclusive = inclusive; } @@ -4126,10 +4241,10 @@ abort_search: inc_cursor(); } if (restore_vis_bef) { - pos_T t = curwin->w_cursor; + pos_T t = curwin->w_cursor; - curwin->w_cursor = VIsual; - VIsual = t; + curwin->w_cursor = VIsual; + VIsual = t; } } return false; @@ -4137,22 +4252,19 @@ abort_search: -/* - * Find next search match under cursor, cursor at end. - * Used while an operator is pending, and in Visual mode. - */ -int -current_search( - long count, - bool forward // true for forward, false for backward -) +/// Find next search match under cursor, cursor at end. +/// Used while an operator is pending, and in Visual mode. +/// +/// @param forward true for forward, false for backward +int current_search(long count, bool forward) { bool old_p_ws = p_ws; pos_T save_VIsual = VIsual; - /* Correct cursor when 'selection' is exclusive */ - if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) + // Correct cursor when 'selection' is exclusive + if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) { dec_cursor(); + } pos_T end_pos; // end position of the pattern match pos_T orig_pos; // position of the cursor at beginning @@ -4162,7 +4274,7 @@ current_search( // When searching forward and the cursor is at the start of the Visual // area, skip the first search backward, otherwise it doesn't move. const bool skip_first_backward = forward && VIsual_active - && lt(curwin->w_cursor, VIsual); + && lt(curwin->w_cursor, VIsual); orig_pos = pos = curwin->w_cursor; if (VIsual_active) { @@ -4220,8 +4332,9 @@ current_search( // selection works. if (i == 1 && !result) { // not found, abort */ curwin->w_cursor = orig_pos; - if (VIsual_active) + if (VIsual_active) { VIsual = save_VIsual; + } return FAIL; } else if (i == 0 && !result) { if (forward) { // try again from start of buffer @@ -4229,8 +4342,7 @@ current_search( } else { // try again from end of buffer // searching backwards, so set pos to last line and col pos.lnum = curwin->w_buffer->b_ml.ml_line_count; - pos.col = (colnr_T)STRLEN( - ml_get(curwin->w_buffer->b_ml.ml_line_count)); + pos.col = (colnr_T)STRLEN(ml_get(curwin->w_buffer->b_ml.ml_line_count)); } } } @@ -4283,8 +4395,7 @@ current_search( /// else from position "cur". /// "direction" is FORWARD or BACKWARD. /// Returns TRUE, FALSE or -1 for failure. -static int -is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) +static int is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) { regmmatch_T regmatch; int nmatched = 0; @@ -4298,8 +4409,9 @@ is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) } if (search_regcomp(pattern, RE_SEARCH, RE_SEARCH, - SEARCH_KEEP, ®match) == FAIL) + SEARCH_KEEP, ®match) == FAIL) { return -1; + } // init startcol correctly regmatch.startpos[0].col = -1; @@ -4346,7 +4458,7 @@ is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) */ int linewhite(linenr_T lnum) { - char_u *p; + char_u *p; p = skipwhite(ml_get(lnum)); return *p == NUL; @@ -4354,64 +4466,63 @@ int linewhite(linenr_T lnum) // Add the search count "[3/19]" to "msgbuf". // See update_search_stat() for other arguments. -static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, - bool show_top_bot_msg, char_u *msgbuf, - bool recompute, int maxcount, long timeout) +static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, bool show_top_bot_msg, + char_u *msgbuf, bool recompute, int maxcount, long timeout) { - searchstat_T stat; + searchstat_T stat; - update_search_stat(dirc, pos, cursor_pos, &stat, recompute, maxcount, - timeout); - if (stat.cur > 0) { - char t[SEARCH_STAT_BUF_LEN]; + update_search_stat(dirc, pos, cursor_pos, &stat, recompute, maxcount, + timeout); + if (stat.cur > 0) { + char t[SEARCH_STAT_BUF_LEN]; - if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { - if (stat.incomplete == 1) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); - } else if (stat.cnt > maxcount && stat.cur > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", - maxcount, maxcount); - } else if (stat.cnt > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/%d]", - maxcount, stat.cur); - } else { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", - stat.cnt, stat.cur); - } + if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { + if (stat.incomplete == 1) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); + } else if (stat.cnt > maxcount && stat.cur > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", + maxcount, maxcount); + } else if (stat.cnt > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/%d]", + maxcount, stat.cur); } else { - if (stat.incomplete == 1) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); - } else if (stat.cnt > maxcount && stat.cur > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", - maxcount, maxcount); - } else if (stat.cnt > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/>%d]", - stat.cur, maxcount); - } else { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", - stat.cur, stat.cnt); - } + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", + stat.cnt, stat.cur); } - - size_t len = strlen(t); - if (show_top_bot_msg && len + 2 < SEARCH_STAT_BUF_LEN) { - memmove(t + 2, t, len); - t[0] = 'W'; - t[1] = ' '; - len += 2; + } else { + if (stat.incomplete == 1) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); + } else if (stat.cnt > maxcount && stat.cur > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", + maxcount, maxcount); + } else if (stat.cnt > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/>%d]", + stat.cur, maxcount); + } else { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", + stat.cur, stat.cnt); } - - memmove(msgbuf + STRLEN(msgbuf) - len, t, len); - if (dirc == '?' && stat.cur == maxcount + 1) { - stat.cur = -1; - } - - // keep the message even after redraw, but don't put in history - msg_hist_off = true; - msg_ext_set_kind("search_count"); - give_warning(msgbuf, false); - msg_hist_off = false; } + + size_t len = strlen(t); + if (show_top_bot_msg && len + 2 < SEARCH_STAT_BUF_LEN) { + memmove(t + 2, t, len); + t[0] = 'W'; + t[1] = ' '; + len += 2; + } + + memmove(msgbuf + STRLEN(msgbuf) - len, t, len); + if (dirc == '?' && stat.cur == maxcount + 1) { + stat.cur = -1; + } + + // keep the message even after redraw, but don't put in history + msg_hist_off = true; + msg_ext_set_kind("search_count"); + give_warning(msgbuf, false); + msg_hist_off = false; + } } // Add the search count information to "stat". @@ -4420,258 +4531,253 @@ static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, // dirc == 0: don't find the next/previous match (only set the result to "stat") // dirc == '/': find the next match // dirc == '?': find the previous match -static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, - searchstat_T *stat, bool recompute, int maxcount, - long timeout) +static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, searchstat_T *stat, + bool recompute, int maxcount, long timeout) { - int save_ws = p_ws; - bool wraparound = false; - pos_T p = (*pos); - static pos_T lastpos = { 0, 0, 0 }; - static int cur = 0; - static int cnt = 0; - static bool exact_match = false; - static int incomplete = 0; - static int last_maxcount = SEARCH_STAT_DEF_MAX_COUNT; - static int chgtick = 0; - static char_u *lastpat = NULL; - static buf_T *lbuf = NULL; - proftime_T start; + int save_ws = p_ws; + bool wraparound = false; + pos_T p = (*pos); + static pos_T lastpos = { 0, 0, 0 }; + static int cur = 0; + static int cnt = 0; + static bool exact_match = false; + static int incomplete = 0; + static int last_maxcount = SEARCH_STAT_DEF_MAX_COUNT; + static int chgtick = 0; + static char_u *lastpat = NULL; + static buf_T *lbuf = NULL; + proftime_T start; - memset(stat, 0, sizeof(searchstat_T)); + memset(stat, 0, sizeof(searchstat_T)); - if (dirc == 0 && !recompute && !EMPTY_POS(lastpos)) { - stat->cur = cur; - stat->cnt = cnt; - stat->exact_match = exact_match; - stat->incomplete = incomplete; - stat->last_maxcount = last_maxcount; - return; - } - last_maxcount = maxcount; - wraparound = ((dirc == '?' && lt(lastpos, p)) - || (dirc == '/' && lt(p, lastpos))); - - // If anything relevant changed the count has to be recomputed. - // STRNICMP ignores case, but we should not ignore case. - // Unfortunately, there is no STRNICMP function. - // XXX: above comment should be "no MB_STRCMP function" ? - if (!(chgtick == buf_get_changedtick(curbuf) - && lastpat != NULL // suppress clang/NULL passed as nonnull parameter - && STRNICMP(lastpat, spats[last_idx].pat, STRLEN(lastpat)) == 0 - && STRLEN(lastpat) == STRLEN(spats[last_idx].pat) - && equalpos(lastpos, *cursor_pos) - && lbuf == curbuf) - || wraparound || cur < 0 || (maxcount > 0 && cur > maxcount) - || recompute) { - cur = 0; - cnt = 0; - exact_match = false; - incomplete = 0; - clearpos(&lastpos); - lbuf = curbuf; - } - - if (equalpos(lastpos, *cursor_pos) && !wraparound - && (dirc == 0 || dirc == '/' ? cur < cnt : cur > 0)) { - cur += dirc == 0 ? 0 : dirc == '/' ? 1 : -1; - } else { - bool done_search = false; - pos_T endpos = { 0, 0, 0 }; - p_ws = false; - if (timeout > 0) { - start = profile_setlimit(timeout); - } - while (!got_int && searchit(curwin, curbuf, &lastpos, &endpos, - FORWARD, NULL, 1, SEARCH_KEEP, RE_LAST, - NULL) != FAIL) { - done_search = true; - // Stop after passing the time limit. - if (timeout > 0 && profile_passed_limit(start)) { - incomplete = 1; - break; - } - cnt++; - if (ltoreq(lastpos, p)) { - cur = cnt; - if (lt(p, endpos)) { - exact_match = true; - } - } - fast_breakcheck(); - if (maxcount > 0 && cnt > maxcount) { - incomplete = 2; // max count exceeded - break; - } - } - if (got_int) { - cur = -1; // abort - } - if (done_search) { - xfree(lastpat); - lastpat = vim_strsave(spats[last_idx].pat); - chgtick = buf_get_changedtick(curbuf); - lbuf = curbuf; - lastpos = p; - } - } + if (dirc == 0 && !recompute && !EMPTY_POS(lastpos)) { stat->cur = cur; stat->cnt = cnt; stat->exact_match = exact_match; stat->incomplete = incomplete; stat->last_maxcount = last_maxcount; - p_ws = save_ws; + return; + } + last_maxcount = maxcount; + wraparound = ((dirc == '?' && lt(lastpos, p)) + || (dirc == '/' && lt(p, lastpos))); + + // If anything relevant changed the count has to be recomputed. + // STRNICMP ignores case, but we should not ignore case. + // Unfortunately, there is no STRNICMP function. + // XXX: above comment should be "no MB_STRCMP function" ? + if (!(chgtick == buf_get_changedtick(curbuf) + && lastpat != NULL // suppress clang/NULL passed as nonnull parameter + && STRNICMP(lastpat, spats[last_idx].pat, STRLEN(lastpat)) == 0 + && STRLEN(lastpat) == STRLEN(spats[last_idx].pat) + && equalpos(lastpos, *cursor_pos) + && lbuf == curbuf) + || wraparound || cur < 0 || (maxcount > 0 && cur > maxcount) + || recompute) { + cur = 0; + cnt = 0; + exact_match = false; + incomplete = 0; + clearpos(&lastpos); + lbuf = curbuf; + } + + if (equalpos(lastpos, *cursor_pos) && !wraparound + && (dirc == 0 || dirc == '/' ? cur < cnt : cur > 0)) { + cur += dirc == 0 ? 0 : dirc == '/' ? 1 : -1; + } else { + bool done_search = false; + pos_T endpos = { 0, 0, 0 }; + p_ws = false; + if (timeout > 0) { + start = profile_setlimit(timeout); + } + while (!got_int && searchit(curwin, curbuf, &lastpos, &endpos, + FORWARD, NULL, 1, SEARCH_KEEP, RE_LAST, + NULL) != FAIL) { + done_search = true; + // Stop after passing the time limit. + if (timeout > 0 && profile_passed_limit(start)) { + incomplete = 1; + break; + } + cnt++; + if (ltoreq(lastpos, p)) { + cur = cnt; + if (lt(p, endpos)) { + exact_match = true; + } + } + fast_breakcheck(); + if (maxcount > 0 && cnt > maxcount) { + incomplete = 2; // max count exceeded + break; + } + } + if (got_int) { + cur = -1; // abort + } + if (done_search) { + xfree(lastpat); + lastpat = vim_strsave(spats[last_idx].pat); + chgtick = buf_get_changedtick(curbuf); + lbuf = curbuf; + lastpos = p; + } + } + stat->cur = cur; + stat->cnt = cnt; + stat->exact_match = exact_match; + stat->incomplete = incomplete; + stat->last_maxcount = last_maxcount; + p_ws = save_ws; } // "searchcount()" function void f_searchcount(typval_T *argvars, typval_T *rettv, FunPtr fptr) { - pos_T pos = curwin->w_cursor; - char_u *pattern = NULL; - int maxcount = SEARCH_STAT_DEF_MAX_COUNT; - long timeout = SEARCH_STAT_DEF_TIMEOUT; - bool recompute = true; - searchstat_T stat; + pos_T pos = curwin->w_cursor; + char_u *pattern = NULL; + int maxcount = SEARCH_STAT_DEF_MAX_COUNT; + long timeout = SEARCH_STAT_DEF_TIMEOUT; + bool recompute = true; + searchstat_T stat; - tv_dict_alloc_ret(rettv); + tv_dict_alloc_ret(rettv); - if (shortmess(SHM_SEARCHCOUNT)) { // 'shortmess' contains 'S' flag - recompute = true; + if (shortmess(SHM_SEARCHCOUNT)) { // 'shortmess' contains 'S' flag + recompute = true; + } + + if (argvars[0].v_type != VAR_UNKNOWN) { + dict_T *dict; + dictitem_T *di; + listitem_T *li; + bool error = false; + + if (argvars[0].v_type != VAR_DICT || argvars[0].vval.v_dict == NULL) { + EMSG(_(e_dictreq)); + return; } - - if (argvars[0].v_type != VAR_UNKNOWN) { - dict_T *dict; - dictitem_T *di; - listitem_T *li; - bool error = false; - - if (argvars[0].v_type != VAR_DICT || argvars[0].vval.v_dict == NULL) { - EMSG(_(e_dictreq)); + dict = argvars[0].vval.v_dict; + di = tv_dict_find(dict, (const char *)"timeout", -1); + if (di != NULL) { + timeout = (long)tv_get_number_chk(&di->di_tv, &error); + if (error) { return; } - dict = argvars[0].vval.v_dict; - di = tv_dict_find(dict, (const char *)"timeout", -1); - if (di != NULL) { - timeout = (long)tv_get_number_chk(&di->di_tv, &error); + } + di = tv_dict_find(dict, (const char *)"maxcount", -1); + if (di != NULL) { + maxcount = (int)tv_get_number_chk(&di->di_tv, &error); + if (error) { + return; + } + } + di = tv_dict_find(dict, (const char *)"recompute", -1); + if (di != NULL) { + recompute = tv_get_number_chk(&di->di_tv, &error); + if (error) { + return; + } + } + di = tv_dict_find(dict, (const char *)"pattern", -1); + if (di != NULL) { + pattern = (char_u *)tv_get_string_chk(&di->di_tv); + if (pattern == NULL) { + return; + } + } + di = tv_dict_find(dict, (const char *)"pos", -1); + if (di != NULL) { + if (di->di_tv.v_type != VAR_LIST) { + EMSG2(_(e_invarg2), "pos"); + return; + } + if (tv_list_len(di->di_tv.vval.v_list) != 3) { + EMSG2(_(e_invarg2), "List format should be [lnum, col, off]"); + return; + } + li = tv_list_find(di->di_tv.vval.v_list, 0L); + if (li != NULL) { + pos.lnum = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); if (error) { return; } } - di = tv_dict_find(dict, (const char *)"maxcount", -1); - if (di != NULL) { - maxcount = (int)tv_get_number_chk(&di->di_tv, &error); + li = tv_list_find(di->di_tv.vval.v_list, 1L); + if (li != NULL) { + pos.col = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error) - 1; if (error) { return; } } - di = tv_dict_find(dict, (const char *)"recompute", -1); - if (di != NULL) { - recompute = tv_get_number_chk(&di->di_tv, &error); + li = tv_list_find(di->di_tv.vval.v_list, 2L); + if (li != NULL) { + pos.coladd = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); if (error) { return; } } - di = tv_dict_find(dict, (const char *)"pattern", -1); - if (di != NULL) { - pattern = (char_u *)tv_get_string_chk(&di->di_tv); - if (pattern == NULL) { - return; - } - } - di = tv_dict_find(dict, (const char *)"pos", -1); - if (di != NULL) { - if (di->di_tv.v_type != VAR_LIST) { - EMSG2(_(e_invarg2), "pos"); - return; - } - if (tv_list_len(di->di_tv.vval.v_list) != 3) { - EMSG2(_(e_invarg2), "List format should be [lnum, col, off]"); - return; - } - li = tv_list_find(di->di_tv.vval.v_list, 0L); - if (li != NULL) { - pos.lnum = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); - if (error) { - return; - } - } - li = tv_list_find(di->di_tv.vval.v_list, 1L); - if (li != NULL) { - pos.col = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error) - 1; - if (error) { - return; - } - } - li = tv_list_find(di->di_tv.vval.v_list, 2L); - if (li != NULL) { - pos.coladd = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); - if (error) { - return; - } - } - } } + } - save_last_search_pattern(); - if (pattern != NULL) { - if (*pattern == NUL) { - goto the_end; - } - xfree(spats[last_idx].pat); - spats[last_idx].pat = vim_strsave(pattern); - } - if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) { - goto the_end; // the previous pattern was never defined + save_last_search_pattern(); + if (pattern != NULL) { + if (*pattern == NUL) { + goto the_end; } + xfree(spats[last_idx].pat); + spats[last_idx].pat = vim_strsave(pattern); + } + if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) { + goto the_end; // the previous pattern was never defined + } - update_search_stat(0, &pos, &pos, &stat, recompute, maxcount, timeout); + update_search_stat(0, &pos, &pos, &stat, recompute, maxcount, timeout); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("current"), stat.cur); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("total"), stat.cnt); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("exact_match"), stat.exact_match); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("incomplete"), stat.incomplete); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("maxcount"), stat.last_maxcount); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("current"), stat.cur); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("total"), stat.cnt); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("exact_match"), stat.exact_match); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("incomplete"), stat.incomplete); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("maxcount"), stat.last_maxcount); the_end: - restore_last_search_pattern(); + restore_last_search_pattern(); } -/* - * Find identifiers or defines in included files. - * If p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase. - */ -void -find_pattern_in_path( - char_u *ptr, // pointer to search pattern - Direction dir, // direction of expansion - size_t len, // length of search pattern - bool whole, // match whole words only - bool skip_comments, // don't match inside comments - int type, // Type of search; are we looking for a type? - // a macro? - long count, - int action, // What to do when we find it - linenr_T start_lnum, // first line to start searching - linenr_T end_lnum // last line for searching -) +/// Find identifiers or defines in included files. +/// If p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase. +/// +/// @param ptr pointer to search pattern +/// @param dir direction of expansion +/// @param len length of search pattern +/// @param whole match whole words only +/// @param skip_comments don't match inside comments +/// @param type Type of search; are we looking for a type? a macro? +/// @param action What to do when we find it +/// @param start_lnum first line to start searching +/// @param end_lnum last line for searching +void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bool skip_comments, + int type, long count, int action, linenr_T start_lnum, linenr_T end_lnum) { - SearchedFile *files; /* Stack of included files */ - SearchedFile *bigger; /* When we need more space */ + SearchedFile *files; // Stack of included files + SearchedFile *bigger; // When we need more space int max_path_depth = 50; long match_count = 1; - char_u *pat; - char_u *new_fname; - char_u *curr_fname = curbuf->b_fname; - char_u *prev_fname = NULL; + char_u *pat; + char_u *new_fname; + char_u *curr_fname = curbuf->b_fname; + char_u *prev_fname = NULL; linenr_T lnum; int depth; - int depth_displayed; /* For type==CHECK_PATH */ + int depth_displayed; // For type==CHECK_PATH int old_files; int already_searched; - char_u *file_line; - char_u *line; - char_u *p; + char_u *file_line; + char_u *line; + char_u *p; char_u save_char; bool define_matched; regmatch_T regmatch; @@ -4681,10 +4787,10 @@ find_pattern_in_path( bool did_show = false; bool found = false; int i; - char_u *already = NULL; - char_u *startp = NULL; - char_u *inc_opt = NULL; - win_T *curwin_save = NULL; + char_u *already = NULL; + char_u *startp = NULL; + char_u *inc_opt = NULL; + win_T *curwin_save = NULL; const int l_g_do_tagpreview = g_do_tagpreview; regmatch.regprog = NULL; @@ -4696,41 +4802,45 @@ find_pattern_in_path( if (type != CHECK_PATH && type != FIND_DEFINE /* when CONT_SOL is set compare "ptr" with the beginning of the line * is faster than quote_meta/regcomp/regexec "ptr" -- Acevedo */ - && !(compl_cont_status & CONT_SOL) - ) { + && !(compl_cont_status & CONT_SOL)) { pat = xmalloc(len + 5); assert(len <= INT_MAX); sprintf((char *)pat, whole ? "\\<%.*s\\>" : "%.*s", (int)len, ptr); - /* ignore case according to p_ic, p_scs and pat */ + // ignore case according to p_ic, p_scs and pat regmatch.rm_ic = ignorecase(pat); regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); xfree(pat); - if (regmatch.regprog == NULL) + if (regmatch.regprog == NULL) { goto fpip_end; + } } inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc; if (*inc_opt != NUL) { incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0); - if (incl_regmatch.regprog == NULL) + if (incl_regmatch.regprog == NULL) { goto fpip_end; - incl_regmatch.rm_ic = FALSE; /* don't ignore case in incl. pat. */ + } + incl_regmatch.rm_ic = FALSE; // don't ignore case in incl. pat. } if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL)) { def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL ? p_def : curbuf->b_p_def, p_magic ? RE_MAGIC : 0); - if (def_regmatch.regprog == NULL) + if (def_regmatch.regprog == NULL) { goto fpip_end; - def_regmatch.rm_ic = FALSE; /* don't ignore case in define pat. */ + } + def_regmatch.rm_ic = FALSE; // don't ignore case in define pat. } files = xcalloc(max_path_depth, sizeof(SearchedFile)); old_files = max_path_depth; depth = depth_displayed = -1; lnum = start_lnum; - if (end_lnum > curbuf->b_ml.ml_line_count) + if (end_lnum > curbuf->b_ml.ml_line_count) { end_lnum = curbuf->b_ml.ml_line_count; - if (lnum > end_lnum) /* do at least one line */ + } + if (lnum > end_lnum) { // do at least one line lnum = end_lnum; + } line = ml_get(lnum); for (;; ) { @@ -4739,17 +4849,18 @@ find_pattern_in_path( char_u *p_fname = (curr_fname == curbuf->b_fname) ? curbuf->b_ffname : curr_fname; - if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) - /* Use text from '\zs' to '\ze' (or end) of 'include'. */ + if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) { + // Use text from '\zs' to '\ze' (or end) of 'include'. new_fname = find_file_name_in_path(incl_regmatch.startp[0], (size_t)(incl_regmatch.endp[0] - incl_regmatch.startp[0]), FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname); - else - /* Use text after match with 'include'. */ + } else { + // Use text after match with 'include'. new_fname = file_name_in_line(incl_regmatch.endp[0], 0, - FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); + FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); + } already_searched = FALSE; if (new_fname != NULL) { // Check whether we have already searched in this file @@ -4794,15 +4905,17 @@ find_pattern_in_path( did_show = true; while (depth_displayed < depth && !got_int) { ++depth_displayed; - for (i = 0; i < depth_displayed; i++) + for (i = 0; i < depth_displayed; i++) { MSG_PUTS(" "); + } msg_home_replace(files[depth_displayed].name); MSG_PUTS(" -->\n"); } if (!got_int) { /* don't display if 'q' typed for "--more--" message */ - for (i = 0; i <= depth_displayed; i++) + for (i = 0; i <= depth_displayed; i++) { MSG_PUTS(" "); + } if (new_fname != NULL) { /* using "new_fname" is more reliable, e.g., when * 'includeexpr' is set. */ @@ -4814,21 +4927,23 @@ find_pattern_in_path( */ if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) { - /* pattern contains \zs, use the match */ + // pattern contains \zs, use the match p = incl_regmatch.startp[0]; i = (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]); } else { - /* find the file name after the end of the match */ + // find the file name after the end of the match for (p = incl_regmatch.endp[0]; - *p && !vim_isfilec(*p); p++) + *p && !vim_isfilec(*p); p++) { ; - for (i = 0; vim_isfilec(p[i]); i++) + } + for (i = 0; vim_isfilec(p[i]); i++) { ; + } } if (i == 0) { - /* Nothing found, use the rest of the line. */ + // Nothing found, use the rest of the line. p = incl_regmatch.endp[0]; i = (int)STRLEN(p); } @@ -4839,8 +4954,9 @@ find_pattern_in_path( --p; ++i; } - if (p[i] == '"' || p[i] == '>') + if (p[i] == '"' || p[i] == '>') { ++i; + } } save_char = p[i]; p[i] = NUL; @@ -4849,29 +4965,32 @@ find_pattern_in_path( } if (new_fname == NULL && action == ACTION_SHOW_ALL) { - if (already_searched) + if (already_searched) { MSG_PUTS(_(" (Already listed)")); - else + } else { MSG_PUTS(_(" NOT FOUND")); + } } } - ui_flush(); /* output each line directly */ + ui_flush(); // output each line directly } if (new_fname != NULL) { - /* Push the new file onto the file stack */ + // Push the new file onto the file stack if (depth + 1 == old_files) { bigger = xmalloc(max_path_depth * 2 * sizeof(SearchedFile)); - for (i = 0; i <= depth; i++) + for (i = 0; i <= depth; i++) { bigger[i] = files[i]; + } for (i = depth + 1; i < old_files + max_path_depth; i++) { bigger[i].fp = NULL; bigger[i].name = NULL; bigger[i].lnum = 0; bigger[i].matched = FALSE; } - for (i = old_files; i < max_path_depth; i++) + for (i = old_files; i < max_path_depth; i++) { bigger[i + max_path_depth] = files[i]; + } old_files += max_path_depth; max_path_depth *= 2; xfree(files); @@ -4898,10 +5017,9 @@ find_pattern_in_path( } else if (p_verbose >= 5) { verbose_enter(); smsg(_("Searching included file %s"), - (char *)new_fname); + (char *)new_fname); verbose_leave(); } - } } } else { @@ -4919,8 +5037,9 @@ search_line: * don't let it match beyond the end of this identifier. */ p = def_regmatch.endp[0]; - while (*p && !vim_iswordc(*p)) + while (*p && !vim_iswordc(*p)) { p++; + } define_matched = true; } @@ -4930,18 +5049,18 @@ search_line: */ if (def_regmatch.regprog == NULL || define_matched) { if (define_matched - || (compl_cont_status & CONT_SOL) - ) { - /* compare the first "len" chars from "ptr" */ + || (compl_cont_status & CONT_SOL)) { + // compare the first "len" chars from "ptr" startp = skipwhite(p); if (p_ic) { matched = !mb_strnicmp(startp, ptr, len); - } - else + } else { matched = !STRNCMP(startp, ptr, len); + } if (matched && define_matched && whole - && vim_iswordc(startp[len])) + && vim_iswordc(startp[len])) { matched = false; + } } else if (regmatch.regprog != NULL && vim_regexec(®match, line, (colnr_T)(p - line))) { matched = true; @@ -4964,7 +5083,7 @@ search_line: */ p = skipwhite(line); if (matched - || (p[0] == '/' && p[1] == '*') || p[0] == '*') + || (p[0] == '/' && p[1] == '*') || p[0] == '*') { for (p = line; *p && p < startp; ++p) { if (matched && p[0] == '/' @@ -4981,6 +5100,7 @@ search_line: p++; } } + } } } } @@ -4988,35 +5108,39 @@ search_line: if (matched) { if (action == ACTION_EXPAND) { bool cont_s_ipos = false; - char_u *aux; + char_u *aux; - if (depth == -1 && lnum == curwin->w_cursor.lnum) + if (depth == -1 && lnum == curwin->w_cursor.lnum) { break; + } found = true; aux = p = startp; if (compl_cont_status & CONT_ADDING) { p += compl_length; - if (vim_iswordp(p)) + if (vim_iswordp(p)) { goto exit_matched; + } p = find_word_start(p); } p = find_word_end(p); i = (int)(p - aux); if ((compl_cont_status & CONT_ADDING) && i == compl_length) { - /* IOSIZE > compl_length, so the STRNCPY works */ + // IOSIZE > compl_length, so the STRNCPY works STRNCPY(IObuff, aux, i); /* Get the next line: when "depth" < 0 from the current * buffer, otherwise from the included file. Jump to * exit_matched when past the last line. */ if (depth < 0) { - if (lnum >= end_lnum) + if (lnum >= end_lnum) { goto exit_matched; + } line = ml_get(++lnum); } else if (vim_fgets(line = file_line, - LSIZE, files[depth].fp)) + LSIZE, files[depth].fp)) { goto exit_matched; + } /* we read a line, set "already" to check this "line" later * if depth >= 0 we'll increase files[depth].lnum far @@ -5026,9 +5150,10 @@ search_line: p = find_word_end(p); if (p > aux) { if (*aux != ')' && IObuff[i-1] != TAB) { - if (IObuff[i-1] != ' ') + if (IObuff[i-1] != ' ') { IObuff[i++] = ' '; - /* IObuf =~ "\(\k\|\i\).* ", thus i >= 2*/ + } + // IObuf =~ "\(\k\|\i\).* ", thus i >= 2 if (p_js && (IObuff[i-2] == '.' || IObuff[i-2] == '?' @@ -5036,9 +5161,10 @@ search_line: IObuff[i++] = ' '; } } - /* copy as much as possible of the new word */ - if (p - aux >= IOSIZE - i) + // copy as much as possible of the new word + if (p - aux >= IOSIZE - i) { p = aux + IOSIZE - i - 1; + } STRNCPY(IObuff + i, aux, p - aux); i += (int)(p - aux); cont_s_ipos = true; @@ -5046,13 +5172,14 @@ search_line: IObuff[i] = NUL; aux = IObuff; - if (i == compl_length) + if (i == compl_length) { goto exit_matched; + } } - const int add_r = ins_compl_add_infercase( - aux, i, p_ic, curr_fname == curbuf->b_fname ? NULL : curr_fname, - dir, cont_s_ipos); + const int add_r = ins_compl_add_infercase(aux, i, p_ic, + curr_fname == curbuf->b_fname ? NULL : curr_fname, + dir, cont_s_ipos); if (add_r == OK) { // if dir was BACKWARD then honor it just once dir = FORWARD; @@ -5065,11 +5192,13 @@ search_line: gotocmdline(true); // cursor at status line } if (curr_fname != prev_fname) { - if (did_show) - msg_putchar('\n'); /* cursor below last one */ - if (!got_int) /* don't display if 'q' typed + if (did_show) { + msg_putchar('\n'); // cursor below last one + } + if (!got_int) { /* don't display if 'q' typed at "--more--" message */ msg_home_replace_hl(curr_fname); + } prev_fname = curr_fname; } did_show = true; @@ -5082,8 +5211,9 @@ search_line: /* Set matched flag for this file and all the ones that * include it */ - for (i = 0; i <= depth; ++i) + for (i = 0; i <= depth; ++i) { files[i].matched = TRUE; + } } else if (--count <= 0) { found = true; if (depth == -1 && lnum == curwin->w_cursor.lnum @@ -5095,14 +5225,15 @@ search_line: (depth == -1) ? &lnum : &files[depth].lnum, 1L); did_show = true; } else { - /* ":psearch" uses the preview window */ + // ":psearch" uses the preview window if (l_g_do_tagpreview != 0) { curwin_save = curwin; prepare_tagpreview(true); } if (action == ACTION_SPLIT) { - if (win_split(0, 0) == FAIL) + if (win_split(0, 0) == FAIL) { break; + } RESET_BINDING(curwin); } if (depth == -1) { @@ -5134,7 +5265,7 @@ search_line: if (l_g_do_tagpreview != 0 && curwin != curwin_save && win_valid(curwin_save)) { - /* Return cursor to where we were */ + // Return cursor to where we were validate_cursor(); redraw_later(curwin, VALID); win_enter(curwin_save, true); @@ -5154,10 +5285,12 @@ exit_matched: } } line_breakcheck(); - if (action == ACTION_EXPAND) + if (action == ACTION_EXPAND) { ins_compl_check_keys(30, false); - if (got_int || compl_interrupted) + } + if (got_int || compl_interrupted) { break; + } /* * Read the next line. When reading an included file and encountering @@ -5172,55 +5305,62 @@ exit_matched: files[old_files].matched = files[depth].matched; --depth; curr_fname = (depth == -1) ? curbuf->b_fname - : files[depth].name; - if (depth < depth_displayed) + : files[depth].name; + if (depth < depth_displayed) { depth_displayed = depth; + } } - if (depth >= 0) { /* we could read the line */ + if (depth >= 0) { // we could read the line files[depth].lnum++; - /* Remove any CR and LF from the line. */ + // Remove any CR and LF from the line. i = (int)STRLEN(line); - if (i > 0 && line[i - 1] == '\n') + if (i > 0 && line[i - 1] == '\n') { line[--i] = NUL; - if (i > 0 && line[i - 1] == '\r') + } + if (i > 0 && line[i - 1] == '\r') { line[--i] = NUL; + } } else if (!already) { - if (++lnum > end_lnum) + if (++lnum > end_lnum) { break; + } line = ml_get(lnum); } already = NULL; } - /* End of big for (;;) loop. */ + // End of big for (;;) loop. - /* Close any files that are still open. */ + // Close any files that are still open. for (i = 0; i <= depth; i++) { fclose(files[i].fp); xfree(files[i].name); } - for (i = old_files; i < max_path_depth; i++) + for (i = old_files; i < max_path_depth; i++) { xfree(files[i].name); + } xfree(files); if (type == CHECK_PATH) { if (!did_show) { - if (action != ACTION_SHOW_ALL) + if (action != ACTION_SHOW_ALL) { MSG(_("All included files were found")); - else + } else { MSG(_("No included files")); + } } } else if (!found - && action != ACTION_EXPAND - ) { - if (got_int || compl_interrupted) + && action != ACTION_EXPAND) { + if (got_int || compl_interrupted) { EMSG(_(e_interr)); - else if (type == FIND_DEFINE) + } else if (type == FIND_DEFINE) { EMSG(_("E388: Couldn't find definition")); - else + } else { EMSG(_("E389: Couldn't find pattern")); + } } - if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) + if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) { msg_end(); + } fpip_end: xfree(file_line); @@ -5229,11 +5369,11 @@ fpip_end: vim_regfree(def_regmatch.regprog); } -static void show_pat_in_path(char_u *line, int type, bool did_show, int action, - FILE *fp, linenr_T *lnum, long count) +static void show_pat_in_path(char_u *line, int type, bool did_show, int action, FILE *fp, + linenr_T *lnum, long count) FUNC_ATTR_NONNULL_ARG(1, 6) { - char_u *p; + char_u *p; if (did_show) { msg_putchar('\n'); // cursor below last one @@ -5246,11 +5386,13 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, for (;; ) { p = line + STRLEN(line) - 1; if (fp != NULL) { - /* We used fgets(), so get rid of newline at end */ - if (p >= line && *p == '\n') + // We used fgets(), so get rid of newline at end + if (p >= line && *p == '\n') { --p; - if (p >= line && *p == '\r') + } + if (p >= line && *p == '\r') { --p; + } *(p + 1) = NUL; } if (action == ACTION_SHOW_ALL) { @@ -5262,19 +5404,22 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, msg_puts(" "); } msg_prt_line(line, FALSE); - ui_flush(); /* show one line at a time */ + ui_flush(); // show one line at a time - /* Definition continues until line that doesn't end with '\' */ - if (got_int || type != FIND_DEFINE || p < line || *p != '\\') + // Definition continues until line that doesn't end with '\' + if (got_int || type != FIND_DEFINE || p < line || *p != '\\') { break; + } if (fp != NULL) { - if (vim_fgets(line, LSIZE, fp)) /* end of file */ + if (vim_fgets(line, LSIZE, fp)) { // end of file break; + } ++*lnum; } else { - if (++*lnum > curbuf->b_ml.ml_line_count) + if (++*lnum > curbuf->b_ml.ml_line_count) { break; + } line = ml_get(*lnum); } msg_putchar('\n'); diff --git a/src/nvim/window.c b/src/nvim/window.c index 222c1363dc..cb4be36d36 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -73,8 +73,8 @@ static char *m_onlyone = N_("Already only one window"); void do_window(int nchar, long Prenum, int xchar) { long Prenum1; - win_T *wp; - char_u *ptr; + win_T *wp; + char_u *ptr; linenr_T lnum = -1; int type = FIND_DEFINE; size_t len; @@ -287,8 +287,8 @@ newwindow: if (one_window()) { MSG(_(m_onlyone)); } else { - tabpage_T *oldtab = curtab; - tabpage_T *newtab; + tabpage_T *oldtab = curtab; + tabpage_T *newtab; /* First create a new tab with the window, then go back to * the old tab and close the window there. */ @@ -900,8 +900,8 @@ int win_split(int size, int flags) */ int win_split_ins(int size, int flags, win_T *new_wp, int dir) { - win_T *wp = new_wp; - win_T *oldwin; + win_T *wp = new_wp; + win_T *oldwin; int new_size = size; int i; int need_status = 0; @@ -910,7 +910,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) int available; int oldwin_height = 0; int layout; - frame_T *frp, *curfrp, *frp2, *prevfrp; + frame_T *frp, *curfrp, *frp2, *prevfrp; int before; int minheight; int wmh1; @@ -1607,10 +1607,10 @@ int make_windows(int count, bool vertical) */ static void win_exchange(long Prenum) { - frame_T *frp; - frame_T *frp2; - win_T *wp; - win_T *wp2; + frame_T *frp; + frame_T *frp2; + win_T *wp; + win_T *wp2; int temp; if (curwin->w_floating) { @@ -1706,9 +1706,9 @@ static void win_exchange(long Prenum) // if upwards false the first window becomes the second one static void win_rotate(bool upwards, int count) { - win_T *wp1; - win_T *wp2; - frame_T *frp; + win_T *wp1; + win_T *wp2; + frame_T *frp; int n; if (curwin->w_floating) { @@ -1918,7 +1918,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int int n, m; int extra_sep = 0; int wincount, totwincount = 0; - frame_T *fr; + frame_T *fr; int next_curwin_size = 0; int room = 0; int new_size; @@ -2205,7 +2205,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int /// @param keep_curwin don't close `curwin` void close_windows(buf_T *buf, int keep_curwin) { - tabpage_T *tp, *nexttp; + tabpage_T *tp, *nexttp; int h = tabline_height(); ++RedrawingDisabled; @@ -2305,7 +2305,7 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev if (!ONE_WINDOW) { return false; } - buf_T *old_curbuf = curbuf; + buf_T *old_curbuf = curbuf; Terminal *term = win->w_buffer ? win->w_buffer->terminal : NULL; if (term) { @@ -2356,12 +2356,12 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev // Returns FAIL when the window was not closed. int win_close(win_T *win, bool free_buf) { - win_T *wp; + win_T *wp; bool other_buffer = false; bool close_curwin = false; int dir; bool help_window = false; - tabpage_T *prev_curtab = curtab; + tabpage_T *prev_curtab = curtab; frame_T *win_frame = win->w_floating ? NULL : win->w_frame->fr_parent; const bool had_diffmode = win->w_p_diff; @@ -2651,7 +2651,7 @@ static void do_autocmd_winclosed(win_T *win) void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) { int dir; - tabpage_T *ptp = NULL; + tabpage_T *ptp = NULL; bool free_tp = false; // Get here with win->w_buffer == NULL when win_close() detects the tab page @@ -2739,8 +2739,8 @@ void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) /// @return a pointer to the window that got the freed up space. static win_T *win_free_mem(win_T *win, int *dirp, tabpage_T *tp) { - frame_T *frp; - win_T *wp; + frame_T *frp; + win_T *wp; if (!win->w_floating) { // Remove the window and its frame from the tree of frames. @@ -2812,9 +2812,9 @@ void win_free_all(void) /// @return a pointer to the window that got the freed up space. win_T *winframe_remove(win_T *win, int *dirp, tabpage_T *tp) { - frame_T *frp, *frp2, *frp3; - frame_T *frp_close = win->w_frame; - win_T *wp; + frame_T *frp, *frp2, *frp3; + frame_T *frp_close = win->w_frame; + win_T *wp; /* * If there is only one window there is nothing to remove. @@ -2963,7 +2963,7 @@ win_T *winframe_remove(win_T *win, int *dirp, tabpage_T *tp) /// is left over after "win" is closed. static frame_T *win_altframe(win_T *win, tabpage_T *tp) { - frame_T *frp; + frame_T *frp; if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin) { return alt_tabpage()->tp_curwin->w_frame; @@ -3005,7 +3005,7 @@ static frame_T *win_altframe(win_T *win, tabpage_T *tp) */ static tabpage_T *alt_tabpage(void) { - tabpage_T *tp; + tabpage_T *tp; // Use the next tab page if possible. if (curtab->tp_next != NULL) { @@ -3058,7 +3058,7 @@ static bool frame_has_win(const frame_T *frp, const win_T *wp) static void frame_new_height(frame_T *topfrp, int height, bool topfirst, bool wfh) FUNC_ATTR_NONNULL_ALL { - frame_T *frp; + frame_T *frp; int extra_lines; int h; @@ -3214,7 +3214,7 @@ static bool frame_fixed_width(frame_T *frp) */ static void frame_add_statusline(frame_T *frp) { - win_T *wp; + win_T *wp; if (frp->fr_layout == FR_LEAF) { wp = frp->fr_win; @@ -3246,10 +3246,10 @@ static void frame_add_statusline(frame_T *frp) /// may cause the width not to be set. static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, bool wfw) { - frame_T *frp; + frame_T *frp; int extra_cols; int w; - win_T *wp; + win_T *wp; if (topfrp->fr_layout == FR_LEAF) { // Simple case: just one window. @@ -3345,7 +3345,7 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, bool wfw static void frame_add_vsep(const frame_T *frp) FUNC_ATTR_NONNULL_ARG(1) { - win_T *wp; + win_T *wp; if (frp->fr_layout == FR_LEAF) { wp = frp->fr_win; @@ -3397,7 +3397,7 @@ static void frame_fix_height(win_T *wp) */ static int frame_minheight(frame_T *topfrp, win_T *next_curwin) { - frame_T *frp; + frame_T *frp; int m; int n; @@ -3442,7 +3442,7 @@ static int frame_minheight(frame_T *topfrp, win_T *next_curwin) /// @param next_curwin use p_wh and p_wiw for next_curwin static int frame_minwidth(frame_T *topfrp, win_T *next_curwin) { - frame_T *frp; + frame_T *frp; int m, n; if (topfrp->fr_win != NULL) { @@ -3486,8 +3486,8 @@ static int frame_minwidth(frame_T *topfrp, win_T *next_curwin) /// @param forceit always hide all other windows void close_others(int message, int forceit) { - win_T *wp; - win_T *nextwp; + win_T *wp; + win_T *nextwp; int r; if (curwin->w_floating) { @@ -3715,8 +3715,8 @@ void free_tabpage(tabpage_T *tp) /// @return Was the new tabpage created successfully? FAIL or OK. int win_new_tabpage(int after, char_u *filename) { - tabpage_T *old_curtab = curtab; - tabpage_T *newtp; + tabpage_T *old_curtab = curtab; + tabpage_T *newtp; int n; newtp = alloc_tabpage(); @@ -3740,7 +3740,7 @@ int win_new_tabpage(int after, char_u *filename) newtp->tp_next = first_tabpage; first_tabpage = newtp; } else { - tabpage_T *tp = old_curtab; + tabpage_T *tp = old_curtab; if (after > 0) { // Put new tab page before tab page "after". @@ -3887,7 +3887,7 @@ void close_tabpage(tabpage_T *tab) */ tabpage_T *find_tabpage(int n) { - tabpage_T *tp; + tabpage_T *tp; int i = 1; for (tp = first_tabpage; tp != NULL && i != n; tp = tp->tp_next) { @@ -3903,7 +3903,7 @@ tabpage_T *find_tabpage(int n) int tabpage_index(tabpage_T *ftp) { int i = 1; - tabpage_T *tp; + tabpage_T *tp; for (tp = first_tabpage; tp != NULL && tp != ftp; tp = tp->tp_next) { ++i; @@ -3921,7 +3921,7 @@ int tabpage_index(tabpage_T *ftp) /// @param trigger_leave_autocmds when true trigger *Leave autocommands. static int leave_tabpage(buf_T *new_curbuf, bool trigger_leave_autocmds) { - tabpage_T *tp = curtab; + tabpage_T *tp = curtab; reset_VIsual_and_resel(); // stop Visual mode if (trigger_leave_autocmds) { @@ -3960,7 +3960,7 @@ static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, bool trigger_enter_a bool trigger_leave_autocmds) { int old_off = tp->tp_firstwin->w_winrow; - win_T *next_prevwin = tp->tp_prevwin; + win_T *next_prevwin = tp->tp_prevwin; tabpage_T *old_curtab = curtab; curtab = tp; @@ -4055,8 +4055,8 @@ static void tabpage_check_windows(tabpage_T *old_curtab) */ void goto_tabpage(int n) { - tabpage_T *tp = NULL; // shut up compiler - tabpage_T *ttp; + tabpage_T *tp = NULL; // shut up compiler + tabpage_T *ttp; int i; if (text_locked()) { @@ -4215,7 +4215,7 @@ void tabpage_move(int nr) */ void win_goto(win_T *wp) { - win_T *owp = curwin; + win_T *owp = curwin; if (text_locked()) { beep_flush(); @@ -4268,9 +4268,9 @@ tabpage_T *win_find_tabpage(win_T *win) /// @return found window win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count) { - frame_T *fr; - frame_T *nfr; - frame_T *foundfr; + frame_T *fr; + frame_T *nfr; + frame_T *foundfr; foundfr = wp->w_frame; @@ -4351,9 +4351,9 @@ static void win_goto_ver(bool up, long count) /// @return found window win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count) { - frame_T *fr; - frame_T *nfr; - frame_T *foundfr; + frame_T *fr; + frame_T *nfr; + frame_T *foundfr; foundfr = wp->w_frame; @@ -4704,7 +4704,7 @@ void free_wininfo(wininfo_T *wip, buf_T *bp) static void win_free(win_T *wp, tabpage_T *tp) { int i; - wininfo_T *wip; + wininfo_T *wip; pmap_del(handle_T)(&window_handles, wp->handle); clearFolding(wp); @@ -4813,7 +4813,7 @@ void win_free_grid(win_T *wp, bool reinit) */ void win_append(win_T *after, win_T *wp) { - win_T *before; + win_T *before; if (after == NULL) { // after NULL is in front of the first before = firstwin; @@ -5054,8 +5054,8 @@ void win_reconfig_floats(void) */ static void frame_comp_pos(frame_T *topfrp, int *row, int *col) { - win_T *wp; - frame_T *frp; + win_T *wp; + frame_T *frp; int startcol; int startrow; @@ -5156,7 +5156,7 @@ static void frame_setheight(frame_T *curfrp, int height) int take; // number of lines taken from other windows int room_cmdline; // lines available from cmdline int run; - frame_T *frp; + frame_T *frp; int h; int room_reserved; @@ -5353,7 +5353,7 @@ static void frame_setwidth(frame_T *curfrp, int width) int room; // total number of lines available int take; // number of lines taken from other windows int run; - frame_T *frp; + frame_T *frp; int w; int room_reserved; @@ -5520,8 +5520,8 @@ void win_setminwidth(void) /// Status line of dragwin is dragged "offset" lines down (negative is up). void win_drag_status_line(win_T *dragwin, int offset) { - frame_T *curfr; - frame_T *fr; + frame_T *curfr; + frame_T *fr; int room; int row; bool up; // if true, drag status line up, otherwise down @@ -5647,8 +5647,8 @@ void win_drag_status_line(win_T *dragwin, int offset) */ void win_drag_vsep_line(win_T *dragwin, int offset) { - frame_T *curfr; - frame_T *fr; + frame_T *curfr; + frame_T *fr; int room; bool left; // if true, drag separator line left, otherwise right int n; @@ -5980,7 +5980,7 @@ void win_comp_scroll(win_T *wp) void command_height(void) { int h; - frame_T *frp; + frame_T *frp; int old_p_ch = curtab->tp_ch_used; /* Use the value of p_ch that we remembered. This is needed for when the @@ -6072,7 +6072,7 @@ char_u *grab_file_name(long count, linenr_T *file_lnum) int options = FNAME_MESS | FNAME_EXP | FNAME_REL | FNAME_UNESC; if (VIsual_active) { size_t len; - char_u *ptr; + char_u *ptr; if (get_visual_text(NULL, &ptr, &len) == FAIL) { return NULL; } @@ -6114,7 +6114,7 @@ char_u *file_name_at_cursor(int options, long count, linenr_T *file_lnum) char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u *rel_fname, linenr_T *file_lnum) { - char_u *ptr; + char_u *ptr; size_t len; bool in_type = true; bool is_url = false; @@ -6226,8 +6226,8 @@ void last_status(bool morewin) static void last_status_rec(frame_T *fr, bool statusline) { - frame_T *fp; - win_T *wp; + frame_T *fp; + win_T *wp; if (fr->fr_layout == FR_LEAF) { wp = fr->fr_win; @@ -6444,7 +6444,7 @@ static void clear_snapshot_rec(frame_T *fr) /// @param close_curwin closing current window void restore_snapshot(int idx, int close_curwin) { - win_T *wp; + win_T *wp; if (curtab->tp_snapshot[idx] != NULL && curtab->tp_snapshot[idx]->fr_width == topframe->fr_width @@ -6484,8 +6484,8 @@ static int check_snapshot_rec(frame_T *sn, frame_T *fr) */ static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr) { - win_T *wp = NULL; - win_T *wp2; + win_T *wp = NULL; + win_T *wp2; fr->fr_height = sn->fr_height; fr->fr_width = sn->fr_width; @@ -6645,7 +6645,7 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, matchitem_T *prev; matchitem_T *m; int hlg_id; - regprog_T *regprog = NULL; + regprog_T *regprog = NULL; int rtype = SOME_VALID; if (*grp == NUL || (pat != NULL && *pat == NUL)) {