robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local M ={} 2 3local echo_err =require ( 'vim._core.util' ). echo_err 4local fs =require ( 'vim.fs' ) 5 6local tag_exceptions ={ 7-- Interpret asterisk (star, '*') literal but name it 'star' 8[ '*' ] ='star' , 9[ 'g*' ] ='gstar' , 10[ '[*' ] ='[star' , 11[ ']*' ] =']star' , 12[ ':*' ] =':star' , 13[ '/*' ] ='/star' , 14[ '/\\*' ] ='/\\\\star' , 15[ '\\\\star' ] ='/\\\\star' , 16[ '"*' ] ='quotestar' , 17[ '**' ] ='starstar' , 18[ 'cpo-*' ] ='cpo-star' , 19 20-- Literal question mark '?' 21[ '?' ] ='?' , 22[ '??' ] ='??' , 23[ ':?' ] =':?' , 24[ '?<CR>' ] ='?<CR>' , 25[ 'g?' ] ='g?' , 26[ 'g?g?' ] ='g?g?' , 27[ 'g??' ] ='g??' , 28[ '-?' ] ='-?' , 29[ 'q?' ] ='q?' , 30[ 'v_g?' ] ='v_g?' , 31[ '/\\?' ] ='/\\\\?' , 32 33-- Backslash-escaping hell 34[ '/\\%(\\)' ] ='/\\\\%(\\\\)' , 35[ '/\\z(\\)' ] ='/\\\\z(\\\\)' , 36[ '\\=' ] ='\\\\=' , 37[ '\\%$' ] ='/\\\\%\\$' , 38 39-- Some expressions are literal but without the 'expr-' prefix. Note: not all 'expr-' subjects! 40[ 'expr-!=?' ] ='!=?' , 41[ 'expr-!~?' ] ='!\\~?' , 42[ 'expr-<=?' ] ='<=?' , 43[ 'expr-<?' ] ='<?' , 44[ 'expr-==?' ] ='==?' , 45[ 'expr-=~?' ] ='=\\~?' , 46[ 'expr->=?' ] ='>=?' , 47[ 'expr->?' ] ='>?' , 48[ 'expr-is?' ] ='is?' , 49[ 'expr-isnot?' ] ='isnot?' , 50} 51 52---Transform a help tag query into a search pattern for find_tags(). 53--- 54---This function converts user input from `:help {subject}` into a regex pattern that balances 55---literal matching with wildcard support. Vim help tags can contain characters that have special 56---meaning in regex (like *, ?, |), but we also want to support wildcard searches. 57--- 58---Examples: 59--- '*' --> 'star' (literal match for the * command help tag) 60--- 'buffer*' --> 'buffer.*' (wildcard: find all buffer-related tags) 61--- 'CTRL-W' --> stays as 'CTRL-W' (already in tag format) 62--- '^A' --> 'CTRL-A' (caret notation converted to tag format) 63--- 64---@param word string The help subject as entered by the user 65---@return string pattern The escaped regex pattern to search for in tag files 66function M . escape_subject ( word ) 67local replacement =tag_exceptions [ word ] 68if replacement then 69return replacement 70end 71 72-- Add prefix '/\\' to patterns starting with a backslash 73-- Examples: \S, \%^, \%(, \zs, \z1, \@<, \@=, \@<=, \_$, \_^ 74if word : match ( [[^\.$]] ) or word : match ( '^\\[%%_z@]' ) then 75word =[[/\]] .. word 76word =word : gsub ( '[$.~]' , [[\%0]] ) 77word =word : gsub ( '|' , 'bar' ) 78else 79-- Fix for bracket expressions and curly braces: 80-- '\' --> '\\' (needs to come first) 81-- '[' --> '\[' (escape the opening bracket) 82-- ':[' --> ':\[' (escape the opening bracket) 83-- '\{' --> '\\{' (for '\{' pattern matching) 84-- '(' --> '' (parentheses around option tags should be ignored) 85word =word : gsub ( [[\+]] , [[\\]] ) 86word =word : gsub ( [[^%[]] , [[\[]] ) 87word =word : gsub ( [[^:%[]] , [[:\[]] ) 88word =word : gsub ( [[^\{]] , [[\\{]] ) 89word =word : gsub ( [[^%(']] , [[']] ) 90 91word =word : gsub ( '|' , 'bar' ) 92word =word : gsub ( [["]] , 'quote' ) 93word =word : gsub ( '[$.~]' , [[\%0]] ) 94word =word : gsub ( '%*' , '.*' ) 95word =word : gsub ( '?' , '.' ) 96 97-- Handle control characters. 98-- First convert raw control chars to the caret notation 99-- E.g. 0x01 --> '^A' etc. 100---@type string 101word =word : gsub ( '([\1-\31])' , function ( ctrl_char ) 102-- '^\' needs an extra backslash 103local repr =string . char ( ctrl_char : byte () + 64 ): gsub ( [[\]] , [[\\]] ) 104return '^' .. repr 105end ) 106 107-- Change caret notation to 'CTRL-', except '^_' 108-- E.g. 'i^G^J' --> 'iCTRL-GCTRL-J' 109-- Only treat '^' as control notation when followed by a caret-notation 110-- char (a letter or one of "?@[\]^{"); otherwise leave it literal so 111-- patterns like ':set^=' are not wrongly split. '{' is included so 112-- '^{char}' matches the 'CTRL-{char}' placeholder tag. 113word =word : gsub ( '%^([%a?@\\[\\%]{^])' , 'CTRL-%1' ) 114-- Add underscores around 'CTRL-X' characters 115-- E.g. 'iCTRL-GCTRL-J' --> 'i_CTRL-G_CTRL-J' 116-- Only exception: 'CTRL-{character}' 117word =word : gsub ( '([^-_])CTRL%-' , '%1_CTRL-' ) 118word =word : gsub ( '(CTRL%-[^{])([^%u_\\-])' , '%1_%2' ) 119 120-- Skip function arguments 121-- E.g. 'abs({expr})' --> 'abs' 122-- E.g. 'abs([arg])' --> 'abs' 123word =word : gsub ( '%({.*' , '' ) 124word =word : gsub ( '%(%[.*' , '' ) 125 126-- Skip punctuation after second apostrophe/curly brace 127-- E.g. ''option',' --> ''option'' 128-- E.g. '{address},' --> '{address}' 129-- E.g. '`command`,' --> 'command' (backticks are removed too, but '``' stays '``') 130word =word : gsub ( [[^'([^']*)'.*]] , [['%1']] ) 131word =word : gsub ( [[^{([^}]*)}.*]] , '{%1}' ) 132word =word : gsub ( [[.*`([^`]+)`.*]] , '%1' ) 133end 134 135return word 136end 137 138--- Characters that are considered punctuation for trimming help tags. 139--- Dots (.) are NOT included here — they're trimmed separately as a last resort. 140local trimmable_punct ={ 141[ '(' ] =true , 142[ ')' ] =true , 143[ '<' ] =true , 144[ '>' ] =true , 145[ '[' ] =true , 146[ ']' ] =true , 147[ '{' ] =true , 148[ '}' ] =true , 149[ '`' ] =true , 150[ '|' ] =true , 151[ '"' ] =true , 152[ ',' ] =true , 153[ "'" ] =true , 154[ ' ' ] =true , 155[ '\t' ] =true , 156} 157 158--- Trim one layer of punctuation from a help tag string. 159--- Uses cursor offset to intelligently trim: if cursor is on trimmable punctuation, 160--- removes everything before cursor and skips past punctuation after cursor. 161--- 162---@param tag string The tag to trim 163---@param offset integer Cursor position within the tag (-1 if not applicable) 164---@return string? trimmed Trimmed string, or nil if unchanged 165local function trim_tag ( tag , offset ) 166if not tag or tag == '' then 167return nil 168end 169 170-- Special cases: single character tags 171if tag == '|' then 172return 'bar' 173end 174if tag == '"' then 175return 'quote' 176end 177 178local len =# tag 179-- start/end are 1-indexed inclusive positions into tag 180local s =1 181local e =len 182 183if offset >= 0 and offset < len and trimmable_punct [ tag : sub ( offset + 1 , offset + 1 )] then 184-- Heuristic: cursor is on trimmable punctuation, skip past it to the right 185s =offset + 1 186while s <= e and trimmable_punct [ tag : sub ( s , s )] do 187s =s + 1 188end 189elseif offset >= 0 and offset < len then 190-- Cursor is on non-trimmable char: find start of identifier at cursor 191local cursor_pos =offset + 1 -- 1-indexed 192while cursor_pos > s and not trimmable_punct [ tag : sub ( cursor_pos - 1 , cursor_pos - 1 )] do 193cursor_pos =cursor_pos - 1 194end 195s =cursor_pos 196else 197-- No cursor info: trim leading punctuation 198while s <= e and trimmable_punct [ tag : sub ( s , s )] do 199s =s + 1 200end 201end 202 203-- Trim trailing punctuation 204while e >= s and trimmable_punct [ tag : sub ( e , e )] do 205e =e - 1 206end 207 208-- Truncate function or generic arguments, e.g. "foo('bar')" => "foo", "Task<R...>" => "Task". 209-- But keep "()" since it's part of valid tags like "vim.fn.expand()". 210for i =s , e do 211if 212tag : sub ( i , i ) == '<' 213or ( tag : sub ( i , i ) == '(' and not ( i + 1 <= e and tag : sub ( i + 1 , i + 1 ) == ')' )) 214then 215e =i - 1 216break 217end 218end 219 220-- If nothing changed, return nil 221if s == 1 and e == len then 222return nil 223end 224 225-- If everything was trimmed, return nil 226if s > e then 227return nil 228end 229 230return tag : sub ( s , e ) 231end 232 233--- Trim namespace prefix (dots) from a help tag. 234--- Only call this if regular trimming didn't find a match. 235--- Returns the tag with the leftmost dot-separated segment removed. 236--- 237---@param tag string The tag to trim 238---@return string? trimmed Trimmed string, or nil if no dots found 239local function trim_tag_dots ( tag ) 240if not tag or tag == '' then 241return nil 242end 243local after_dot =tag : match ( '^[^.]+%.(.+)$' ) 244return after_dot 245end 246 247--- For ":help!" (bang, no args): DWIM resolve a help tag from the cursor context. 248--- Gets `<cWORD>` at cursor, tries it first, then trims punctuation and dots until a valid help 249--- tag is found. Falls back to `<cword>` (keyword at cursor) before dot-trimming. 250--- 251---@return string? resolved The resolved help tag, or nil if no match found 252function M . resolve_tag () 253local tag =vim . fn . expand ( '<cWORD>' ) --[[@as string]] 254if not tag or tag == '' then 255return nil 256end 257 258-- In type annotations, "?" means nullable rather than a help-search wildcard. 259local nullable_type =tag : match ( '^%(`([%w_.]+)[%[%]]*%?`%)$' ) 260if nullable_type and # vim . fn . getcompletion ( nullable_type , 'help' ) > 0 then 261return nullable_type 262end 263 264-- Compute cursor offset within <cWORD>. 265local line =vim . api . nvim_get_current_line () 266local col =vim . fn . col ( '.' ) -- 1-indexed 267local s =col 268-- Scan backward from col('.') to find the whitespace boundary. 269while s > 1 and not line : sub ( s - 1 , s - 1 ): match ( '%s' ) do 270s =s - 1 271end 272local offset =col - s -- 0-indexed offset within <cWORD> 273 274-- Try the original tag first. 275if # vim . fn . getcompletion ( tag , 'help' ) > 0 then 276return tag 277end 278 279-- Extract |tag| reference if the cursor is inside one (help's link syntax). 280local pipe_tag =tag : match ( '|(.+)|' ) 281if pipe_tag and # vim . fn . getcompletion ( pipe_tag , 'help' ) > 0 then 282return pipe_tag 283end 284 285-- Iteratively trim punctuation and try again, up to 10 times. 286local candidate =tag 287for _ =1 , 10 do 288local trimmed =trim_tag ( candidate , offset ) 289if not trimmed then 290break 291end 292candidate =trimmed 293-- After first trim, offset is no longer valid. 294offset =- 1 295 296if # vim . fn . getcompletion ( candidate , 'help' ) > 0 then 297return candidate 298end 299end 300 301-- Try the word (alphanumeric/underscore run) at the cursor before dot-trimming, since 302-- dot-trimming strips from the left and may move away from the cursor position. 303-- E.g. for '@lsp.type.function' with cursor on "lsp", the word is "lsp". 304-- Note: we don't use <cword> because it depends on 'iskeyword'. 305local word_s , word_e =col , col 306-- If cursor is not on a word char, find the nearest word char to the right. 307if not line : sub ( col , col ): match ( '[%w_]' ) then 308while word_s <= # line and not line : sub ( word_s , word_s ): match ( '[%w_]' ) do 309word_s =word_s + 1 310end 311word_e =word_s 312end 313while word_s > 1 and line : sub ( word_s - 1 , word_s - 1 ): match ( '[%w_]' ) do 314word_s =word_s - 1 315end 316while word_e <= # line and line : sub ( word_e , word_e ): match ( '[%w_]' ) do 317word_e =word_e + 1 318end 319word_e =word_e - 1 320local cword =line : sub ( word_s , word_e ) 321if # cword > 1 and cword ~= tag and # vim . fn . getcompletion ( cword , 'help' ) > 0 then 322return cword 323end 324 325-- Try trimming namespace dots (left-to-right). 326for _ =1 , 10 do 327local trimmed =trim_tag_dots ( candidate ) 328if not trimmed then 329break 330end 331candidate =trimmed 332 333if # vim . fn . getcompletion ( candidate , 'help' ) > 0 then 334return candidate 335end 336end 337 338-- No match found: return raw <cWORD> so the caller can show it in an error message. 339return tag 340end 341 342---Populates the |local-additions| section of a help buffer with references to locally-installed 343---help files. These are help files outside of $VIMRUNTIME (typically from plugins) whose first 344---line contains a tag (e.g. *plugin-name.txt*) and a short description. 345--- 346---For each help file found in 'runtimepath', the first line is extracted and added to the buffer 347---as a reference (converting '*tag*' to '|tag|'). If a translated version of a help file exists 348---in the same language as the current buffer (e.g. 'plugin.nlx' alongside 'plugin.txt'), the 349---translated version is preferred over the '.txt' file. 350function M . local_additions () 351local buf =vim . api . nvim_get_current_buf () 352local bufname =vim . fs . basename ( vim . api . nvim_buf_get_name ( buf )) 353 354-- "help.txt" or "help.??x" where ?? is a language code, see |help-translated|. 355local lang =bufname : match ( '^help%.(%a%a)x$' ) 356if bufname ~= 'help.txt' and not lang then 357return 358end 359 360-- Find local help files 361---@type table<string, string> 362local plugins ={} 363local pattern =lang and ( 'doc/*.{txt,%sx}' ): format ( lang ) or 'doc/*.txt' 364for _ , docpath in ipairs ( vim . api . nvim_get_runtime_file ( pattern , true )) do 365if not vim . fs . relpath ( assert ( vim . env . VIMRUNTIME ), docpath ) then 366-- '/path/to/doc/plugin.txt' --> 'plugin' 367local plugname =vim . fs . basename ( docpath ): sub ( 1 , - 5 ) 368-- prefer language-specific files over .txt 369if not plugins [ plugname ] or vim . endswith ( plugins [ plugname ], '.txt' ) then 370plugins [ plugname ] =docpath 371end 372end 373end 374 375-- Format plugin list lines 376-- Default to 78 if 'textwidth' is not set (e.g. in sandbox) 377local textwidth =math . max ( vim . bo [ buf ]. textwidth , 78 ) 378local lines ={} 379for _ , path in vim . spairs ( plugins ) do 380local fp =io . open ( path , 'r' ) 381if fp then 382local tagline =fp : read ( '*l' ) or '' 383fp : close () 384---@type string, string 385local plugname , desc =tagline : match ( '^%*([^*]+)%*%s*(.*)$' ) 386if plugname and desc then 387-- left-align taglink and right-align description by inserting spaces in between 388local plug_width =vim . fn . strdisplaywidth ( plugname ) 389local _ , concealed_chars =desc : gsub ( '|' , '' ) 390local desc_width =vim . fn . strdisplaywidth ( desc ) - concealed_chars 391-- max(l, 1) forces at least one space for if the description is too long 392local spaces =string . rep ( ' ' , math . max ( textwidth - desc_width - plug_width - 2 , 1 )) 393local fmt =string . format ( '|%s|%s%s' , plugname , spaces , desc ) 394table . insert ( lines , fmt ) 395end 396end 397end 398 399-- Add plugin list to local-additions section 400for linenr , line in ipairs ( vim . api . nvim_buf_get_lines ( buf , 0 , - 1 , false )) do 401if line : find ( '*local-additions*' , 1 , true ) then 402vim . _with ( { buf =buf , bo ={ modifiable =true , readonly =false } } , function () 403vim . api . nvim_buf_set_lines ( buf , linenr , linenr , true , lines ) 404end ) 405break 406end 407end 408end 409 410---Language code of a help file: "en" for "*.txt", "nl" for "*.nlx". See |help-translated|. 411---@param file string 412---@return string? 413local function helpfile_lang ( file ) 414local ext =file : sub ( - 4 ): lower () 415return ext == '.txt' and 'en' or ext : match ( '^%.(%a%a)x$' ) 416end 417 418---Report duplicate tags. 419---@param tags string[] sorted tags file lines 420local function report_duplicates ( tags ) 421local prevtag 422 423for i , tagline in ipairs ( tags ) do 424local curtag =tagline : match ( '^[^\t]*' ) 425if curtag == prevtag then 426local curfn =tagline : match ( '\t([^\t]*)' ) 427local prevfn =assert ( tags [ i - 1 ]): match ( '\t([^\t]*)' ) 428local filenames =prevfn ~= curfn and ( curfn .. ' and ' .. prevfn ) or curfn 429echo_err (( 'E154: Duplicate tag "%s" in %s' ): format ( curtag , filenames )) 430end 431prevtag =curtag 432end 433end 434 435local helptags_pattern ---@type vim.lpeg.Pattern 436do 437local P , S , R , B , C , Ct =vim . lpeg . P , vim . lpeg . S , vim . lpeg . R , vim . lpeg . B , vim . lpeg . C , vim . lpeg . Ct 438local any =P ( 1 ) 439local eof =- any 440local space =S ( ' \t' ) 441-- Accept LF, CRLF, and an unterminated final line. 442local newline =P ( '\r' ) ^ - 1 * P ( '\n' ) 443local line_end =newline + P ( '\r' ) ^ - 1 * eof 444local line_start =- B ( any ) + B ( P ( '\n' )) 445-- Assert surrounding whitespace without consuming it, so adjacent tags can share it. 446local tag =( line_start + B ( space )) 447* P ( '*' ) 448* C (( any - S ( '* \t|\n' )) ^ 1 ) 449* P ( '*' ) 450* # ( space + line_end ) 451-- An example continues through blank or indented lines. 452local example_line =newline + space * ( any - P ( '\n' )) ^ 0 * ( P ( '\n' ) + eof ) 453local example =( line_start + B ( P ( ' ' ))) 454* P ( '>' ) 455* R ( 'az' , '09' ) ^ 0 456* line_end 457* example_line ^ 0 458-- Skip ordinary text in spans; consume invalid markers one character at a time. 459local text =( any - S ( '*>' )) ^ 1 + any 460helptags_pattern =Ct ((( example + tag + text ) ^ 0 ) --[[@as vim.lpeg.Pattern]] ) 461end 462 463---Extract tags from {file} and add to list of tags. Modifies {tags}. 464---@param tags string[] 465---@param file string 466---@param name string Path of {file} relative to the help directory, as stored in the tags file. 467local function extract_tags ( tags , file , name ) 468local f =io . open ( file , 'r' ) 469if not f then 470echo_err (( 'E153: Unable to open %s for reading' ): format ( file )) 471return 472end 473-- Read once to avoid stdio calls and locking for every line. 474local source =assert ( f : read ( '*a' )) 475f : close () 476 477for _ , tagname in ipairs ( helptags_pattern : match ( source )) do 478tags [ # tags + 1 ] =( '%s\t%s\t/*%s*' ): format ( tagname , name , tagname : gsub ( '[\\/]' , '\\%0' )) 479end 480end 481 482--- Extract tags from helpfiles and combine in a single 'tags' file. 483--- @param helpfiles string[] list of helpfiles 484--- @param dir string Help directory; tag entries name the helpfiles relative to it. 485--- @param outpath string path to write the 'tags' file to. 486--- @param index_tag string? Filename for the "help-tags" entry, if included 487--- @param ignore_writeerr boolean don't report a tags file that cannot be written 488function M . gen_tagsfile ( helpfiles , dir , outpath , index_tag , ignore_writeerr ) 489-- Avoid scanning helpfiles when the output cannot be written (:helptags ALL). 490local f =io . open ( outpath , 'w' ) 491if not f then 492if not ignore_writeerr then 493echo_err (( 'E152: Cannot open %s for writing' ): format ( outpath )) 494end 495return 496end 497 498---@type string[] Tags file lines: "tag<Tab>file<Tab>search command". 499local tags ={} 500 501-- (1) extract tags from all files 502for _ , file in ipairs ( helpfiles ) do 503extract_tags ( tags , file , fs . relpath ( dir , file ) or fs . basename ( file )) 504end 505 506if index_tag then 507table . insert ( tags , ( 'help-tags\t%s\t1' ): format ( index_tag )) 508end 509 510-- (2) sort by byte value, as |tags-file-format| requires. 511-- PUC Lua uses strcoll(), so use C collation for this sort. 512-- The stdlib annotation omits nil, which queries the current locale. 513--- @diagnostic disable-next-line: param-type-mismatch 514local locale =assert ( os . setlocale ( nil , 'collate' )) 515os . setlocale ( 'C' , 'collate' ) 516table . sort ( tags ) 517os . setlocale ( locale , 'collate' ) 518 519-- (3) report duplicates 520report_duplicates ( tags ) 521 522-- (4) write tags to file 523for _ , tag in ipairs ( tags ) do 524f : write ( tag , '\n' ) 525end 526f : close () 527end 528 529--- Create a "tags" file for all help files in the given directory. 530--- 531--- The directory {dir} is generally a "doc" directory that contains "*.txt" 532--- helpfiles. 533--- 534--- @param dir string? Path to directory with help files. If `nil` (or |vim.NIL|), 535--- generate tags for every `doc` directory in the runtimepath. 536--- @param include_index_tag? boolean (default: false) Whether to include the "help-tags" tag. 537function M . gen_tags ( dir , include_index_tag ) 538if dir == vim . NIL then 539dir =nil 540end 541vim . validate ( 'dir' , dir , 'string' , true ) 542vim . validate ( 'include_index_tag' , include_index_tag , 'boolean' , true ) 543 544local dirs =dir and { vim . fs . normalize ( dir ) } or vim . api . nvim_get_runtime_file ( 'doc' , true ) 545local vimruntime =vim . fs . normalize ( vim . fs . joinpath ( assert ( vim . env . VIMRUNTIME ), 'doc' )) 546 547if dir and vim . fn . isdirectory ( assert ( dirs [ 1 ])) == 0 then 548echo_err (( 'E150: Not a directory: %s' ): format ( dir )) 549return 550end 551 552for _ , directory in ipairs ( dirs ) do 553-- Resolve once for traversal and relpath(), avoiding getcwd() for every file. 554-- Keep directory for messages and the VIMRUNTIME comparison. 555local absdir =vim . fs . abspath ( directory ) 556local files =vim . fs . find ( function ( name , _ ) 557return helpfile_lang ( name ) ~= nil 558end , { 559path =absdir , 560type ='file' , 561follow =true , 562limit =math . huge , 563} ) 564 565if vim . tbl_isempty ( files ) then 566echo_err (( 'E151: No match: %s' ): format ( vim . fs . joinpath ( directory , '**/*.txt' ))) 567end 568 569-- categorize helpfiles per language, see |help-translated| 570---@type table<string, string[]> 571local per_lang ={} 572for _ , file in ipairs ( files ) do 573local lang =assert ( helpfile_lang ( file )) 574per_lang [ lang ] =per_lang [ lang ] or {} 575table . insert ( per_lang [ lang ], file ) 576end 577 578for lang , langfiles in pairs ( per_lang ) do 579-- English is an exception: "*.txt" files generate the "tags" file. 580local tagsfile =lang == 'en' and 'tags' or ( 'tags-%s' ): format ( lang ) 581local outpath =vim . fs . joinpath ( directory , tagsfile ) 582-- ":helptags ALL" walks 'runtimepath', which may contain read-only directories. 583local ignore_writeerr =dir == nil 584M . gen_tagsfile ( 585langfiles , 586absdir , 587outpath , 588( include_index_tag or directory == vimruntime ) and tagsfile or nil , 589ignore_writeerr 590) 591end 592end 593end 594 595return M