robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <stdbool.h> 3#include <stdint.h> 4#include <stdlib.h> 5#include <string.h> 6 7#include "nvim/ascii_defs.h" 8#include "nvim/assert_defs.h" 9#include "nvim/buffer.h" 10#include "nvim/buffer_defs.h" 11#include "nvim/change.h" 12#include "nvim/charset.h" 13#include "nvim/cursor.h" 14#include "nvim/drawscreen.h" 15#include "nvim/errors.h" 16#include "nvim/eval.h" 17#include "nvim/eval/typval.h" 18#include "nvim/eval/typval_defs.h" 19#include "nvim/eval/vars.h" 20#include "nvim/ex_cmds_defs.h" 21#include "nvim/ex_docmd.h" 22#include "nvim/extmark.h" 23#include "nvim/extmark_defs.h" 24#include "nvim/gettext_defs.h" 25#include "nvim/globals.h" 26#include "nvim/indent.h" 27#include "nvim/indent_c.h" 28#include "nvim/insert.h" 29#include "nvim/mark_defs.h" 30#include "nvim/mbyte.h" 31#include "nvim/mbyte_defs.h" 32#include "nvim/memline.h" 33#include "nvim/memory.h" 34#include "nvim/message.h" 35#include "nvim/move.h" 36#include "nvim/ops.h" 37#include "nvim/option.h" 38#include "nvim/option_defs.h" 39#include "nvim/option_vars.h" 40#include "nvim/optionstr.h" 41#include "nvim/os/input.h" 42#include "nvim/plines.h" 43#include "nvim/pos_defs.h" 44#include "nvim/regexp.h" 45#include "nvim/regexp_defs.h" 46#include "nvim/search.h" 47#include "nvim/state_defs.h" 48#include "nvim/strings.h" 49#include "nvim/textformat.h" 50#include "nvim/types_defs.h" 51#include "nvim/undo.h" 52#include "nvim/vim_defs.h" 53 54#include "indent.c.generated.h" 55 56#include "options_keysets.generated.h" 57 58/// Set the integer values corresponding to the string setting of 'vartabstop'. 59/// "array" will be set, caller must free it if needed. 60/// 61/// @return false for an error. 62bool tabstop_set (char * var ,colnr_T ** array ) 63{ 64int valcount = 1 ; 65 66if (var [0 ]== NUL || (var [0 ]== '0' && var [1 ]== NUL )) { 67* array = NULL ; 68return true; 69 } 70 71for (char * cp = var ;* cp != NUL ;cp ++ ) { 72if (cp == var || cp [-1 ]== ',' ) { 73char * end = cp ; 74 75// Use def=1 so that overflow/too-large values pass this check and are 76// instead rejected by the "n > TABSTOP_MAX" check in the loop below. 77if (getdigits (& end , false,1 ) <=0 ) { 78if (cp != end ) { 79emsg (_ (e_positive )); 80 }else { 81semsg (_ (e_invarg2 ),cp ); 82 } 83return false; 84 } 85 } 86 87if (ascii_isdigit (* cp )) { 88continue ; 89 } 90if (cp [0 ]== ',' && cp > var && cp [-1 ]!= ',' && cp [1 ]!= NUL ) { 91valcount ++ ; 92continue ; 93 } 94semsg (_ (e_invarg2 ),var ); 95return false; 96 } 97 98* array = (colnr_T * )xmalloc ((unsigned )(valcount + 1 )* sizeof (int )); 99 (* array )[0 ]= (colnr_T )valcount ; 100 101int t = 1 ; 102for (char * cp = var ;* cp != NUL ;) { 103int n = atoi (cp ); 104 105// Catch negative values, overflow and ridiculous big values. 106if (n <=0 || n > TABSTOP_MAX ) { 107semsg (_ (e_invarg2 ),cp ); 108XFREE_CLEAR (* array ); 109return false; 110 } 111 (* array )[t ++ ]= n ; 112while (* cp != NUL && * cp != ',' ) { 113cp ++ ; 114 } 115if (* cp != NUL ) { 116cp ++ ; 117 } 118 } 119 120return true; 121} 122 123/// Calculate the number of screen spaces a tab will occupy. 124/// If "vts" is set then the tab widths are taken from that array, 125/// otherwise the value of ts is used. 126int tabstop_padding (colnr_T col ,OptInt ts_arg ,const colnr_T * vts ) 127FUNC_ATTR_PURE 128{ 129OptInt ts = ts_arg == 0 ?8 :ts_arg ; 130colnr_T tabcol = 0 ; 131int t ; 132int padding = 0 ; 133 134if (vts == NULL || vts [0 ]== 0 ) { 135return (int )(ts - (col %ts )); 136 } 137 138const int tabcount = vts [0 ]; 139 140for (t = 1 ;t <=tabcount ;t ++ ) { 141tabcol += vts [t ]; 142if (tabcol > col ) { 143padding = tabcol - col ; 144break ; 145 } 146 } 147if (t > tabcount ) { 148padding = vts [tabcount ]- ((col - tabcol ) %vts [tabcount ]); 149 } 150 151return padding ; 152} 153 154/// Find the size of the tab that covers a particular column. 155/// 156/// If this is being called as part of a shift operation, col is not the cursor 157/// column but is the column number to the left of the first non-whitespace 158/// character in the line. If the shift is to the left (left == true), then 159/// return the size of the tab interval to the left of the column. 160int tabstop_at (colnr_T col ,OptInt ts ,const colnr_T * vts ,bool left ) 161{ 162if (vts == NULL || vts [0 ]== 0 ) { 163return (int )ts ; 164 } 165 166colnr_T tabcol = 0 ;// Column of the tab stop under consideration. 167int t ;// Tabstop index in the list of variable tab stops. 168int tab_size = 0 ;// Size of the tab stop interval to the right or left of the col. 169const int tabcount // Number of tab stops in the list of variable tab stops. 170= vts [0 ]; 171for (t = 1 ;t <=tabcount ;t ++ ) { 172tabcol += vts [t ]; 173if (tabcol > col ) { 174// If shifting left (left == true), and if the column to the left of 175// the first first non-blank character (col) in the line is 176// already to the left of the first tabstop, set the shift amount 177// (tab_size) to just enough to shift the line to the left margin. 178// The value doesn't seem to matter as long as it is at least that 179// distance. 180if (left && (t == 1 )) { 181tab_size = col ; 182 }else { 183tab_size = vts [t - (left ?1 :0 )]; 184 } 185break ; 186 } 187 } 188if (t > tabcount ) {// If the value of the index t is beyond the 189// end of the list, use the tab stop value at 190// the end of the list. 191tab_size = vts [tabcount ]; 192 } 193 194return tab_size ; 195} 196 197/// Find the column on which a tab starts. 198colnr_T tabstop_start (colnr_T col ,int ts ,colnr_T * vts ) 199{ 200colnr_T tabcol = 0 ; 201 202if (vts == NULL || vts [0 ]== 0 ) { 203return col - col %ts ; 204 } 205 206const int tabcount = vts [0 ]; 207for (int t = 1 ;t <=tabcount ;t ++ ) { 208tabcol += vts [t ]; 209if (tabcol > col ) { 210return (tabcol - vts [t ]); 211 } 212 } 213 214const int excess = (tabcol %vts [tabcount ]); 215return col - (col - excess ) %vts [tabcount ]; 216} 217 218/// Find the number of tabs and spaces necessary to get from one column 219/// to another. 220void tabstop_fromto (colnr_T start_col ,colnr_T end_col ,int ts_arg ,const colnr_T * vts ,int * ntabs , 221int * nspcs ) 222{ 223int spaces = end_col - start_col ; 224colnr_T tabcol = 0 ; 225int padding = 0 ; 226int t ; 227int ts = ts_arg == 0 ? (int )curbuf -> b_p_ts :ts_arg ; 228assert (ts != 0 );// suppress clang "Division by zero" 229 230if (vts == NULL || vts [0 ]== 0 ) { 231int tabs = 0 ; 232 233const int initspc = (ts - (start_col %ts )); 234if (spaces >=initspc ) { 235spaces -= initspc ; 236tabs ++ ; 237 } 238tabs += (spaces /ts ); 239spaces -= ((spaces /ts )* ts ); 240 241* ntabs = tabs ; 242* nspcs = spaces ; 243return ; 244 } 245 246// Find the padding needed to reach the next tabstop. 247const int tabcount = vts [0 ]; 248for (t = 1 ;t <=tabcount ;t ++ ) { 249tabcol += vts [t ]; 250if (tabcol > start_col ) { 251padding = tabcol - start_col ; 252break ; 253 } 254 } 255if (t > tabcount ) { 256padding = vts [tabcount ]- ((start_col - tabcol ) %vts [tabcount ]); 257 } 258 259// If the space needed is less than the padding no tabs can be used. 260if (spaces < padding ) { 261* ntabs = 0 ; 262* nspcs = spaces ; 263return ; 264 } 265 266* ntabs = 1 ; 267spaces -= padding ; 268 269// At least one tab has been used. See if any more will fit. 270while (spaces != 0 && ++ t <=tabcount ) { 271padding = vts [t ]; 272if (spaces < padding ) { 273* nspcs = spaces ; 274return ; 275 } 276* ntabs += 1 ; 277spaces -= padding ; 278 } 279 280* ntabs += spaces / (int )vts [tabcount ]; 281* nspcs = spaces % (int )vts [tabcount ]; 282} 283 284/// Copy a tabstop array, allocating space for the new array. 285int * tabstop_copy (const int * oldts ) 286{ 287if (oldts == 0 ) { 288return 0 ; 289 } 290 291int * newts = xmalloc ((unsigned )(oldts [0 ]+ 1 )* sizeof (int )); 292for (int t = 0 ;t <=oldts [0 ];t ++ ) { 293newts [t ]= oldts [t ]; 294 } 295 296return newts ; 297} 298 299/// Return a count of the number of tabstops. 300int tabstop_count (colnr_T * ts ) 301{ 302return ts != NULL ? (int )ts [0 ] :0 ; 303} 304 305/// Return the first tabstop, or 8 if there are no tabstops defined. 306int tabstop_first (colnr_T * ts ) 307{ 308return ts != NULL ? (int )ts [1 ] :8 ; 309} 310 311/// Return the effective shiftwidth value for current buffer, using the 312/// 'tabstop' value when 'shiftwidth' is zero. 313int get_sw_value (buf_T * buf ) 314{ 315int result = get_sw_value_col (buf ,0 , false); 316return result ; 317} 318 319/// Idem, using "pos". 320static int get_sw_value_pos (buf_T * buf ,pos_T * pos ,bool left ) 321{ 322pos_T save_cursor = curwin -> w_cursor ; 323 324curwin -> w_cursor = * pos ; 325int sw_value = get_sw_value_col (buf ,get_nolist_virtcol (),left ); 326curwin -> w_cursor = save_cursor ; 327return sw_value ; 328} 329 330/// Idem, using the first non-black in the current line. 331int get_sw_value_indent (buf_T * buf ,bool left ) 332{ 333pos_T pos = curwin -> w_cursor ; 334 335pos .col = (colnr_T )getwhitecols_curline (); 336return get_sw_value_pos (buf ,& pos ,left ); 337} 338 339/// Idem, using virtual column "col". 340int get_sw_value_col (buf_T * buf ,colnr_T col ,bool left ) 341{ 342return buf -> b_p_sw ? (int )buf -> b_p_sw 343 :tabstop_at (col ,buf -> b_p_ts ,buf -> b_p_vts_array ,left ); 344} 345 346/// Return the effective softtabstop value for the current buffer, 347/// using the shiftwidth value when 'softtabstop' is negative. 348int get_sts_value (void ) 349{ 350int result = curbuf -> b_p_sts < 0 ?get_sw_value (curbuf ) : (int )curbuf -> b_p_sts ; 351return result ; 352} 353 354/// Count the size (in window cells) of the indent in the current line. 355int get_indent (void ) 356{ 357return indent_size_ts (get_cursor_line_ptr (),curbuf -> b_p_ts ,curbuf -> b_p_vts_array ); 358} 359 360/// Count the size (in window cells) of the indent in line "lnum". 361int get_indent_lnum (linenr_T lnum ) 362{ 363return indent_size_ts (ml_get (lnum ),curbuf -> b_p_ts ,curbuf -> b_p_vts_array ); 364} 365 366/// Count the size (in window cells) of the indent in line "lnum" of buffer "buf". 367int get_indent_buf (buf_T * buf ,linenr_T lnum ) 368{ 369return indent_size_ts (ml_get_buf (buf ,lnum ),buf -> b_p_ts ,buf -> b_p_vts_array ); 370} 371 372/// Compute the size of the indent (in window cells) in line "ptr", 373/// without tabstops (count tab as ^I or <09>). 374int indent_size_no_ts (char const * ptr ) 375FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 376{ 377int tab_size = dy_escape_width ; 378 379int vcol = 0 ; 380while (true) { 381char const c = * ptr ++ ; 382if (c == ' ' ) { 383vcol ++ ; 384 }else if (c == TAB ) { 385vcol += tab_size ; 386 }else { 387return vcol ; 388 } 389 } 390} 391 392/// Compute the size of the indent (in window cells) in line "ptr", 393/// using tabstops 394int indent_size_ts (char const * ptr ,OptInt ts ,colnr_T * vts ) 395FUNC_ATTR_NONNULL_ARG (1 )FUNC_ATTR_PURE 396{ 397assert (char2cells (' ' )== 1 ); 398 399int vcol = 0 ; 400int tabstop_width ,next_tab_vcol ; 401 402if (vts == NULL || vts [0 ]< 1 ) {// tab has fixed width 403// can ts be 0 ? This is from tabstop_padding(). 404tabstop_width = (int )(ts == 0 ?8 :ts ); 405next_tab_vcol = tabstop_width ; 406 }else {// tab has variable width 407colnr_T * cur_tabstop = vts + 1 ; 408colnr_T * const last_tabstop = vts + vts [0 ]; 409 410while (cur_tabstop != last_tabstop ) { 411int cur_vcol = vcol ; 412vcol += * cur_tabstop ++ ; 413assert (cur_vcol < vcol ); 414 415do { 416char const c = * ptr ++ ; 417if (c == ' ' ) { 418cur_vcol ++ ; 419 }else if (c == TAB ) { 420break ; 421 }else { 422return cur_vcol ; 423 } 424 }while (cur_vcol != vcol ); 425 } 426 427tabstop_width = * last_tabstop ; 428next_tab_vcol = vcol + tabstop_width ; 429 } 430 431assert (tabstop_width != 0 ); 432while (true) { 433char const c = * ptr ++ ; 434if (c == ' ' ) { 435vcol ++ ; 436next_tab_vcol += (vcol == next_tab_vcol ) ?tabstop_width :0 ; 437 }else if (c == TAB ) { 438vcol = next_tab_vcol ; 439next_tab_vcol += tabstop_width ; 440 }else { 441return vcol ; 442 } 443 } 444} 445 446/// Set the indent of the current line. 447/// Leaves the cursor on the first non-blank in the line. 448/// Caller must take care of undo. 449/// "flags": 450/// SIN_CHANGED: call changed_bytes() if the line was changed. 451/// SIN_INSERT: insert the indent in front of the line. 452/// SIN_UNDO: save line for undo before changing it. 453/// SIN_NOMARK: don't move extmarks (because just after ml_append or something) 454/// @param size measured in spaces 455/// 456/// @return true if the line was changed. 457bool set_indent (int size ,int flags ) 458{ 459char * newline ; 460char * oldline ; 461char * s ; 462int doit = false; 463int ind_done = 0 ;// Measured in spaces. 464int tab_pad ; 465bool retval = false; 466 467// Number of initial whitespace chars when 'et' and 'pi' are both set. 468int orig_char_len = -1 ; 469 470// First check if there is anything to do and compute the number of 471// characters needed for the indent. 472int todo = size ; 473int ind_len = 0 ;// Measured in characters. 474char * p = oldline = get_cursor_line_ptr (); 475int line_len = get_cursor_line_len ()+ 1 ;// size of the line (including the NUL) 476 477// Calculate the buffer size for the new indent, and check to see if it 478// isn't already set. 479// If 'expandtab' isn't set: use TABs; if both 'expandtab' and 480// 'preserveindent' are set count the number of characters at the 481// beginning of the line to be copied. 482if (!curbuf -> b_p_et || (!(flags & SIN_INSERT )&& curbuf -> b_p_pi )) { 483int ind_col = 0 ; 484// If 'preserveindent' is set then reuse as much as possible of 485// the existing indent structure for the new indent. 486if (!(flags & SIN_INSERT )&& curbuf -> b_p_pi ) { 487ind_done = 0 ; 488 489// Count as many characters as we can use. 490while (todo > 0 && ascii_iswhite (* p )) { 491if (* p == TAB ) { 492tab_pad = tabstop_padding (ind_done , 493curbuf -> b_p_ts , 494curbuf -> b_p_vts_array ); 495 496// Stop if this tab will overshoot the target. 497if (todo < tab_pad ) { 498break ; 499 } 500todo -= tab_pad ; 501ind_len ++ ; 502ind_done += tab_pad ; 503 }else { 504todo -- ; 505ind_len ++ ; 506ind_done ++ ; 507 } 508p ++ ; 509 } 510 511// These diverge from this point. 512ind_col = ind_done ; 513// Set initial number of whitespace chars to copy if we are 514// preserving indent but expandtab is set. 515if (curbuf -> b_p_et ) { 516orig_char_len = ind_len ; 517 } 518// Fill to next tabstop with a tab, if possible. 519tab_pad = tabstop_padding (ind_done , 520curbuf -> b_p_ts , 521curbuf -> b_p_vts_array ); 522if ((todo >=tab_pad )&& (orig_char_len == -1 )) { 523doit = true; 524todo -= tab_pad ; 525ind_len ++ ; 526 527// ind_done += tab_pad; 528ind_col += tab_pad ; 529 } 530 } 531 532// Count tabs required for indent. 533while (true) { 534tab_pad = tabstop_padding (ind_col ,curbuf -> b_p_ts ,curbuf -> b_p_vts_array ); 535if (todo < tab_pad ) { 536break ; 537 } 538if (* p != TAB ) { 539doit = true; 540 }else { 541p ++ ; 542 } 543todo -= tab_pad ; 544ind_len ++ ; 545ind_col += tab_pad ; 546 } 547 } 548 549// Count spaces required for indent. 550while (todo > 0 ) { 551if (* p != ' ' ) { 552doit = true; 553 }else { 554p ++ ; 555 } 556todo -- ; 557ind_len ++ ; 558 559// ind_done++; 560 } 561 562// Return if the indent is OK already. 563if (!doit && !ascii_iswhite (* p )&& !(flags & SIN_INSERT )) { 564return false; 565 } 566 567// Allocate memory for the new line. 568if (flags & SIN_INSERT ) { 569p = oldline ; 570 }else { 571p = skipwhite (p ); 572line_len -= (int )(p - oldline ); 573 } 574 575// If 'preserveindent' and 'expandtab' are both set keep the original 576// characters and allocate accordingly. We will fill the rest with spaces 577// after the if (!curbuf->b_p_et) below. 578int skipcols = 0 ;// number of columns (in bytes) that were presved 579if (orig_char_len != -1 ) { 580int newline_size ;// = orig_char_len + size - ind_done + line_len 581STRICT_ADD (orig_char_len ,size ,& newline_size ,int ); 582STRICT_SUB (newline_size ,ind_done ,& newline_size ,int ); 583STRICT_ADD (newline_size ,line_len ,& newline_size ,int ); 584assert (newline_size >=0 ); 585newline = xmalloc ((size_t )newline_size ); 586todo = size - ind_done ; 587 588// Set total length of indent in characters, which may have been 589// undercounted until now. 590ind_len = orig_char_len + todo ; 591p = oldline ; 592s = newline ; 593skipcols = orig_char_len ; 594 595while (orig_char_len > 0 ) { 596* s ++ = * p ++ ; 597orig_char_len -- ; 598 } 599 600// Skip over any additional white space (useful when newindent is less 601// than old). 602while (ascii_iswhite (* p )) { 603p ++ ; 604 } 605 }else { 606todo = size ; 607assert (ind_len + line_len >=0 ); 608size_t newline_size ; 609STRICT_ADD (ind_len ,line_len ,& newline_size ,size_t ); 610newline = xmalloc (newline_size ); 611s = newline ; 612 } 613 614// Put the characters in the new line. 615// if 'expandtab' isn't set: use TABs 616if (!curbuf -> b_p_et ) { 617// If 'preserveindent' is set then reuse as much as possible of 618// the existing indent structure for the new indent. 619if (!(flags & SIN_INSERT )&& curbuf -> b_p_pi ) { 620p = oldline ; 621ind_done = 0 ; 622 623while (todo > 0 && ascii_iswhite (* p )) { 624if (* p == TAB ) { 625tab_pad = tabstop_padding (ind_done , 626curbuf -> b_p_ts , 627curbuf -> b_p_vts_array ); 628 629// Stop if this tab will overshoot the target. 630if (todo < tab_pad ) { 631break ; 632 } 633todo -= tab_pad ; 634ind_done += tab_pad ; 635 }else { 636todo -- ; 637ind_done ++ ; 638 } 639* s ++ = * p ++ ; 640skipcols ++ ; 641 } 642 643// Fill to next tabstop with a tab, if possible. 644tab_pad = tabstop_padding (ind_done , 645curbuf -> b_p_ts , 646curbuf -> b_p_vts_array ); 647 648if (todo >=tab_pad ) { 649* s ++ = TAB ; 650todo -= tab_pad ; 651ind_done += tab_pad ; 652 } 653p = skipwhite (p ); 654 } 655 656while (true) { 657tab_pad = tabstop_padding (ind_done , 658curbuf -> b_p_ts , 659curbuf -> b_p_vts_array ); 660if (todo < tab_pad ) { 661break ; 662 } 663* s ++ = TAB ; 664todo -= tab_pad ; 665ind_done += tab_pad ; 666 } 667 } 668 669while (todo > 0 ) { 670* s ++ = ' ' ; 671todo -- ; 672 } 673memmove (s ,p , (size_t )line_len ); 674 675// Replace the line (unless undo fails). 676if (!(flags & SIN_UNDO )|| (u_savesub (curwin -> w_cursor .lnum )== OK )) { 677const colnr_T old_offset = (colnr_T )(p - oldline ); 678const colnr_T new_offset = (colnr_T )(s - newline ); 679 680// this may free "newline" 681ml_replace (curwin -> w_cursor .lnum ,newline , false); 682if (!(flags & SIN_NOMARK )) { 683extmark_splice_cols (curbuf , 684 (int )curwin -> w_cursor .lnum - 1 , 685skipcols , 686old_offset - skipcols , 687new_offset - skipcols , 688kExtmarkUndo ); 689 } 690 691if (flags & SIN_CHANGED ) { 692changed_bytes (curwin -> w_cursor .lnum ,0 ); 693 } 694 695// Correct saved cursor position if it is in this line. 696if (saved_cursor .lnum == curwin -> w_cursor .lnum ) { 697if (saved_cursor .col >=old_offset ) { 698// Cursor was after the indent, adjust for the number of 699// bytes added/removed. 700saved_cursor .col += ind_len - old_offset ; 701 }else if (saved_cursor .col >=new_offset ) { 702// Cursor was in the indent, and is now after it, put it back 703// at the start of the indent (replacing spaces with TAB). 704saved_cursor .col = new_offset ; 705 } 706 } 707retval = true; 708 }else { 709xfree (newline ); 710 } 711curwin -> w_cursor .col = ind_len ; 712return retval ; 713} 714 715// Return the indent of the current line after a number. Return -1 if no 716// number was found. Used for 'n' in 'formatoptions': numbered list. 717// Since a pattern is used it can actually handle more than numbers. 718int get_number_indent (linenr_T lnum ) 719{ 720colnr_T col ; 721pos_T pos ; 722regmatch_T regmatch ; 723int lead_len = 0 ;// Length of comment leader. 724 725if (lnum > curbuf -> b_ml .ml_line_count ) { 726return -1 ; 727 } 728pos .lnum = 0 ; 729 730// In format_lines() (i.e. not insert mode), fo+=q is needed too... 731if ((State & MODE_INSERT )|| has_format_option (kFoQComs )) { 732lead_len = get_leader_len (ml_get (lnum ),NULL , false, true); 733 } 734regmatch .regprog = vim_regcomp (curbuf -> b_p_flp ,RE_MAGIC ); 735 736if (regmatch .regprog != NULL ) { 737regmatch .rm_ic = false; 738 739// vim_regexec() expects a pointer to a line. This lets us 740// start matching for the flp beyond any comment leader... 741if (vim_regexec (& regmatch ,ml_get (lnum )+ lead_len ,0 )) { 742pos .lnum = lnum ; 743pos .col = (colnr_T )(* regmatch .endp - ml_get (lnum )); 744pos .coladd = 0 ; 745 } 746vim_regfree (regmatch .regprog ); 747 } 748 749if ((pos .lnum == 0 )|| (* ml_get_pos (& pos )== NUL )) { 750return -1 ; 751 } 752getvcol (curwin ,& pos ,& col ,NULL ,NULL ,0 ); 753return (int )col ; 754} 755 756/// Check "briopt" as 'breakindentopt' and update the members of "wp". 757/// This is called when 'breakindentopt' is changed and when a window is 758/// initialized 759/// 760/// @param briopt when NULL: use "wp->w_p_briopt" 761/// @param wp when NULL: only check "briopt" 762/// 763/// @return FAIL for failure, OK otherwise. 764void briopt_check (win_T * wp ) 765{ 766if (wp == NULL ) { 767return ;// Setting the global value: nothing to apply to a window. 768 } 769// 'breakindentopt' is stored as its ":set" string (validated when set); reify it into a keyset and 770// map that onto the applied per-window fields. 771OptKeyDict_briopt * v = opt_keyset (wp -> w_p_briopt ,kOptBreakindentopt ,NULL ); 772wp -> w_briopt_shift = HAS_KEY (v ,briopt ,shift ) ? (int )v -> shift :0 ; 773wp -> w_briopt_min = HAS_KEY (v ,briopt ,min ) ? (int )v -> min :20 ; 774wp -> w_briopt_sbr = HAS_KEY (v ,briopt ,sbr ); 775wp -> w_briopt_list = HAS_KEY (v ,briopt ,list ) ? (int )v -> list :0 ; 776wp -> w_briopt_vcol = HAS_KEY (v ,briopt ,column ) ? (int )v -> column :0 ; 777} 778 779// Return appropriate space number for breakindent, taking influencing 780// parameters into account. Window must be specified, since it is not 781// necessarily always the current one. 782int get_breakindent_win (win_T * wp ,char * line ) 783FUNC_ATTR_NONNULL_ALL 784{ 785static int prev_indent = 0 ;// cached indent value 786static OptInt prev_ts = 0 ;// cached tabstop value 787static colnr_T * prev_vts = NULL ;// cached vartabs values 788static int prev_fnum = 0 ;// cached buffer number 789static char * prev_line = NULL ;// cached copy of "line" 790static varnumber_T prev_tick = 0 ;// changedtick of cached value 791static int prev_list = 0 ;// cached list indent 792static int prev_listopt = 0 ;// cached w_p_briopt_list value 793static bool prev_no_ts = false;// cached no_ts value 794static unsigned prev_dy_uhex = 0 ;// cached 'display' "uhex" value 795static char * prev_flp = NULL ;// cached formatlistpat value 796int bri = 0 ; 797// window width minus window margin space, i.e. what rests for text 798const int eff_wwidth = wp -> w_view_width - win_col_off (wp )+ win_col_off2 (wp ); 799 800// In list mode, if 'listchars' "tab" isn't set, a TAB is displayed as ^I. 801const bool no_ts = wp -> w_p_list && wp -> w_p_lcs_chars .tab1 == NUL ; 802 803// Used cached indent, unless 804// - buffer changed, or 805// - 'tabstop' changed, or 806// - 'vartabstop' changed, or 807// - buffer was changed, or 808// - 'breakindentopt' "list" changed, or 809// - 'list' or 'listchars' "tab" changed, or 810// - 'display' "uhex" flag changed, or 811// - 'formatlistpat' changed, or 812// - line changed. 813if (prev_fnum != wp -> w_buffer -> b_fnum 814|| prev_ts != wp -> w_buffer -> b_p_ts 815|| prev_vts != wp -> w_buffer -> b_p_vts_array 816|| prev_tick != buf_get_changedtick (wp -> w_buffer ) 817|| prev_listopt != wp -> w_briopt_list 818|| prev_no_ts != no_ts 819|| prev_dy_uhex != (dy_flags & kOptDyFlagUhex ) 820|| prev_flp == NULL 821|| strcmp (prev_flp ,get_flp_value (wp -> w_buffer ))!= 0 822|| prev_line == NULL || strcmp (prev_line ,line )!= 0 ) { 823prev_fnum = wp -> w_buffer -> b_fnum ; 824xfree (prev_line ); 825prev_line = xstrdup (line ); 826prev_ts = wp -> w_buffer -> b_p_ts ; 827prev_vts = wp -> w_buffer -> b_p_vts_array ; 828if (wp -> w_briopt_vcol == 0 ) { 829if (no_ts ) { 830prev_indent = indent_size_no_ts (line ); 831 }else { 832prev_indent = indent_size_ts (line ,wp -> w_buffer -> b_p_ts , 833wp -> w_buffer -> b_p_vts_array ); 834 } 835 } 836prev_tick = buf_get_changedtick (wp -> w_buffer ); 837prev_listopt = wp -> w_briopt_list ; 838prev_list = 0 ; 839prev_no_ts = no_ts ; 840prev_dy_uhex = (dy_flags & kOptDyFlagUhex ); 841xfree (prev_flp ); 842prev_flp = xstrdup (get_flp_value (wp -> w_buffer )); 843// add additional indent for numbered lists 844if (wp -> w_briopt_list != 0 && wp -> w_briopt_vcol == 0 ) { 845regmatch_T regmatch = { 846 .regprog = vim_regcomp (prev_flp ,RE_MAGIC + RE_STRING + RE_AUTO + RE_STRICT ), 847 }; 848if (regmatch .regprog != NULL ) { 849regmatch .rm_ic = false; 850if (vim_regexec (& regmatch ,line ,0 )) { 851if (wp -> w_briopt_list > 0 ) { 852prev_list += wp -> w_briopt_list ; 853 }else { 854char * ptr = * regmatch .startp ; 855char * end_ptr = * regmatch .endp ; 856int indent = 0 ; 857// Compute the width of the matched text. 858// Use win_chartabsize() so that TAB size is correct, 859// while wrapping is ignored. 860while (ptr < end_ptr ) { 861indent += win_chartabsize (wp ,ptr ,indent ); 862MB_PTR_ADV (ptr ); 863 } 864prev_indent = indent ; 865 } 866 } 867vim_regfree (regmatch .regprog ); 868 } 869 } 870 } 871if (wp -> w_briopt_vcol != 0 ) { 872// column value has priority 873bri = wp -> w_briopt_vcol ; 874prev_list = 0 ; 875 }else { 876bri = prev_indent + wp -> w_briopt_shift ; 877 } 878 879// Add offset for number column, if 'n' is in 'cpoptions' 880bri += win_col_off2 (wp ); 881 882// add additional indent for numbered lists 883if (wp -> w_briopt_list > 0 ) { 884bri += prev_list ; 885 } 886 887// indent minus the length of the showbreak string 888if (wp -> w_briopt_sbr ) { 889bri -= vim_strsize (get_showbreak_value (wp )); 890 } 891 892// never indent past left window margin 893if (bri < 0 ) { 894bri = 0 ; 895 }else if (bri > eff_wwidth - wp -> w_briopt_min ) { 896// always leave at least bri_min characters on the left, 897// if text width is sufficient 898bri = (eff_wwidth - wp -> w_briopt_min < 0 ) 899 ?0 :eff_wwidth - wp -> w_briopt_min ; 900 } 901 902return bri ; 903} 904 905// When extra == 0: Return true if the cursor is before or on the first 906// non-blank in the line. 907// When extra == 1: Return true if the cursor is before the first non-blank in 908// the line. 909bool inindent (int extra ) 910{ 911char * ptr ; 912colnr_T col ; 913 914for (col = 0 ,ptr = get_cursor_line_ptr ();ascii_iswhite (* ptr );col ++ ) { 915ptr ++ ; 916 } 917 918if (col >=curwin -> w_cursor .col + extra ) { 919return true; 920 } 921return false; 922} 923 924/// Handle reindenting a block of lines. 925void op_reindent (oparg_T * oap ,Indenter how ) 926{ 927int i = 0 ; 928linenr_T first_changed = 0 ; 929linenr_T last_changed = 0 ; 930linenr_T start_lnum = curwin -> w_cursor .lnum ; 931 932// Don't even try when 'modifiable' is off. 933if (!MODIFIABLE (curbuf )) { 934emsg (_ (e_modifiable )); 935return ; 936 } 937 938// Save for undo. Do this once for all lines, much faster than doing this 939// for each line separately, especially when undoing. 940if (u_savecommon (curbuf ,start_lnum - 1 ,start_lnum + oap -> line_count , 941start_lnum + oap -> line_count , false)== OK ) { 942int amount ; 943for (i = oap -> line_count - 1 ;i >=0 && !got_int ;i -- ) { 944// it's a slow thing to do, so give feedback so there's no worry 945// that the computer's just hung. 946 947if (i > 1 948&& (i %50 == 0 || i == oap -> line_count - 1 ) 949&& oap -> line_count > p_report ) { 950snprintf (IObuff ,IOSIZE ,_ ("%" PRId64 " lines to indent... " ), (int64_t )i ); 951// Restore cursor to avoid redrawing curwin in msg_show callback. 952linenr_T save_lnum = curwin -> w_cursor .lnum ; 953curwin -> w_cursor .lnum = start_lnum ; 954msg_progress (IObuff ,"nvim.indent" ,"running" ,0 , true, false, false); 955curwin -> w_cursor .lnum = save_lnum ; 956 } 957 958// Be vi-compatible: For lisp indenting the first line is not 959// indented, unless there is only one line. 960if (i != oap -> line_count - 1 || oap -> line_count == 1 || how != get_lisp_indent ) { 961char * l = skipwhite (get_cursor_line_ptr ()); 962// Get indent for this line unless it is blank. 963amount = * l == NUL ?0 :how (); 964if (amount >=0 && set_indent (amount ,0 )) { 965// did change the indent, call changed_lines() later 966if (first_changed == 0 ) { 967first_changed = curwin -> w_cursor .lnum ; 968 } 969last_changed = curwin -> w_cursor .lnum ; 970 } 971 } 972curwin -> w_cursor .lnum ++ ; 973curwin -> w_cursor .col = 0 ;// make sure it's valid 974 } 975 } 976 977// put cursor on first non-blank of indented line 978curwin -> w_cursor .lnum = start_lnum ; 979beginline (BL_SOL |BL_FIX ); 980 981// Mark changed lines so that they will be redrawn. When Visual 982// highlighting was present, need to continue until the last line. When 983// there is no change still need to remove the Visual highlighting. 984if (last_changed != 0 ) { 985changed_lines (curbuf ,first_changed ,0 , 986oap -> is_VIsual ?start_lnum + oap -> line_count 987 :last_changed + 1 ,0 , true); 988 }else if (oap -> is_VIsual ) { 989redraw_curbuf_later (UPD_INVERTED ); 990 } 991 992if (oap -> line_count > p_report ) { 993i = oap -> line_count - (i + 1 ); 994snprintf (IObuff ,IOSIZE , 995NGETTEXT ("%" PRId64 " line indented " ,"%" PRId64 " lines indented " ,i ), (int64_t )i ); 996msg_progress (IObuff ,"nvim.indent" ,"success" ,0 , true, false, false); 997 } 998if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 999// set '[ and '] marks 1000curbuf -> b_op_start = oap -> start ; 1001curbuf -> b_op_end = oap -> end ; 1002 } 1003} 1004 1005/// @return true if lines starting with '#' should be left aligned. 1006bool preprocs_left (void ) 1007{ 1008return ((curbuf -> b_p_si && !curbuf -> b_p_cin ) 1009|| (curbuf -> b_p_cin && in_cinkeys ('#' ,' ' , true) 1010&& curbuf -> b_ind_hash_comment == 0 )); 1011} 1012 1013/// @return true if the conditions are OK for smart indenting. 1014bool may_do_si (void ) 1015{ 1016return curbuf -> b_p_si && !curbuf -> b_p_cin && curbuf -> b_p_inde .type == kCallbackNone && !p_paste ; 1017} 1018 1019// Try to do some very smart auto-indenting. 1020// Used when inserting a "normal" character. 1021void ins_try_si (int c ) 1022{ 1023pos_T * pos ; 1024 1025// do some very smart indenting when entering '{' or '}' 1026if (((Ins .did_si || Ins .can_si_back )&& c == '{' )|| (Ins .can_si && c == '}' && inindent (0 ))) { 1027pos_T old_pos ; 1028char * ptr ; 1029int i ; 1030bool temp ; 1031// for '}' set indent equal to indent of line containing matching '{' 1032if (c == '}' && (pos = findmatch (NULL ,'{' ))!= NULL ) { 1033old_pos = curwin -> w_cursor ; 1034// If the matching '{' has a ')' immediately before it (ignoring 1035// white-space), then line up with the start of the line 1036// containing the matching '(' if there is one. This handles the 1037// case where an "if (..\n..) {" statement continues over multiple 1038// lines -- webb 1039ptr = ml_get (pos -> lnum ); 1040i = pos -> col ; 1041if (i > 0 ) {// skip blanks before '{' 1042while (-- i > 0 && ascii_iswhite (ptr [i ])) {} 1043 } 1044curwin -> w_cursor .lnum = pos -> lnum ; 1045curwin -> w_cursor .col = i ; 1046if (ptr [i ]== ')' && (pos = findmatch (NULL ,'(' ))!= NULL ) { 1047curwin -> w_cursor = * pos ; 1048 } 1049i = get_indent (); 1050curwin -> w_cursor = old_pos ; 1051if (State & VREPLACE_FLAG ) { 1052change_indent (INDENT_SET ,i , false, true); 1053 }else { 1054set_indent (i ,SIN_CHANGED ); 1055 } 1056 }else if (curwin -> w_cursor .col > 0 ) { 1057// when inserting '{' after "O" reduce indent, but not 1058// more than indent of previous line 1059temp = true; 1060if (c == '{' && Ins .can_si_back && curwin -> w_cursor .lnum > 1 ) { 1061old_pos = curwin -> w_cursor ; 1062i = get_indent (); 1063while (curwin -> w_cursor .lnum > 1 ) { 1064ptr = skipwhite (ml_get (-- (curwin -> w_cursor .lnum ))); 1065 1066// ignore empty lines and lines starting with '#'. 1067if (* ptr != '#' && * ptr != NUL ) { 1068break ; 1069 } 1070 } 1071if (get_indent () >=i ) { 1072temp = false; 1073 } 1074curwin -> w_cursor = old_pos ; 1075 } 1076if (temp ) { 1077shift_line (true, false,1 , true); 1078 } 1079 } 1080 } 1081 1082// set indent of '#' always to 0 1083if (curwin -> w_cursor .col > 0 && Ins .can_si && c == '#' && inindent (0 )) { 1084// remember current indent for next line 1085old_indent = get_indent (); 1086set_indent (0 ,SIN_CHANGED ); 1087 } 1088 1089// Adjust Ins.ai_col, the char at this position can be deleted. 1090Ins .ai_col = MIN (Ins .ai_col ,curwin -> w_cursor .col ); 1091} 1092 1093/// Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D). 1094/// Keep the cursor on the same character. 1095/// type == INDENT_INC increase indent (for CTRL-T or <Tab>) 1096/// type == INDENT_DEC decrease indent (for CTRL-D) 1097/// type == INDENT_SET set indent to "amount" 1098/// 1099/// @param round if true, round the indent to 'shiftwidth' (only with _INC and _Dec). 1100/// @param call_changed_bytes call changed_bytes() 1101void change_indent (int type ,int amount ,int round ,bool call_changed_bytes ) 1102{ 1103int insstart_less ;// reduction for Ins.start.col 1104colnr_T orig_col = 0 ;// init for GCC 1105char * orig_line = NULL ;// init for GCC 1106 1107// MODE_VREPLACE state needs to know what the line was like before changing 1108if (State & VREPLACE_FLAG ) { 1109orig_line = xstrnsave (get_cursor_line_ptr (), (size_t )get_cursor_line_len ()); 1110orig_col = curwin -> w_cursor .col ; 1111 } 1112 1113// for the following tricks we don't want list mode 1114int save_p_list = curwin -> w_p_list ; 1115curwin -> w_p_list = false; 1116colnr_T vc = getvcol_nolist (& curwin -> w_cursor ); 1117int vcol = vc ; 1118 1119// For Replace mode we need to fix the replace stack later, which is only 1120// possible when the cursor is in the indent. Remember the number of 1121// characters before the cursor if it's possible. 1122int start_col = curwin -> w_cursor .col ; 1123 1124// determine offset from first non-blank 1125int new_cursor_col = curwin -> w_cursor .col ; 1126beginline (BL_WHITE ); 1127new_cursor_col -= curwin -> w_cursor .col ; 1128 1129insstart_less = curwin -> w_cursor .col ; 1130 1131// If the cursor is in the indent, compute how many screen columns the 1132// cursor is to the left of the first non-blank. 1133if (new_cursor_col < 0 ) { 1134vcol = get_indent ()- vcol ; 1135 } 1136 1137if (new_cursor_col > 0 ) {// can't fix replace stack 1138start_col = -1 ; 1139 } 1140 1141// Set the new indent. The cursor will be put on the first non-blank. 1142if (type == INDENT_SET ) { 1143set_indent (amount ,call_changed_bytes ?SIN_CHANGED :0 ); 1144 }else { 1145int save_State = State ; 1146 1147// Avoid being called recursively. 1148if (State & VREPLACE_FLAG ) { 1149State = MODE_INSERT ; 1150 } 1151shift_line (type == INDENT_DEC ,round ,1 ,call_changed_bytes ); 1152State = save_State ; 1153 } 1154insstart_less -= curwin -> w_cursor .col ; 1155 1156// Try to put cursor on same character. 1157// If the cursor is at or after the first non-blank in the line, 1158// compute the cursor column relative to the column of the first 1159// non-blank character. 1160// If we are not in insert mode, leave the cursor on the first non-blank. 1161// If the cursor is before the first non-blank, position it relative 1162// to the first non-blank, counted in screen columns. 1163if (new_cursor_col >=0 ) { 1164// When changing the indent while the cursor is touching it, reset 1165// Insstart_col to 0. 1166if (new_cursor_col == 0 ) { 1167insstart_less = MAXCOL ; 1168 } 1169new_cursor_col += curwin -> w_cursor .col ; 1170 }else if (!(State & MODE_INSERT )) { 1171new_cursor_col = curwin -> w_cursor .col ; 1172 }else { 1173// Compute the screen column where the cursor should be. 1174vcol = get_indent ()- vcol ; 1175int const end_vcol = (colnr_T )((vcol < 0 ) ?0 :vcol ); 1176curwin -> w_virtcol = end_vcol ; 1177 1178// Advance the cursor until we reach the right screen column. 1179new_cursor_col = 0 ; 1180char * const line = get_cursor_line_ptr (); 1181vcol = 0 ; 1182if (* line != NUL ) { 1183CharsizeArg csarg ; 1184CSType cstype = init_charsize_arg (& csarg ,curwin ,0 ,line ); 1185StrCharInfo ci = utf_ptr2StrCharInfo (line ); 1186while (true) { 1187ClusterInfo cli = utf_ClusterInfo (ci ); 1188int next_vcol = vcol + win_charsize (cstype ,vcol ,ci .ptr ,ci .chr .value ,& csarg , 1189cli .cells ).width ; 1190if (next_vcol > end_vcol ) { 1191break ; 1192 } 1193vcol = next_vcol ; 1194ci = cli .next ; 1195if (* ci .ptr == NUL ) { 1196break ; 1197 } 1198 } 1199new_cursor_col = (int )(ci .ptr - line ); 1200 } 1201 1202// May need to insert spaces to be able to position the cursor on 1203// the right screen column. 1204if (vcol != (int )curwin -> w_virtcol ) { 1205curwin -> w_cursor .col = (colnr_T )new_cursor_col ; 1206const size_t ptrlen = (size_t )(curwin -> w_virtcol - vcol ); 1207char * ptr = xmallocz (ptrlen ); 1208memset (ptr ,' ' ,ptrlen ); 1209new_cursor_col += (int )ptrlen ; 1210ins_str (ptr ,ptrlen ); 1211xfree (ptr ); 1212 } 1213 1214// When changing the indent while the cursor is in it, reset 1215// Insstart_col to 0. 1216insstart_less = MAXCOL ; 1217 } 1218 1219curwin -> w_p_list = save_p_list ; 1220curwin -> w_cursor .col = MAX (0 , (colnr_T )new_cursor_col ); 1221curwin -> w_set_curswant = true; 1222changed_cline_bef_curs (curwin ); 1223 1224// May have to adjust the start of the insert. 1225if (State & MODE_INSERT ) { 1226if (curwin -> w_cursor .lnum == Ins .start .lnum && Ins .start .col != 0 ) { 1227if ((int )Ins .start .col <=insstart_less ) { 1228Ins .start .col = 0 ; 1229 }else { 1230Ins .start .col -= insstart_less ; 1231 } 1232 } 1233if ((int )Ins .ai_col <=insstart_less ) { 1234Ins .ai_col = 0 ; 1235 }else { 1236Ins .ai_col -= insstart_less ; 1237 } 1238 } 1239 1240// For MODE_REPLACE state, may have to fix the replace stack, if it's 1241// possible. If the number of characters before the cursor decreased, need 1242// to pop a few characters from the replace stack. 1243// If the number of characters before the cursor increased, need to push a 1244// few NULs onto the replace stack. 1245if (REPLACE_NORMAL (State )&& start_col >=0 ) { 1246while (start_col > (int )curwin -> w_cursor .col ) { 1247replace_join (0 );// remove a NUL from the replace stack 1248start_col -- ; 1249 } 1250while (start_col < (int )curwin -> w_cursor .col ) { 1251replace_push_nul (); 1252start_col ++ ; 1253 } 1254 } 1255 1256// For MODE_VREPLACE state, we also have to fix the replace stack. In this 1257// case it is always possible because we backspace over the whole line and 1258// then put it back again the way we wanted it. 1259if (State & VREPLACE_FLAG ) { 1260// Save new line 1261char * new_line = xstrnsave (get_cursor_line_ptr (), (size_t )get_cursor_line_len ()); 1262 1263// We only put back the new line up to the cursor 1264new_line [curwin -> w_cursor .col ]= NUL ; 1265int new_col = curwin -> w_cursor .col ; 1266 1267// Put back original line 1268ml_replace (curwin -> w_cursor .lnum ,orig_line , false); 1269curwin -> w_cursor .col = orig_col ; 1270 1271curbuf_splice_pending ++ ; 1272 1273// Backspace from cursor to start of line 1274backspace_until_column (0 ); 1275 1276// Insert new stuff into line again 1277ins_bytes (new_line ); 1278 1279xfree (new_line ); 1280 1281curbuf_splice_pending -- ; 1282 1283// TODO(bfredl): test for crazy edge cases, like we stand on a TAB or 1284// something? does this even do the right text change then? 1285int delta = orig_col - new_col ; 1286extmark_splice_cols (curbuf , (int )curwin -> w_cursor .lnum - 1 ,new_col , 1287delta < 0 ?- delta :0 , 1288delta > 0 ?delta :0 , 1289kExtmarkUndo ); 1290 } 1291} 1292 1293/// Copy the indent from ptr to the current line (and fill to size). 1294/// Leaves the cursor on the first non-blank in the line. 1295/// 1296/// @return true if the line was changed. 1297bool copy_indent (int size ,char * src ) 1298{ 1299char * p = NULL ; 1300char * line = NULL ; 1301int ind_len ; 1302int line_len = 0 ; 1303int tab_pad ; 1304 1305// Round 1: compute the number of characters needed for the indent 1306// Round 2: copy the characters. 1307for (int round = 1 ;round <=2 ;round ++ ) { 1308int todo = size ; 1309ind_len = 0 ; 1310int ind_done = 0 ; 1311int ind_col = 0 ; 1312char * s = src ; 1313 1314// Count/copy the usable portion of the source line. 1315while (todo > 0 && ascii_iswhite (* s )) { 1316if (* s == TAB ) { 1317tab_pad = tabstop_padding (ind_done , 1318curbuf -> b_p_ts , 1319curbuf -> b_p_vts_array ); 1320 1321// Stop if this tab will overshoot the target. 1322if (todo < tab_pad ) { 1323break ; 1324 } 1325todo -= tab_pad ; 1326ind_done += tab_pad ; 1327ind_col += tab_pad ; 1328 }else { 1329todo -- ; 1330ind_done ++ ; 1331ind_col ++ ; 1332 } 1333ind_len ++ ; 1334 1335if (p != NULL ) { 1336* p ++ = * s ; 1337 } 1338s ++ ; 1339 } 1340 1341// Fill to next tabstop with a tab, if possible. 1342tab_pad = tabstop_padding (ind_done ,curbuf -> b_p_ts ,curbuf -> b_p_vts_array ); 1343 1344if ((todo >=tab_pad )&& !curbuf -> b_p_et ) { 1345todo -= tab_pad ; 1346ind_len ++ ; 1347ind_col += tab_pad ; 1348 1349if (p != NULL ) { 1350* p ++ = TAB ; 1351 } 1352 } 1353 1354// Add tabs required for indent. 1355if (!curbuf -> b_p_et ) { 1356while (true) { 1357tab_pad = tabstop_padding (ind_col , 1358curbuf -> b_p_ts , 1359curbuf -> b_p_vts_array ); 1360if (todo < tab_pad ) { 1361break ; 1362 } 1363todo -= tab_pad ; 1364ind_len ++ ; 1365ind_col += tab_pad ; 1366if (p != NULL ) { 1367* p ++ = TAB ; 1368 } 1369 } 1370 } 1371 1372// Count/add spaces required for indent. 1373while (todo > 0 ) { 1374todo -- ; 1375ind_len ++ ; 1376 1377if (p != NULL ) { 1378* p ++ = ' ' ; 1379 } 1380 } 1381 1382if (p == NULL ) { 1383// Allocate memory for the result: the copied indent, new indent 1384// and the rest of the line. 1385line_len = get_cursor_line_len ()+ 1 ; 1386assert (ind_len + line_len >=0 ); 1387size_t line_size ; 1388STRICT_ADD (ind_len ,line_len ,& line_size ,size_t ); 1389line = xmalloc (line_size ); 1390p = line ; 1391 } 1392 } 1393 1394// Append the original line 1395memmove (p ,get_cursor_line_ptr (), (size_t )line_len ); 1396 1397// Replace the line 1398ml_replace (curwin -> w_cursor .lnum ,line , false); 1399 1400// Put the cursor after the indent. 1401curwin -> w_cursor .col = ind_len ; 1402return true; 1403} 1404 1405/// Give a "resulting text too long" error and maybe set got_int. 1406static void emsg_text_too_long (void ) 1407{ 1408emsg (_ (e_resulting_text_too_long )); 1409// when not inside a try/catch set got_int to break out of any loop 1410if (trylevel == 0 ) { 1411got_int = true; 1412 } 1413} 1414 1415/// ":retab". 1416void ex_retab (exarg_T * eap ) 1417{ 1418bool got_tab = false; 1419int num_spaces = 0 ; 1420int start_col = 0 ;// For start of white-space string 1421int64_t start_vcol = 0 ;// For start of white-space string 1422char * new_line = (char * )1 ;// init to non-NULL 1423colnr_T * new_vts_array = NULL ; 1424char * new_ts_str ;// string value of tab argument 1425 1426linenr_T first_line = 0 ;// first changed line 1427linenr_T last_line = 0 ;// last changed line 1428bool is_indent_only = false; 1429 1430char * ptr = eap -> arg ; 1431if (strncmp (ptr ,"-indentonly" ,11 )== 0 && ascii_iswhite_or_nul (ptr [11 ])) { 1432is_indent_only = true; 1433ptr = skipwhite (ptr + 11 ); 1434 } 1435 1436new_ts_str = ptr ; 1437if (!tabstop_set (ptr ,& new_vts_array )) { 1438return ; 1439 } 1440while (ascii_isdigit (* ptr )|| * ptr == ',' ) { 1441ptr ++ ; 1442 } 1443 1444// This ensures that either new_vts_array and new_ts_str are freshly 1445// allocated, or new_vts_array points to an existing array and new_ts_str 1446// is null. 1447if (new_vts_array == NULL ) { 1448new_vts_array = curbuf -> b_p_vts_array ; 1449new_ts_str = NULL ; 1450 }else { 1451new_ts_str = xmemdupz (new_ts_str , (size_t )(ptr - new_ts_str )); 1452 } 1453 1454int save_list = curwin -> w_p_list ; 1455curwin -> w_p_list = 0 ;// don't want list mode here 1456 1457for (linenr_T lnum = eap -> line1 ; !got_int && lnum <=eap -> line2 ;lnum ++ ) { 1458ptr = ml_get (lnum ); 1459int old_len = ml_get_len (lnum ); 1460int col = 0 ; 1461int64_t vcol = 0 ; 1462bool did_undo = false;// called u_save for current line 1463while (true) { 1464if (ascii_iswhite (ptr [col ])) { 1465if (!got_tab && num_spaces == 0 ) { 1466// First consecutive white-space 1467start_vcol = vcol ; 1468start_col = col ; 1469 } 1470if (ptr [col ]== ' ' ) { 1471num_spaces ++ ; 1472 }else { 1473got_tab = true; 1474 } 1475 }else { 1476if (got_tab || (eap -> forceit && num_spaces > 1 )) { 1477// Retabulate this string of white-space 1478 1479// len is virtual length of white string 1480int len = num_spaces = (int )(vcol - start_vcol ); 1481int num_tabs = 0 ; 1482if (!curbuf -> b_p_et ) { 1483int t ,s ; 1484 1485tabstop_fromto ((colnr_T )start_vcol , (colnr_T )vcol , 1486 (int )curbuf -> b_p_ts ,new_vts_array ,& t ,& s ); 1487num_tabs = t ; 1488num_spaces = s ; 1489 } 1490if (curbuf -> b_p_et || got_tab 1491|| (num_spaces + num_tabs < len )) { 1492if (did_undo == false) { 1493did_undo = true; 1494if (u_save ((linenr_T )(lnum - 1 ), 1495 (linenr_T )(lnum + 1 ))== FAIL ) { 1496new_line = NULL ;// flag out-of-memory 1497break ; 1498 } 1499 } 1500 1501// len is actual number of white characters used 1502len = num_spaces + num_tabs ; 1503const int new_len = old_len - col + start_col + len + 1 ; 1504if (new_len <=0 || new_len >=MAXCOL ) { 1505emsg_text_too_long (); 1506break ; 1507 } 1508new_line = xmalloc ((size_t )new_len ); 1509 1510if (start_col > 0 ) { 1511memmove (new_line ,ptr , (size_t )start_col ); 1512 } 1513memmove (new_line + start_col + len , 1514ptr + col , (size_t )old_len - (size_t )col + 1 ); 1515ptr = new_line + start_col ; 1516for (col = 0 ;col < len ;col ++ ) { 1517ptr [col ]= (col < num_tabs ) ?'\t' :' ' ; 1518 } 1519if (ml_replace (lnum ,new_line , false)== OK ) { 1520// "new_line" may have been copied 1521new_line = curbuf -> b_ml .ml_line_ptr ; 1522extmark_splice_cols (curbuf ,lnum - 1 ,0 , (colnr_T )old_len , 1523 (colnr_T )new_len - 1 ,kExtmarkUndo ); 1524 } 1525if (first_line == 0 ) { 1526first_line = lnum ; 1527 } 1528last_line = lnum ; 1529ptr = new_line ; 1530old_len = new_len - 1 ; 1531col = start_col + len ; 1532 } 1533 } 1534got_tab = false; 1535num_spaces = 0 ; 1536 1537if (is_indent_only ) { 1538break ; 1539 } 1540 } 1541if (ptr [col ]== NUL ) { 1542break ; 1543 } 1544vcol += win_chartabsize (curwin ,ptr + col , (colnr_T )vcol ); 1545if (vcol >=MAXCOL ) { 1546emsg_text_too_long (); 1547break ; 1548 } 1549col += utfc_ptr2len (ptr + col ); 1550 } 1551if (new_line == NULL ) {// out of memory 1552break ; 1553 } 1554line_breakcheck (); 1555 } 1556if (got_int ) { 1557emsg (_ (e_interr )); 1558 } 1559 1560if (first_line != 0 ) { 1561changed_lines (curbuf ,first_line ,0 ,last_line + 1 ,0 , true); 1562 } 1563 1564curwin -> w_p_list = save_list ;// restore 'list' 1565// Finish buffer cleanup before OptionSet can switch buffers. 1566u_clearline (curbuf ); 1567 1568if (new_ts_str != NULL ) {// set the new tabstop 1569const handle_T win_handle = curwin -> handle ; 1570const handle_T buf_handle = curbuf -> handle ; 1571 1572// If 'vartabstop' is in use or if the value given to retab has more 1573// than one tabstop then update 'vartabstop'. 1574if (tabstop_count (curbuf -> b_p_vts_array )> 0 || tabstop_count (new_vts_array )> 1 ) { 1575set_option_value (kOptVartabstop ,CSTR_AS_OBJ (new_ts_str ),OPT_LOCAL , true,NULL ); 1576 }else { 1577// 'vartabstop' wasn't in use and a single value was given to 1578// retab then update 'tabstop'. 1579set_option_value (kOptTabstop ,INTEGER_OBJ (tabstop_first (new_vts_array )),OPT_LOCAL , true, 1580NULL ); 1581 } 1582xfree (new_vts_array ); 1583xfree (new_ts_str ); 1584// OptionSet may have left the command's window or buffer. 1585if (curwin -> handle != win_handle || curbuf -> handle != buf_handle ) { 1586return ; 1587 } 1588 } 1589coladvance (curwin ,curwin -> w_curswant ); 1590} 1591 1592/// Get indent level from 'indentexpr'. 1593int get_expr_indent (void ) 1594{ 1595bool use_sandbox = was_set_insecurely (curwin ,kOptIndentexpr ,OPT_LOCAL ); 1596const sctx_T save_sctx = current_sctx ; 1597 1598// Save and restore cursor position and curswant, in case it was changed 1599// * via :normal commands. 1600pos_T save_pos = curwin -> w_cursor ; 1601colnr_T save_curswant = curwin -> w_curswant ; 1602bool save_set_curswant = curwin -> w_set_curswant ; 1603set_vim_var_nr (VV_LNUM , (varnumber_T )curwin -> w_cursor .lnum ); 1604 1605textlock ++ ; 1606current_sctx = curbuf -> b_p_script_ctx [kBufOptIndentexpr ]; 1607 1608int indent = eval_expr_option_number (& curbuf -> b_p_inde ,use_sandbox ); 1609 1610textlock -- ; 1611current_sctx = save_sctx ; 1612 1613// Restore the cursor position so that 'indentexpr' doesn't need to. 1614// Pretend to be in Insert mode, allow cursor past end of line for "o" 1615// command. 1616int save_State = State ; 1617State = MODE_INSERT ; 1618curwin -> w_cursor = save_pos ; 1619curwin -> w_curswant = save_curswant ; 1620curwin -> w_set_curswant = save_set_curswant ; 1621check_cursor (curwin ); 1622State = save_State ; 1623 1624// Reset did_throw, unless 'debug' has "throw" and inside a try/catch. 1625if (did_throw && (vim_strchr (p_debug ,'t' )== NULL || trylevel == 0 )) { 1626handle_did_throw (); 1627did_throw = false; 1628 } 1629 1630// If there is an error, just keep the current indent. 1631if (indent < 0 ) { 1632indent = get_indent (); 1633 } 1634 1635return indent ; 1636} 1637 1638// When 'p' is present in 'cpoptions, a Vi compatible method is used. 1639// The incompatible newer method is quite a bit better at indenting 1640// code in lisp-like languages than the traditional one; it's still 1641// mostly heuristics however -- Dirk van Deun, dirk@rave.org 1642 1643// TODO(unknown): 1644// Findmatch() should be adapted for lisp, also to make showmatch 1645// work correctly: now (v5.3) it seems all C/C++ oriented: 1646// - it does not recognize the #\( and #\) notations as character literals 1647// - it doesn't know about comments starting with a semicolon 1648// - it incorrectly interprets '(' as a character literal 1649// All this messes up get_lisp_indent in some rare cases. 1650// Update from Sergey Khorev: 1651// I tried to fix the first two issues. 1652int get_lisp_indent (void ) 1653{ 1654pos_T * pos ; 1655pos_T paren ; 1656int amount ; 1657 1658pos_T realpos = curwin -> w_cursor ; 1659curwin -> w_cursor .col = 0 ; 1660 1661if ((pos = findmatch (NULL ,'(' ))== NULL ) { 1662pos = findmatch (NULL ,'[' ); 1663 }else { 1664paren = * pos ; 1665pos = findmatch (NULL ,'[' ); 1666 1667if ((pos == NULL )|| lt (* pos ,paren )) { 1668pos = & paren ; 1669 } 1670 } 1671 1672if (pos != NULL ) { 1673// Extra trick: Take the indent of the first previous non-white 1674// line that is at the same () level. 1675amount = -1 ; 1676int parencount = 0 ; 1677 1678while (-- curwin -> w_cursor .lnum >=pos -> lnum ) { 1679if (linewhite (curwin -> w_cursor .lnum )) { 1680continue ; 1681 } 1682 1683for (char * that = get_cursor_line_ptr ();* that != NUL ;that ++ ) { 1684if (* that == ';' ) { 1685while (* (that + 1 )!= NUL ) { 1686that ++ ; 1687 } 1688continue ; 1689 } 1690 1691if (* that == '\\' ) { 1692if (* (that + 1 )!= NUL ) { 1693that ++ ; 1694 } 1695continue ; 1696 } 1697 1698if ((* that == '"' )&& (* (that + 1 )!= NUL )) { 1699while (*++ that && * that != '"' ) { 1700// Skipping escaped characters in the string 1701if (* that == '\\' ) { 1702if (*++ that == NUL ) { 1703break ; 1704 } 1705if (that [1 ]== NUL ) { 1706that ++ ; 1707break ; 1708 } 1709 } 1710 } 1711if (* that == NUL ) { 1712break ; 1713 } 1714 } 1715if ((* that == '(' )|| (* that == '[' )) { 1716parencount ++ ; 1717 }else if ((* that == ')' )|| (* that == ']' )) { 1718parencount -- ; 1719 } 1720 } 1721 1722if (parencount == 0 ) { 1723amount = get_indent (); 1724break ; 1725 } 1726 } 1727 1728if (amount == -1 ) { 1729curwin -> w_cursor .lnum = pos -> lnum ; 1730curwin -> w_cursor .col = pos -> col ; 1731colnr_T col = pos -> col ; 1732 1733char * line = get_cursor_line_ptr (); 1734 1735CharsizeArg csarg ; 1736CSType cstype = init_charsize_arg (& csarg ,curwin ,pos -> lnum ,line ); 1737 1738StrCharInfo sci = utf_ptr2StrCharInfo (line ); 1739amount = 0 ; 1740while (* sci .ptr != NUL && col > 0 ) { 1741ClusterInfo cli = utf_ClusterInfo (sci ); 1742amount += win_charsize (cstype ,amount ,sci .ptr ,sci .chr .value ,& csarg ,cli .cells ).width ; 1743sci = cli .next ; 1744col -- ; 1745 } 1746char * that = sci .ptr ; 1747 1748// Some keywords require "body" indenting rules (the 1749// non-standard-lisp ones are Scheme special forms): 1750// (let ((a 1)) instead (let ((a 1)) 1751// (...)) of (...)) 1752if (((* that == '(' )|| (* that == '[' ))&& lisp_match (that + 1 )) { 1753amount += 2 ; 1754 }else { 1755if (* that != NUL ) { 1756that ++ ; 1757amount ++ ; 1758 } 1759colnr_T firsttry = amount ; 1760 1761while (ascii_iswhite (* that )) { 1762amount += win_charsize (cstype ,amount ,that , (uint8_t )(* that ),& csarg ,1 ).width ; 1763that ++ ; 1764 } 1765 1766if (* that && (* that != ';' )) { 1767// Not a comment line. 1768// Test *that != '(' to accommodate first let/do 1769// argument if it is more than one line. 1770if ((* that != '(' )&& (* that != '[' )) { 1771firsttry ++ ; 1772 } 1773 1774parencount = 0 ; 1775 1776CharInfo ci = utf_ptr2CharInfo (that ); 1777if (((ci .value != '"' )&& (ci .value != '\'' )&& (ci .value != '#' ) 1778&& ((ci .value < '0' )|| (ci .value > '9' )))) { 1779int quotecount = 0 ; 1780while (* that && (!ascii_iswhite (ci .value )|| quotecount || parencount )) { 1781if (ci .value == '"' ) { 1782quotecount = !quotecount ; 1783 } 1784if (((ci .value == '(' )|| (ci .value == '[' ))&& !quotecount ) { 1785parencount ++ ; 1786 } 1787if (((ci .value == ')' )|| (ci .value == ']' ))&& !quotecount ) { 1788parencount -- ; 1789 } 1790if ((ci .value == '\\' )&& (* (that + 1 )!= NUL )) { 1791ClusterInfo cli = utf_ClusterInfo ((StrCharInfo ){that ,ci }); 1792amount += win_charsize (cstype ,amount ,that ,ci .value ,& csarg ,cli .cells ).width ; 1793that = cli .next .ptr ; 1794ci = cli .next .chr ; 1795 } 1796 1797ClusterInfo cli = utf_ClusterInfo ((StrCharInfo ){that ,ci }); 1798amount += win_charsize (cstype ,amount ,that ,ci .value ,& csarg ,cli .cells ).width ; 1799that = cli .next .ptr ; 1800ci = cli .next .chr ; 1801 } 1802 } 1803 1804while (ascii_iswhite (* that )) { 1805amount += win_charsize (cstype ,amount ,that , (uint8_t )(* that ),& csarg ,1 ).width ; 1806that ++ ; 1807 } 1808 1809if (!* that || (* that == ';' )) { 1810amount = firsttry ; 1811 } 1812 } 1813 } 1814 } 1815 }else { 1816amount = 0 ;// No matching '(' or '[' found, use zero indent. 1817 } 1818curwin -> w_cursor = realpos ; 1819 1820return amount ; 1821} 1822 1823static int lisp_match (char * p ) 1824{ 1825char buf [512 ]; 1826char * word = * curbuf -> b_p_lw != NUL ?curbuf -> b_p_lw :p_lispwords ; 1827 1828while (* word != NUL ) { 1829size_t len = copy_option_part (& word ,buf ,sizeof (buf ),"," ); 1830if ((strncmp (buf ,p ,len )== 0 )&& ascii_iswhite_or_nul (p [len ])) { 1831return true; 1832 } 1833 } 1834return false; 1835} 1836 1837/// Re-indent the current line, based on the current contents of it and the 1838/// surrounding lines. Fixing the cursor position seems really easy -- I'm very 1839/// confused what all the part that handles Control-T is doing that I'm not. 1840/// "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent. 1841void fixthisline (IndentGetter get_the_indent ) 1842{ 1843int amount = get_the_indent (); 1844 1845if (amount < 0 ) { 1846return ; 1847 } 1848 1849change_indent (INDENT_SET ,amount , false, true); 1850if (linewhite (curwin -> w_cursor .lnum )) { 1851Ins .did_ai = true;// delete the indent if the line stays empty 1852 } 1853} 1854 1855/// Return true if 'indentexpr' should be used for Lisp indenting. 1856/// Caller may want to check 'autoindent'. 1857bool use_indentexpr_for_lisp (void ) 1858{ 1859return curbuf -> b_p_lisp 1860&& curbuf -> b_p_inde .type != kCallbackNone 1861&& strcmp (curbuf -> b_p_lop ,"expr:1" )== 0 ; 1862} 1863 1864/// Fix indent for 'lisp' and 'cindent'. 1865void fix_indent (void ) 1866{ 1867if (p_paste ) { 1868return ;// no auto-indenting when 'paste' is set 1869 } 1870if (curbuf -> b_p_lisp && curbuf -> b_p_ai ) { 1871if (use_indentexpr_for_lisp ()) { 1872do_c_expr_indent (); 1873 }else { 1874fixthisline (get_lisp_indent ); 1875 } 1876 }else if (cindent_on ()) { 1877do_c_expr_indent (); 1878 } 1879} 1880 1881/// "indent()" function 1882void f_indent (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1883{ 1884const linenr_T lnum = tv_get_lnum (argvars ); 1885if (lnum >=1 && lnum <=curbuf -> b_ml .ml_line_count ) { 1886rettv -> vval .v_number = get_indent_lnum (lnum ); 1887 }else { 1888rettv -> vval .v_number = -1 ; 1889 } 1890} 1891 1892/// "lispindent(lnum)" function 1893void f_lispindent (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1894{ 1895const pos_T pos = curwin -> w_cursor ; 1896const linenr_T lnum = tv_get_lnum (argvars ); 1897if (lnum >=1 && lnum <=curbuf -> b_ml .ml_line_count ) { 1898curwin -> w_cursor .lnum = lnum ; 1899rettv -> vval .v_number = get_lisp_indent (); 1900curwin -> w_cursor = pos ; 1901 }else { 1902rettv -> vval .v_number = -1 ; 1903 } 1904}