robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
4836ecad1f
master
1// textformat.c: text formatting functions 2 3#include <stdbool.h> 4#include <stdint.h> 5#include <string.h> 6 7#include "nvim/ascii_defs.h" 8#include "nvim/buffer_defs.h" 9#include "nvim/change.h" 10#include "nvim/charset.h" 11#include "nvim/cursor.h" 12#include "nvim/drawscreen.h" 13#include "nvim/eval.h" 14#include "nvim/eval/typval.h" 15#include "nvim/eval/typval_defs.h" 16#include "nvim/eval/vars.h" 17#include "nvim/ex_cmds_defs.h" 18#include "nvim/globals.h" 19#include "nvim/indent.h" 20#include "nvim/indent_c.h" 21#include "nvim/input.h" 22#include "nvim/insert.h" 23#include "nvim/macros_defs.h" 24#include "nvim/mark.h" 25#include "nvim/mbyte.h" 26#include "nvim/memline.h" 27#include "nvim/memory.h" 28#include "nvim/message.h" 29#include "nvim/move.h" 30#include "nvim/ops.h" 31#include "nvim/option.h" 32#include "nvim/option_defs.h" 33#include "nvim/option_vars.h" 34#include "nvim/os/input.h" 35#include "nvim/pos_defs.h" 36#include "nvim/search.h" 37#include "nvim/state_defs.h" 38#include "nvim/strings.h" 39#include "nvim/textformat.h" 40#include "nvim/textobject.h" 41#include "nvim/ui.h" 42#include "nvim/undo.h" 43#include "nvim/vim_defs.h" 44#include "nvim/window.h" 45 46#include "textformat.c.generated.h" 47 48static bool did_add_space = false;///< auto_format() added an extra space 49///< under the cursor 50 51#define WHITECHAR (cc ) (ascii_iswhite(cc) \ 52 && !utf_iscomposing_first(utf_ptr2char((char *)get_cursor_pos_ptr() + 1))) 53 54/// Return true if format option 'x' is in effect. 55/// Take care of no formatting when 'paste' is set. 56bool has_format_option (int x ) 57FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 58{ 59if (p_paste ) { 60return false; 61 } 62return vim_strchr (curbuf -> b_p_fo ,x )!= NULL ; 63} 64 65/// Format text at the current insert position. 66/// 67/// If the INSCHAR_COM_LIST flag is present, then the value of second_indent 68/// will be the comment leader length sent to open_line(). 69/// 70/// @param c character to be inserted (can be NUL) 71void internal_format (int textwidth ,int second_indent ,int flags ,bool format_only ,int c ) 72{ 73int cc ; 74char save_char = NUL ; 75bool haveto_redraw = false; 76const bool fo_ins_blank = has_format_option (kFoInsBlank ); 77const bool fo_multibyte = has_format_option (kFoMbyteBreak ); 78const bool fo_rigor_tw = has_format_option (kFoRigorousTw ); 79const bool fo_white_par = has_format_option (kFoWhitePar ); 80bool first_line = true; 81colnr_T leader_len ; 82bool no_leader = false; 83bool do_comments = (flags & INSCHAR_DO_COM ); 84int has_lbr = curwin -> w_p_lbr ; 85 86// make sure win_charsize() counts correctly 87curwin -> w_p_lbr = false; 88 89// When 'ai' is off we don't want a space under the cursor to be 90// deleted. Replace it with an 'x' temporarily. 91if (!curbuf -> b_p_ai && !(State & VREPLACE_FLAG )) { 92cc = gchar_cursor (); 93if (ascii_iswhite (cc )) { 94save_char = (char )cc ; 95pchar_cursor ('x' ); 96 } 97 } 98 99// Repeat breaking lines, until the current line is not too long. 100while (!got_int ) { 101int startcol ;// Cursor column at entry 102int wantcol ;// column at textwidth border 103int foundcol ;// column for start of spaces 104int end_foundcol = 0 ;// column for start of word 105int orig_col = 0 ; 106char * saved_text = NULL ; 107colnr_T col ; 108bool did_do_comment = false; 109 110colnr_T virtcol = get_nolist_virtcol ()+ char2cells (c != NUL ?c :gchar_cursor ()); 111if (virtcol <= (colnr_T )textwidth ) { 112break ; 113 } 114 115if (no_leader ) { 116do_comments = false; 117 }else if (!(flags & INSCHAR_FORMAT ) 118&& has_format_option (kFoWrapComs )) { 119do_comments = true; 120 } 121 122// Don't break until after the comment leader 123if (do_comments ) { 124char * line = get_cursor_line_ptr (); 125leader_len = get_leader_len (line ,NULL , false, true); 126if (leader_len == 0 && curbuf -> b_p_cin ) { 127// Check for a line comment after code. 128int comment_start = check_linecomment (line ); 129if (comment_start != MAXCOL ) { 130leader_len = get_leader_len (line + comment_start ,NULL , false, true); 131if (leader_len != 0 ) { 132leader_len += comment_start ; 133 } 134 } 135 } 136 }else { 137leader_len = 0 ; 138 } 139 140// If the line doesn't start with a comment leader, then don't 141// start one in a following broken line. Avoids that a %word 142// moved to the start of the next line causes all following lines 143// to start with %. 144if (leader_len == 0 ) { 145no_leader = true; 146 } 147if (!(flags & INSCHAR_FORMAT ) 148&& leader_len == 0 149&& !has_format_option (kFoWrap )) { 150break ; 151 } 152if ((startcol = curwin -> w_cursor .col )== 0 ) { 153break ; 154 } 155 156// find column of textwidth border 157coladvance (curwin , (colnr_T )textwidth ); 158wantcol = curwin -> w_cursor .col ; 159 160curwin -> w_cursor .col = startcol ; 161foundcol = 0 ; 162int skip_pos = 0 ; 163 164// Find position to break at. 165// Stop at first entered white when 'formatoptions' has 'v' 166while ((!fo_ins_blank && !has_format_option (kFoInsVi )) 167|| (flags & INSCHAR_FORMAT ) 168|| curwin -> w_cursor .lnum != Ins .start .lnum 169|| curwin -> w_cursor .col >=Ins .start .col ) { 170if (curwin -> w_cursor .col == startcol && c != NUL ) { 171cc = c ; 172 }else { 173cc = gchar_cursor (); 174 } 175if (WHITECHAR (cc )) { 176// remember position of blank just before text 177colnr_T end_col = curwin -> w_cursor .col ; 178 179// find start of sequence of blanks 180int wcc = 0 ;// counter for whitespace chars 181while (curwin -> w_cursor .col > 0 && WHITECHAR (cc )) { 182dec_cursor (); 183cc = gchar_cursor (); 184 185// Increment count of how many whitespace chars in this 186// group; we only need to know if it's more than one. 187if (wcc < 2 ) { 188wcc ++ ; 189 } 190 } 191if (curwin -> w_cursor .col == 0 && WHITECHAR (cc )) { 192break ;// only spaces in front of text 193 } 194 195// Don't break after a period when 'formatoptions' has 'p' and 196// there are less than two spaces. 197if (has_format_option (kFoPeriodAbbr )&& cc == '.' && wcc < 2 ) { 198continue ; 199 } 200 201// Don't break until after the comment leader 202if (curwin -> w_cursor .col < leader_len ) { 203break ; 204 } 205 206if (has_format_option (kFoOneLetter )) { 207// do not break after one-letter words 208if (curwin -> w_cursor .col == 0 ) { 209break ;// one-letter word at begin 210 } 211// do not break "#a b" when 'tw' is 2 212if (curwin -> w_cursor .col <=leader_len ) { 213break ; 214 } 215col = curwin -> w_cursor .col ; 216dec_cursor (); 217cc = gchar_cursor (); 218 219if (WHITECHAR (cc )) { 220continue ;// one-letter, continue 221 } 222curwin -> w_cursor .col = col ; 223 } 224 225inc_cursor (); 226 227end_foundcol = end_col + 1 ; 228foundcol = curwin -> w_cursor .col ; 229if (curwin -> w_cursor .col <= (colnr_T )wantcol ) { 230break ; 231 } 232 }else if ((cc >=0x100 || !utf_allow_break_before (cc ))&& fo_multibyte ) { 233int ncc ; 234bool allow_break ; 235 236// Break after or before a multi-byte character. 237if (curwin -> w_cursor .col != startcol ) { 238// Don't break until after the comment leader 239if (curwin -> w_cursor .col < leader_len ) { 240break ; 241 } 242col = curwin -> w_cursor .col ; 243inc_cursor (); 244ncc = gchar_cursor (); 245allow_break = utf_allow_break (cc ,ncc ); 246 247// If we have already checked this position, skip! 248if (curwin -> w_cursor .col != skip_pos && allow_break ) { 249foundcol = curwin -> w_cursor .col ; 250end_foundcol = foundcol ; 251if (curwin -> w_cursor .col <= (colnr_T )wantcol ) { 252break ; 253 } 254 } 255curwin -> w_cursor .col = col ; 256 } 257 258if (curwin -> w_cursor .col == 0 ) { 259break ; 260 } 261 262ncc = cc ; 263col = curwin -> w_cursor .col ; 264 265dec_cursor (); 266cc = gchar_cursor (); 267 268if (WHITECHAR (cc )) { 269continue ;// break with space 270 } 271// Don't break until after the comment leader. 272if (curwin -> w_cursor .col < leader_len ) { 273break ; 274 } 275 276curwin -> w_cursor .col = col ; 277skip_pos = curwin -> w_cursor .col ; 278 279allow_break = utf_allow_break (cc ,ncc ); 280 281// Must handle this to respect line break prohibition. 282if (allow_break ) { 283foundcol = curwin -> w_cursor .col ; 284end_foundcol = foundcol ; 285 } 286if (curwin -> w_cursor .col <= (colnr_T )wantcol ) { 287const bool ncc_allow_break = utf_allow_break_before (ncc ); 288 289if (allow_break ) { 290break ; 291 } 292if (!ncc_allow_break && !fo_rigor_tw ) { 293// Enable at most 1 punct hang outside of textwidth. 294if (curwin -> w_cursor .col == startcol ) { 295// We are inserting a non-breakable char, postpone 296// line break check to next insert. 297end_foundcol = foundcol = 0 ; 298break ; 299 } 300 301// Neither cc nor ncc is NUL if we are here, so 302// it's safe to inc_cursor. 303col = curwin -> w_cursor .col ; 304 305inc_cursor (); 306cc = ncc ; 307ncc = gchar_cursor (); 308// handle insert 309ncc = (ncc != NUL ) ?ncc :c ; 310 311allow_break = utf_allow_break (cc ,ncc ); 312 313if (allow_break ) { 314// Break only when we are not at end of line. 315end_foundcol = foundcol = ncc == NUL ?0 :curwin -> w_cursor .col ; 316break ; 317 } 318curwin -> w_cursor .col = col ; 319 } 320 } 321 } 322if (curwin -> w_cursor .col == 0 ) { 323break ; 324 } 325dec_cursor (); 326 } 327 328if (foundcol == 0 ) {// no spaces, cannot break line 329curwin -> w_cursor .col = startcol ; 330break ; 331 } 332 333// Going to break the line, remove any "$" now. 334undisplay_dollar (); 335 336// Offset between cursor position and line break is used by replace 337// stack functions. MODE_VREPLACE does not use this, and backspaces 338// over the text instead. 339if (State & VREPLACE_FLAG ) { 340orig_col = startcol ;// Will start backspacing from here 341 }else { 342replace_offset = startcol - end_foundcol ; 343 } 344 345// adjust startcol for spaces that will be deleted and 346// characters that will remain on top line 347curwin -> w_cursor .col = foundcol ; 348while ((cc = gchar_cursor (),WHITECHAR (cc )) 349&& (!fo_white_par || curwin -> w_cursor .col < startcol )) { 350inc_cursor (); 351 } 352startcol -= curwin -> w_cursor .col ; 353startcol = MAX (startcol ,0 ); 354 355if (State & VREPLACE_FLAG ) { 356// In MODE_VREPLACE state, we will backspace over the text to be 357// wrapped, so save a copy now to put on the next line. 358saved_text = xstrnsave (get_cursor_pos_ptr (), (size_t )get_cursor_pos_len ()); 359curwin -> w_cursor .col = orig_col ; 360saved_text [startcol ]= NUL ; 361 362// Backspace over characters that will move to the next line 363if (!fo_white_par ) { 364backspace_until_column (foundcol ); 365 } 366 }else { 367// put cursor after pos. to break line 368if (!fo_white_par ) { 369curwin -> w_cursor .col = foundcol ; 370 } 371 } 372 373// Split the line just before the margin. 374// Only insert/delete lines, but don't really redraw the window. 375open_line (FORWARD ,OPENLINE_DELSPACES + OPENLINE_MARKFIX 376+ (fo_white_par ?OPENLINE_KEEPTRAIL :0 ) 377+ (do_comments ?OPENLINE_DO_COM :0 ) 378+ OPENLINE_FORMAT 379+ ((flags & INSCHAR_COM_LIST ) ?OPENLINE_COM_LIST :0 ), 380 ((flags & INSCHAR_COM_LIST ) ?second_indent :old_indent ), 381& did_do_comment ); 382if (!(flags & INSCHAR_COM_LIST )) { 383old_indent = 0 ; 384 } 385 386// If a comment leader was inserted, may also do this on a following 387// line. 388if (did_do_comment ) { 389no_leader = false; 390 } 391 392replace_offset = 0 ; 393if (first_line ) { 394if (!(flags & INSCHAR_COM_LIST )) { 395// This section is for auto-wrap of numeric lists. When not 396// in insert mode (i.e. format_lines()), the INSCHAR_COM_LIST 397// flag will be set and open_line() will handle it (as seen 398// above). The code here (and in get_number_indent()) will 399// recognize comments if needed... 400if (second_indent < 0 && has_format_option (kFoQNumber )) { 401second_indent = get_number_indent (curwin -> w_cursor .lnum - 1 ); 402 } 403if (second_indent >=0 ) { 404if (State & VREPLACE_FLAG ) { 405change_indent (INDENT_SET ,second_indent , false, true); 406 }else if (leader_len > 0 && second_indent - leader_len > 0 ) { 407int padding = second_indent - leader_len ; 408 409// We started at the first_line of a numbered list 410// that has a comment. the open_line() function has 411// inserted the proper comment leader and positioned 412// the cursor at the end of the split line. Now we 413// add the additional whitespace needed after the 414// comment leader for the numbered list. 415for (int i = 0 ;i < padding ;i ++ ) { 416ins_str (S_LEN (" " )); 417 } 418 }else { 419set_indent (second_indent ,SIN_CHANGED ); 420 } 421 } 422 } 423first_line = false; 424 } 425 426if (State & VREPLACE_FLAG ) { 427// In MODE_VREPLACE state we have backspaced over the text to be 428// moved, now we re-insert it into the new line. 429ins_bytes (saved_text ); 430xfree (saved_text ); 431 }else { 432// Check if cursor is not past the NUL off the line, cindent 433// may have added or removed indent. 434curwin -> w_cursor .col += startcol ; 435colnr_T len = get_cursor_line_len (); 436curwin -> w_cursor .col = MIN (curwin -> w_cursor .col ,len ); 437 } 438 439haveto_redraw = true; 440set_can_cindent (true); 441// moved the cursor, don't autoindent or cindent now 442Ins .did_ai = false; 443Ins .did_si = false; 444Ins .can_si = false; 445Ins .can_si_back = false; 446line_breakcheck (); 447 } 448 449if (save_char != NUL ) {// put back space after cursor 450pchar_cursor (save_char ); 451 } 452 453curwin -> w_p_lbr = has_lbr ; 454 455if (!format_only && haveto_redraw ) { 456update_topline (curwin ); 457redraw_curbuf_later (UPD_VALID ); 458 } 459} 460 461/// Blank lines, and lines containing only the comment leader, are left 462/// untouched by the formatting. The function returns true in this 463/// case. It also returns true when a line starts with the end of a comment 464/// ('e' in comment flags), so that this line is skipped, and not joined to the 465/// previous line. A new paragraph starts after a blank line, or when the 466/// comment leader changes. 467static int fmt_check_par (linenr_T lnum ,int * leader_len ,char ** leader_flags ,bool do_comments ) 468{ 469char * flags = NULL ;// init for GCC 470char * ptr = ml_get (lnum ); 471if (do_comments ) { 472* leader_len = get_leader_len (ptr ,leader_flags , false, true); 473 }else { 474* leader_len = 0 ; 475 } 476 477if (* leader_len > 0 ) { 478// Search for 'e' flag in comment leader flags. 479flags = * leader_flags ; 480while (* flags && * flags != ':' && * flags != COM_END ) { 481flags ++ ; 482 } 483 } 484 485return * skipwhite (ptr + * leader_len )== NUL 486|| (* leader_len > 0 && * flags == COM_END ) 487|| startPS (lnum ,NUL , false); 488} 489 490/// @return true if line "lnum" ends in a white character. 491static bool ends_in_white (linenr_T lnum ) 492{ 493char * s = ml_get (lnum ); 494 495if (* s == NUL ) { 496return false; 497 } 498colnr_T l = ml_get_len (lnum )- 1 ; 499return ascii_iswhite ((uint8_t )s [l ]); 500} 501 502/// @return true if the two comment leaders given are the same. 503/// 504/// @param lnum The first line. White-space is ignored. 505/// 506/// @note the whole of 'leader1' must match 'leader2_len' characters from 'leader2'. 507static bool same_leader (linenr_T lnum ,int leader1_len ,char * leader1_flags ,int leader2_len , 508char * leader2_flags ) 509{ 510int idx1 = 0 ; 511int idx2 = 0 ; 512 513if (leader1_len == 0 ) { 514return leader2_len == 0 ; 515 } 516 517// If first leader has 'f' flag, the lines can be joined only if the 518// second line does not have a leader. 519// If first leader has 'e' flag, the lines can never be joined. 520// If first leader has 's' flag, the lines can only be joined if there is 521// some text after it and the second line has the 'm' flag. 522if (leader1_flags != NULL ) { 523for (char * p = leader1_flags ;* p && * p != ':' ;p ++ ) { 524if (* p == COM_FIRST ) { 525return leader2_len == 0 ; 526 } 527if (* p == COM_END ) { 528return false; 529 } 530if (* p == COM_START ) { 531int line_len = ml_get_len (lnum ); 532if (line_len <=leader1_len ) { 533return false; 534 } 535if (leader2_flags == NULL || leader2_len == 0 ) { 536return false; 537 } 538for (p = leader2_flags ;* p && * p != ':' ;p ++ ) { 539if (* p == COM_MIDDLE ) { 540return true; 541 } 542 } 543return false; 544 } 545 } 546 } 547 548// Get current line and next line, compare the leaders. 549// The first line has to be saved, only one line can be locked at a time. 550char * line1 = xstrnsave (ml_get (lnum ), (size_t )ml_get_len (lnum )); 551for (idx1 = 0 ;ascii_iswhite (line1 [idx1 ]);idx1 ++ ) {} 552char * line2 = ml_get (lnum + 1 ); 553for (idx2 = 0 ;idx2 < leader2_len ;idx2 ++ ) { 554if (!ascii_iswhite (line2 [idx2 ])) { 555if (line1 [idx1 ++ ]!= line2 [idx2 ]) { 556break ; 557 } 558 }else { 559while (ascii_iswhite (line1 [idx1 ])) { 560idx1 ++ ; 561 } 562 } 563 } 564xfree (line1 ); 565 566return idx2 == leader2_len && idx1 == leader1_len ; 567} 568 569/// Used for auto-formatting. 570/// 571/// @return true when a paragraph starts in line "lnum". 572/// false when the previous line is in the same paragraph. 573static bool paragraph_start (linenr_T lnum ) 574{ 575int leader_len = 0 ;// leader len of current line 576char * leader_flags = NULL ;// flags for leader of current line 577int next_leader_len = 0 ;// leader len of next line 578char * next_leader_flags = NULL ;// flags for leader of next line 579 580if (lnum <=1 ) { 581return true;// start of the file 582 } 583char * p = ml_get (lnum - 1 ); 584if (* p == NUL ) { 585return true;// after empty line 586 } 587const bool do_comments = has_format_option (kFoQComs );// format comments 588if (fmt_check_par (lnum - 1 ,& leader_len ,& leader_flags ,do_comments )) { 589return true;// after non-paragraph line 590 } 591 592if (fmt_check_par (lnum ,& next_leader_len ,& next_leader_flags ,do_comments )) { 593return true;// "lnum" is not a paragraph line 594 } 595 596if (has_format_option (kFoWhitePar )&& !ends_in_white (lnum - 1 )) { 597return true;// missing trailing space in previous line. 598 } 599if (has_format_option (kFoQNumber )&& (get_number_indent (lnum )> 0 )) { 600return true;// numbered item starts in "lnum". 601 } 602if (!same_leader (lnum - 1 ,leader_len ,leader_flags , 603next_leader_len ,next_leader_flags )) { 604return true;// change of comment leader. 605 } 606return false; 607} 608 609/// Called after inserting or deleting text: When 'formatoptions' includes the 610/// 'a' flag format from the current line until the end of the paragraph. 611/// Keep the cursor at the same position relative to the text. 612/// The caller must have saved the cursor line for undo, following ones will be 613/// saved here. 614/// 615/// @param trailblank when true also format with trailing blank 616/// @param prev_line may start in previous line 617void auto_format (bool trailblank ,bool prev_line ) 618{ 619if (!has_format_option (kFoAuto )) { 620return ; 621 } 622 623pos_T pos = curwin -> w_cursor ; 624char * old = get_cursor_line_ptr (); 625 626// may remove added space 627check_auto_format (false); 628 629// Don't format in Insert mode when the cursor is on a trailing blank, the 630// user might insert normal text next. Also skip formatting when "1" is 631// in 'formatoptions' and there is a single character before the cursor. 632// Otherwise the line would be broken and when typing another non-white 633// next they are not joined back together. 634bool wasatend = (pos .col == get_cursor_line_len ()); 635if (* old != NUL && !trailblank && wasatend ) { 636dec_cursor (); 637int cc = gchar_cursor (); 638if (!WHITECHAR (cc )&& curwin -> w_cursor .col > 0 639&& has_format_option (kFoOneLetter )) { 640dec_cursor (); 641 } 642cc = gchar_cursor (); 643if (WHITECHAR (cc )) { 644curwin -> w_cursor = pos ; 645return ; 646 } 647curwin -> w_cursor = pos ; 648 } 649 650// Also skip formatting when the user just typed whitespace in the 651// middle of the line. Reformatting would join all paragraph lines and 652// re-wrap, consuming the space at the line break point via 653// OPENLINE_DELSPACES. By deferring, the next non-whitespace character 654// will be inserted adjacent to the space, keeping it protected from 655// being consumed at a line break. auto_format() will then reformat 656// properly on the next keystroke. 657if (* old != NUL && !trailblank && !wasatend && pos .col > 0 658&& (State & MODE_INSERT )) { 659char * line = get_cursor_line_ptr (); 660if (WHITECHAR (line [pos .col - 1 ])) { 661curwin -> w_cursor = pos ; 662return ; 663 } 664 } 665 666// With the 'c' flag in 'formatoptions' and 't' missing: only format 667// comments. 668if (has_format_option (kFoWrapComs )&& !has_format_option (kFoWrap ) 669&& get_leader_len (old ,NULL , false, true)== 0 ) { 670return ; 671 } 672 673// May start formatting in a previous line, so that after "x" a word is 674// moved to the previous line if it fits there now. Only when this is not 675// the start of a paragraph. 676if (prev_line && !paragraph_start (curwin -> w_cursor .lnum )) { 677curwin -> w_cursor .lnum -- ; 678if (u_save_cursor ()== FAIL ) { 679return ; 680 } 681 } 682 683// Do the formatting and restore the cursor position. "saved_cursor" will 684// be adjusted for the text formatting. 685saved_cursor = pos ; 686format_lines (-1 , false); 687curwin -> w_cursor = saved_cursor ; 688saved_cursor .lnum = 0 ; 689 690if (curwin -> w_cursor .lnum > curbuf -> b_ml .ml_line_count ) { 691// "cannot happen" 692curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 693coladvance (curwin ,MAXCOL ); 694 }else { 695check_cursor_col (curwin ); 696 } 697 698// Insert mode: If the cursor is now after the end of the line while it 699// previously wasn't, the line was broken. Because of the rule above we 700// need to add a space when 'w' is in 'formatoptions' to keep a paragraph 701// formatted. 702if (!wasatend && has_format_option (kFoWhitePar )) { 703char * linep = get_cursor_line_ptr (); 704colnr_T len = get_cursor_line_len (); 705if (curwin -> w_cursor .col == len ) { 706char * plinep = xstrnsave (linep , (size_t )len + 2 ); 707plinep [len ]= ' ' ; 708plinep [len + 1 ]= NUL ; 709ml_replace (curwin -> w_cursor .lnum ,plinep , false); 710// remove the space later 711did_add_space = true; 712 }else { 713// may remove added space 714check_auto_format (false); 715 } 716 } 717 718check_cursor (curwin ); 719} 720 721/// When an extra space was added to continue a paragraph for auto-formatting, 722/// delete it now. The space must be under the cursor, just after the insert 723/// position. 724/// 725/// @param end_insert true when ending Insert mode 726void check_auto_format (bool end_insert ) 727{ 728if (!did_add_space ) { 729return ; 730 } 731 732int cc = gchar_cursor (); 733if (!WHITECHAR (cc )) { 734// Somehow the space was removed already. 735did_add_space = false; 736 }else { 737int c = ' ' ; 738if (!end_insert ) { 739inc_cursor (); 740c = gchar_cursor (); 741dec_cursor (); 742 } 743if (c != NUL ) { 744// The space is no longer at the end of the line, delete it. 745del_char (false); 746did_add_space = false; 747 } 748 } 749} 750 751/// Find out textwidth to be used for formatting: 752/// if 'textwidth' option is set, use it 753/// else if 'wrapmargin' option is set, use curwin->w_view_width-'wrapmargin' 754/// if invalid value, use 0. 755/// Set default to window width (maximum 79) for "gq" operator. 756/// 757/// @param ff force formatting (for "gq" command) 758int comp_textwidth (bool ff ) 759{ 760int textwidth = (int )curbuf -> b_p_tw ; 761if (textwidth == 0 && curbuf -> b_p_wm ) { 762// The width is the window width minus 'wrapmargin' minus all the 763// things that add to the margin. 764textwidth = curwin -> w_view_width - (int )curbuf -> b_p_wm ; 765textwidth -= win_fdccol_count (curwin ); 766textwidth -= curwin -> w_scwidth ; 767 768if (curwin -> w_p_nu || curwin -> w_p_rnu ) { 769textwidth -= 8 ; 770 } 771 } 772textwidth = MAX (textwidth ,0 ); 773if (ff && textwidth == 0 ) { 774textwidth = MIN (curwin -> w_view_width - 1 ,79 ); 775 } 776return textwidth ; 777} 778 779/// Implementation of the format operator 'gq'. 780/// 781/// @param keep_cursor keep cursor on same text char 782void op_format (oparg_T * oap ,bool keep_cursor ) 783{ 784linenr_T old_line_count = curbuf -> b_ml .ml_line_count ; 785 786// Place the cursor where the "gq" or "gw" command was given, so that "u" 787// can put it back there. 788curwin -> w_cursor = oap -> cursor_start ; 789 790if (u_save ((linenr_T )(oap -> start .lnum - 1 ), 791 (linenr_T )(oap -> end .lnum + 1 ))== FAIL ) { 792return ; 793 } 794curwin -> w_cursor = oap -> start ; 795 796if (oap -> is_VIsual ) { 797// When there is no change: need to remove the Visual selection 798redraw_curbuf_later (UPD_INVERTED ); 799 } 800 801if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 802// Set '[ mark at the start of the formatted area 803curbuf -> b_op_start = oap -> start ; 804 } 805 806// For "gw" remember the cursor position and put it back below (adjusted 807// for joined and split lines). 808if (keep_cursor ) { 809saved_cursor = oap -> cursor_start ; 810 } 811 812format_lines (oap -> line_count ,keep_cursor ); 813 814// Leave the cursor at the first non-blank of the last formatted line. 815// If the cursor was moved one line back (e.g. with "Q}") go to the next 816// line, so "." will do the next lines. 817if (oap -> end_adjusted && curwin -> w_cursor .lnum < curbuf -> b_ml .ml_line_count ) { 818curwin -> w_cursor .lnum ++ ; 819 } 820beginline (BL_WHITE |BL_FIX ); 821old_line_count = curbuf -> b_ml .ml_line_count - old_line_count ; 822msgmore (old_line_count ); 823 824if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 825// put '] mark on the end of the formatted area 826curbuf -> b_op_end = curwin -> w_cursor ; 827 } 828 829if (keep_cursor ) { 830curwin -> w_cursor = saved_cursor ; 831saved_cursor .lnum = 0 ; 832 833// formatting may have made the cursor position invalid 834check_cursor (curwin ); 835 } 836 837if (oap -> is_VIsual ) { 838FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 839if (wp -> w_old_cursor_lnum != 0 ) { 840// When lines have been inserted or deleted, adjust the end of 841// the Visual area to be redrawn. 842if (wp -> w_old_cursor_lnum > wp -> w_old_visual_lnum ) { 843wp -> w_old_cursor_lnum += old_line_count ; 844 }else { 845wp -> w_old_visual_lnum += old_line_count ; 846 } 847 } 848 } 849 } 850} 851 852/// Implementation of the format operator 'gq' for when using 'formatexpr'. 853void op_formatexpr (oparg_T * oap ) 854{ 855if (oap -> is_VIsual ) { 856// When there is no change: need to remove the Visual selection 857redraw_curbuf_later (UPD_INVERTED ); 858 } 859 860if (fex_format (oap -> start .lnum ,oap -> line_count ,NUL )!= 0 ) { 861// As documented: when 'formatexpr' returns non-zero fall back to 862// internal formatting. 863op_format (oap , false); 864 } 865} 866 867/// @param c character to be inserted 868int fex_format (linenr_T lnum ,long count ,int c ) 869{ 870bool use_sandbox = was_set_insecurely (curwin ,kOptFormatexpr ,OPT_LOCAL ); 871const sctx_T save_sctx = current_sctx ; 872 873// Set v:lnum to the first line number and v:count to the number of lines. 874// Set v:char to the character to be inserted (can be NUL). 875set_vim_var_nr (VV_LNUM , (varnumber_T )lnum ); 876set_vim_var_nr (VV_COUNT , (varnumber_T )count ); 877set_vim_var_char (c ); 878 879current_sctx = curbuf -> b_p_script_ctx [kBufOptFormatexpr ]; 880 881// 'formatexpr' may modify the buffer, so it runs without textlock. 882int r = eval_expr_option_number (& curbuf -> b_p_fex ,use_sandbox ); 883 884set_vim_var_string (VV_CHAR ,NULL ,-1 ); 885current_sctx = save_sctx ; 886 887return r ; 888} 889 890/// @param line_count number of lines to format, starting at the cursor position. 891/// when negative, format until the end of the paragraph. 892/// 893/// Lines after the cursor line are saved for undo, caller must have saved the 894/// first line. 895/// 896/// @param avoid_fex don't use 'formatexpr' 897void format_lines (linenr_T line_count ,bool avoid_fex ) 898{ 899bool is_not_par ;// current line not part of parag. 900bool next_is_not_par ;// next line not part of paragraph 901bool is_end_par ;// at end of paragraph 902bool prev_is_end_par = false;// prev. line not part of parag. 903bool next_is_start_par = false; 904int leader_len = 0 ;// leader len of current line 905int next_leader_len ;// leader len of next line 906char * leader_flags = NULL ;// flags for leader of current line 907char * next_leader_flags = NULL ;// flags for leader of next line 908bool advance = true; 909int second_indent = -1 ;// indent for second line (comment aware) 910bool first_par_line = true; 911int smd_save ; 912long count ; 913bool need_set_indent = true;// set indent of next paragraph 914linenr_T first_line = curwin -> w_cursor .lnum ; 915bool force_format = false; 916const int old_State = State ; 917 918// length of a line to force formatting: 3 * 'tw' 919const int max_len = comp_textwidth (true)* 3 ; 920 921// check for 'q', '2', 'n' and 'w' in 'formatoptions' 922const bool do_comments = has_format_option (kFoQComs );// format comments 923int do_comments_list = 0 ;// format comments with 'n' or '2' 924const bool do_second_indent = has_format_option (kFoQSecond ); 925const bool do_number_indent = has_format_option (kFoQNumber ); 926const bool do_trail_white = has_format_option (kFoWhitePar ); 927 928// Get info about the previous and current line. 929if (curwin -> w_cursor .lnum > 1 ) { 930is_not_par = fmt_check_par (curwin -> w_cursor .lnum - 1 , 931& leader_len ,& leader_flags ,do_comments ); 932 }else { 933is_not_par = true; 934 } 935next_is_not_par = fmt_check_par (curwin -> w_cursor .lnum , 936& next_leader_len ,& next_leader_flags ,do_comments ); 937is_end_par = (is_not_par || next_is_not_par ); 938if (!is_end_par && do_trail_white ) { 939is_end_par = !ends_in_white (curwin -> w_cursor .lnum - 1 ); 940 } 941 942curwin -> w_cursor .lnum -- ; 943for (count = line_count ;count != 0 && !got_int ;count -- ) { 944// Advance to next paragraph. 945if (advance ) { 946curwin -> w_cursor .lnum ++ ; 947prev_is_end_par = is_end_par ; 948is_not_par = next_is_not_par ; 949leader_len = next_leader_len ; 950leader_flags = next_leader_flags ; 951 } 952 953// The last line to be formatted. 954if (count == 1 || curwin -> w_cursor .lnum == curbuf -> b_ml .ml_line_count ) { 955next_is_not_par = true; 956next_leader_len = 0 ; 957next_leader_flags = NULL ; 958 }else { 959next_is_not_par = fmt_check_par (curwin -> w_cursor .lnum + 1 , 960& next_leader_len ,& next_leader_flags ,do_comments ); 961if (do_number_indent ) { 962next_is_start_par = 963 (get_number_indent (curwin -> w_cursor .lnum + 1 )> 0 ); 964 } 965 } 966advance = true; 967is_end_par = (is_not_par || next_is_not_par || next_is_start_par ); 968if (!is_end_par && do_trail_white ) { 969is_end_par = !ends_in_white (curwin -> w_cursor .lnum ); 970 } 971 972// Skip lines that are not in a paragraph. 973if (is_not_par ) { 974if (line_count < 0 ) { 975break ; 976 } 977 }else { 978// For the first line of a paragraph, check indent of second line. 979// Don't do this for comments and empty lines. 980if (first_par_line 981&& (do_second_indent || do_number_indent ) 982&& prev_is_end_par 983&& curwin -> w_cursor .lnum < curbuf -> b_ml .ml_line_count ) { 984if (do_second_indent && !LINEEMPTY (curwin -> w_cursor .lnum + 1 )) { 985if (leader_len == 0 && next_leader_len == 0 ) { 986// no comment found 987second_indent = 988get_indent_lnum (curwin -> w_cursor .lnum + 1 ); 989 }else { 990second_indent = next_leader_len ; 991do_comments_list = 1 ; 992 } 993 }else if (do_number_indent ) { 994if (leader_len == 0 && next_leader_len == 0 ) { 995// no comment found 996second_indent = 997get_number_indent (curwin -> w_cursor .lnum ); 998 }else { 999// get_number_indent() is now "comment aware"... 1000second_indent = 1001get_number_indent (curwin -> w_cursor .lnum ); 1002do_comments_list = 1 ; 1003 } 1004 } 1005 } 1006 1007// When the comment leader changes, it's the end of the paragraph. 1008if (curwin -> w_cursor .lnum >=curbuf -> b_ml .ml_line_count 1009|| !same_leader (curwin -> w_cursor .lnum , 1010leader_len ,leader_flags , 1011next_leader_len , 1012next_leader_flags )) { 1013// Special case: If the next line starts with a line comment 1014// and this line has a line comment after some text, the 1015// paragraph doesn't really end. 1016if (next_leader_flags == NULL 1017|| strncmp (next_leader_flags ,"://" ,3 )!= 0 1018|| check_linecomment (get_cursor_line_ptr ())== MAXCOL ) { 1019is_end_par = true; 1020 } 1021 } 1022 1023// If we have got to the end of a paragraph, or the line is 1024// getting long, format it. 1025if (is_end_par || force_format ) { 1026if (need_set_indent ) { 1027int indent = 0 ;// amount of indent needed 1028 1029// Replace indent in first line of a paragraph with minimal 1030// number of tabs and spaces, according to current options. 1031// For the very first formatted line keep the current 1032// indent. 1033if (curwin -> w_cursor .lnum == first_line ) { 1034indent = get_indent (); 1035 }else if (curbuf -> b_p_lisp ) { 1036indent = get_lisp_indent (); 1037 }else { 1038if (cindent_on ()) { 1039indent = curbuf -> b_p_inde .type != kCallbackNone ?get_expr_indent () :get_c_indent (); 1040 }else { 1041indent = get_indent (); 1042 } 1043 } 1044set_indent (indent ,SIN_CHANGED ); 1045 } 1046 1047// put cursor on last non-space 1048State = MODE_NORMAL ;// don't go past end-of-line 1049coladvance (curwin ,MAXCOL ); 1050while (curwin -> w_cursor .col && ascii_isspace (gchar_cursor ())) { 1051dec_cursor (); 1052 } 1053 1054// do the formatting, without 'showmode' 1055State = MODE_INSERT ;// for open_line() 1056smd_save = p_smd ; 1057p_smd = false; 1058 1059insertchar (NUL ,INSCHAR_FORMAT 1060+ (do_comments ?INSCHAR_DO_COM :0 ) 1061+ (do_comments && do_comments_list ?INSCHAR_COM_LIST :0 ) 1062+ (avoid_fex ?INSCHAR_NO_FEX :0 ),second_indent ); 1063 1064State = old_State ; 1065p_smd = smd_save ; 1066// Cursor shape may have been updated (e.g. by :normal) in insertchar(), 1067// so it needs to be updated here. 1068ui_cursor_shape (); 1069 1070second_indent = -1 ; 1071// at end of par.: need to set indent of next par. 1072need_set_indent = is_end_par ; 1073if (is_end_par ) { 1074// When called with a negative line count, break at the 1075// end of the paragraph. 1076if (line_count < 0 ) { 1077break ; 1078 } 1079first_par_line = true; 1080 } 1081force_format = false; 1082 } 1083 1084// When still in same paragraph, join the lines together. But 1085// first delete the leader from the second line. 1086if (!is_end_par ) { 1087advance = false; 1088curwin -> w_cursor .lnum ++ ; 1089curwin -> w_cursor .col = 0 ; 1090if (line_count < 0 && u_save_cursor ()== FAIL ) { 1091break ; 1092 } 1093if (next_leader_len > 0 ) { 1094del_bytes (next_leader_len , false, false); 1095mark_col_adjust (curwin -> w_cursor .lnum ,0 ,0 ,- next_leader_len ,0 ); 1096 }else if (second_indent > 0 ) {// the "leader" for kFoQSecond 1097int indent = (int )getwhitecols_curline (); 1098 1099if (indent > 0 ) { 1100del_bytes (indent , false, false); 1101mark_col_adjust (curwin -> w_cursor .lnum ,0 ,0 ,- indent ,0 ); 1102 } 1103 } 1104curwin -> w_cursor .lnum -- ; 1105if (do_join (2 , true, false, false, false)== FAIL ) { 1106beep_flush (); 1107break ; 1108 } 1109first_par_line = false; 1110// If the line is getting long, format it next time 1111force_format = get_cursor_line_len ()> max_len ; 1112 } 1113 } 1114line_breakcheck (); 1115 } 1116}