robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
387.9 KiB9731 linesraw
1" Creator:    Charles E Campbell
2" Previous Maintainer: Luca Saccarola <github.e41mv@aleeas.com>
3" Maintainer: This runtime file is looking for a new maintainer.
4" Last Change: 2026 Sep 07
5" Copyright:  Copyright (C) 2016 Charles E. Campbell {{{1
6"             Permission is hereby granted to use and distribute this code,
7"             with or without modifications, provided that this copyright
8"             notice is copied with it. Like anything else that's free,
9"             netrw.vim, netrwPlugin.vim, and netrwSettings.vim are provided
10"             *as is* and come with no warranty of any kind, either
11"             expressed or implied. By using this plugin, you agree that
12"             in no event will the copyright holder be liable for any damages
13"             resulting from the use of this software.
14"
15" Note: the code here was started in 1999 under a much earlier version of vim.  The directory browsing
16"       code was written using vim v6, which did not have Lists (Lists were first offered with vim-v7).
17
18" Load Once: {{{1
19if &cp || exists("g:loaded_netrw")
20    finish
21endif
22
23let g:loaded_netrw = "v184"
24
25if !has("patch-9.1.1054") && !has('nvim')
26    echoerr 'netrw needs Vim v9.1.1054'
27    finish
28endif
29
30let s:keepcpo= &cpo
31setl cpo&vim
32
33"  Netrw Variables: {{{1
34
35" s:NetrwInit: initializes variables if they haven't been defined {{{2
36
37function s:NetrwInit(name, default)
38    if !exists(a:name)
39        let {a:name} = a:default
40    endif
41endfunction
42
43"  Netrw Constants: {{{2
44call s:NetrwInit("g:netrw_dirhistcnt",0)
45if !exists("s:LONGLIST")
46  call s:NetrwInit("s:THINLIST",0)
47  call s:NetrwInit("s:LONGLIST",1)
48  call s:NetrwInit("s:WIDELIST",2)
49  call s:NetrwInit("s:TREELIST",3)
50  call s:NetrwInit("s:MAXLIST" ,4)
51endif
52
53" Default option values: {{{2
54call s:NetrwInit("g:netrw_localcopycmdopt","")
55call s:NetrwInit("g:netrw_localcopydircmdopt","")
56call s:NetrwInit("g:netrw_localmkdiropt","")
57call s:NetrwInit("g:netrw_localmovecmdopt","")
58
59" Default values for netrw's global protocol variables {{{2
60
61if !exists("g:netrw_dav_cmd")
62  if executable("cadaver")
63    let g:netrw_dav_cmd   = "cadaver"
64  elseif executable("curl")
65    let g:netrw_dav_cmd   = "curl"
66  else
67    let g:netrw_dav_cmd   = ""
68  endif
69endif
70if !exists("g:netrw_fetch_cmd")
71  if executable("fetch")
72    let g:netrw_fetch_cmd = "fetch -o"
73  else
74    let g:netrw_fetch_cmd = ""
75  endif
76endif
77if !exists("g:netrw_file_cmd")
78  if executable("elinks")
79    call s:NetrwInit("g:netrw_file_cmd","elinks")
80  elseif executable("links")
81    call s:NetrwInit("g:netrw_file_cmd","links")
82  endif
83endif
84if !exists("g:netrw_ftp_cmd")
85  let g:netrw_ftp_cmd   = "ftp"
86endif
87let s:netrw_ftp_cmd= g:netrw_ftp_cmd
88if !exists("g:netrw_ftp_options")
89  let g:netrw_ftp_options= "-i -n"
90endif
91if !exists("g:netrw_http_cmd")
92  if executable("wget")
93    let g:netrw_http_cmd  = "wget"
94    call s:NetrwInit("g:netrw_http_xcmd","-q -O")
95  elseif executable("curl")
96    let g:netrw_http_cmd  = "curl"
97    call s:NetrwInit("g:netrw_http_xcmd","-L -o")
98  elseif executable("elinks")
99    let g:netrw_http_cmd = "elinks"
100    call s:NetrwInit("g:netrw_http_xcmd","-source >")
101  elseif executable("fetch")
102    let g:netrw_http_cmd  = "fetch"
103    call s:NetrwInit("g:netrw_http_xcmd","-o")
104  elseif executable("links")
105    let g:netrw_http_cmd = "links"
106    call s:NetrwInit("g:netrw_http_xcmd","-http.extra-header ".shellescape("Accept-Encoding: identity", 1)." -source >")
107  else
108    let g:netrw_http_cmd  = ""
109  endif
110endif
111call s:NetrwInit("g:netrw_http_put_cmd","curl -T")
112call s:NetrwInit("g:netrw_keepj","keepj")
113call s:NetrwInit("g:netrw_rcp_cmd"  , "rcp")
114call s:NetrwInit("g:netrw_rsync_cmd", "rsync")
115call s:NetrwInit("g:netrw_rsync_sep", "/")
116if !exists("g:netrw_scp_cmd")
117  if executable("scp")
118    call s:NetrwInit("g:netrw_scp_cmd" , "scp -q")
119  elseif executable("pscp")
120    call s:NetrwInit("g:netrw_scp_cmd", 'pscp -q')
121  else
122    call s:NetrwInit("g:netrw_scp_cmd" , "scp -q")
123  endif
124endif
125call s:NetrwInit("g:netrw_sftp_cmd" , "sftp")
126call s:NetrwInit("g:netrw_ssh_cmd"  , "ssh")
127
128if has("win32")
129      \ && exists("g:netrw_use_nt_rcp")
130      \ && g:netrw_use_nt_rcp
131      \ && executable( $SystemRoot .'/system32/rcp.exe')
132  let s:netrw_has_nt_rcp = 1
133  let s:netrw_rcpmode    = '-b'
134else
135  let s:netrw_has_nt_rcp = 0
136  let s:netrw_rcpmode    = ''
137endif
138
139" Default values for netrw's global variables {{{2
140" Cygwin Detection ------- {{{3
141if !exists("g:netrw_cygwin")
142  if has("win32unix") && &shell =~ '\%(\<bash\>\|\<zsh\>\)\%(\.exe\)\=$'
143    let g:netrw_cygwin= 1
144  else
145    let g:netrw_cygwin= 0
146  endif
147endif
148" Default values - a-c ---------- {{{3
149call s:NetrwInit("g:netrw_alto"        , &sb)
150call s:NetrwInit("g:netrw_altv"        , &spr)
151call s:NetrwInit("g:netrw_banner"      , 1)
152call s:NetrwInit("g:netrw_browse_split", 0)
153call s:NetrwInit("g:netrw_bufsettings" , "noma nomod nonu nobl nowrap ro nornu")
154call s:NetrwInit("g:netrw_chgwin"      , -1)
155call s:NetrwInit("g:netrw_clipboard"   , 1)
156call s:NetrwInit("g:netrw_compress"    , "gzip")
157call s:NetrwInit("g:netrw_ctags"       , "ctags")
158call s:NetrwInit("g:netrw_cursor"      , 2)
159let s:netrw_usercul = &cursorline
160let s:netrw_usercuc = &cursorcolumn
161call s:NetrwInit("g:netrw_cygdrive","/cygdrive")
162" Default values - d-g ---------- {{{3
163call s:NetrwInit("s:didstarstar",0)
164call s:NetrwInit("g:netrw_dirhistcnt"      , 0)
165let s:xz_opt = has('unix') ? "XZ_OPT=-T0" :
166      \ (has("win32") && &shell =~? '\vcmd(\.exe)?$' ?
167      \ "setx XZ_OPT=-T0 &&" : "")
168call s:NetrwInit("g:netrw_decompress", {
169            \ '.lz4': 'lz4 -d',
170            \ '.lzo': 'lzop -d',
171            \ '.lz': 'lzip -dk',
172            \ '.7z': '7za x',
173            \ '.001': '7za x',
174            \ '.zip': 'unzip',
175            \ '.bz': 'bunzip2 -k',
176            \ '.bz2': 'bunzip2 -k',
177            \ '.gz': 'gunzip -k',
178            \ '.lzma': 'unlzma -T0 -k',
179            \ '.xz': 'unxz -T0 -k',
180            \ '.zst': 'zstd -T0 -d',
181            \ '.Z': 'uncompress -k',
182            \ '.tar': 'tar -xvf',
183            \ '.tar.bz': 'tar -xvjf',
184            \ '.tar.bz2': 'tar -xvjf',
185            \ '.tbz': 'tar -xvjf',
186            \ '.tbz2': 'tar -xvjf',
187            \ '.tar.gz': 'tar -xvzf',
188            \ '.tgz': 'tar -xvzf',
189            \ '.tar.lzma': s:xz_opt .. ' tar -xvf --lzma',
190            \ '.tlz': s:xz_opt .. ' tar -xvf --lzma',
191            \ '.tar.xz': s:xz_opt .. ' tar -xvfJ',
192            \ '.txz': s:xz_opt .. ' tar -xvfJ',
193            \ '.tar.zst': s:xz_opt .. ' tar -xvf --use-compress-program=unzstd',
194            \ '.tzst': s:xz_opt .. ' tar -xvf --use-compress-program=unzstd',
195            \ '.rar': (executable("unrar")?"unrar x -ad":"rar x -ad"),
196            \ })
197unlet s:xz_opt
198call s:NetrwInit("g:netrw_dirhistmax"       , 10)
199call s:NetrwInit("g:netrw_fastbrowse"       , 1)
200call s:NetrwInit("g:netrw_ftp_browse_reject", '^total\s\+\d\+$\|^Trying\s\+\d\+.*$\|^KERBEROS_V\d rejected\|^Security extensions not\|No such file\|: connect to address [0-9a-fA-F:]*: No route to host$')
201if !exists("g:netrw_ftp_list_cmd")
202  if has("unix") || g:netrw_cygwin
203    let g:netrw_ftp_list_cmd     = "ls -lF"
204    let g:netrw_ftp_timelist_cmd = "ls -tlF"
205    let g:netrw_ftp_sizelist_cmd = "ls -slF"
206  else
207    let g:netrw_ftp_list_cmd     = "dir"
208    let g:netrw_ftp_timelist_cmd = "dir"
209    let g:netrw_ftp_sizelist_cmd = "dir"
210  endif
211endif
212call s:NetrwInit("g:netrw_ftpmode",'binary')
213" Default values - h-lh ---------- {{{3
214call s:NetrwInit("g:netrw_hide",1)
215if !exists("g:netrw_ignorenetrc")
216  if &shell =~ '\c\<\%(cmd\|4nt\)\.exe$'
217    let g:netrw_ignorenetrc= 1
218  else
219    let g:netrw_ignorenetrc= 0
220  endif
221endif
222call s:NetrwInit("g:netrw_keepdir",1)
223if !exists("g:netrw_list_cmd")
224  if g:netrw_scp_cmd =~ '^pscp' && executable("pscp")
225    if exists("g:netrw_list_cmd_options")
226      let g:netrw_list_cmd= g:netrw_scp_cmd." -ls USEPORT HOSTNAME: ".g:netrw_list_cmd_options
227    else
228      let g:netrw_list_cmd= g:netrw_scp_cmd." -ls USEPORT HOSTNAME:"
229    endif
230  elseif executable(g:netrw_ssh_cmd)
231    " provide a scp-based default listing command
232    if exists("g:netrw_list_cmd_options")
233      let g:netrw_list_cmd= g:netrw_ssh_cmd." USEPORT HOSTNAME ls -FLa ".g:netrw_list_cmd_options
234    else
235      let g:netrw_list_cmd= g:netrw_ssh_cmd." USEPORT HOSTNAME ls -FLa"
236    endif
237  else
238    let g:netrw_list_cmd= ""
239  endif
240endif
241call s:NetrwInit("g:netrw_list_hide","")
242" Default values - lh-lz ---------- {{{3
243if !exists("g:netrw_localcmdshell")
244  let g:netrw_localcmdshell= ""
245endif
246
247if !exists("g:netrw_localcopycmd")
248    let g:netrw_localcopycmd = 'cp'
249    let g:netrw_localcopycmdopt = ''
250
251    if has("win32") && !g:netrw_cygwin
252        let g:netrw_localcopycmd = $COMSPEC
253        let g:netrw_localcopycmdopt = ' /c copy'
254    endif
255endif
256
257if !exists("g:netrw_localcopydircmd")
258    let g:netrw_localcopydircmd = 'cp'
259    let g:netrw_localcopydircmdopt = '-R'
260
261    if has("win32") && !g:netrw_cygwin
262        let g:netrw_localcopydircmd = "xcopy"
263        let g:netrw_localcopydircmdopt = " /E /I /H /C /Y"
264    endif
265endif
266
267if !exists("g:netrw_localmkdir")
268  if has("win32")
269    if g:netrw_cygwin
270      let g:netrw_localmkdir= "mkdir"
271    else
272      let g:netrw_localmkdir = $COMSPEC
273      let g:netrw_localmkdiropt= " /c mkdir"
274    endif
275  else
276    let g:netrw_localmkdir= "mkdir"
277  endif
278endif
279
280if !exists("g:netrw_localmovecmd")
281  if has("win32")
282    if g:netrw_cygwin
283      let g:netrw_localmovecmd= "mv"
284    else
285      let g:netrw_localmovecmd = $COMSPEC
286      let g:netrw_localmovecmdopt= " /c move"
287    endif
288  elseif has("unix") || has("macunix")
289    let g:netrw_localmovecmd= "mv"
290  else
291    let g:netrw_localmovecmd= ""
292  endif
293endif
294
295call s:NetrwInit("g:netrw_liststyle"  , s:THINLIST)
296" sanity checks
297if g:netrw_liststyle < 0 || g:netrw_liststyle >= s:MAXLIST
298  let g:netrw_liststyle= s:THINLIST
299endif
300if g:netrw_liststyle == s:LONGLIST && g:netrw_scp_cmd !~ '^pscp'
301  let g:netrw_list_cmd= g:netrw_list_cmd." -l"
302endif
303" Default values - m-r ---------- {{{3
304call s:NetrwInit("g:netrw_markfileesc"   , '*./[\~')
305call s:NetrwInit("g:netrw_maxfilenamelen", 32)
306call s:NetrwInit("g:netrw_menu"          , 1)
307call s:NetrwInit("g:netrw_mkdir_cmd"     , g:netrw_ssh_cmd." USEPORT HOSTNAME mkdir")
308call s:NetrwInit("g:netrw_mousemaps"     , (exists("+mouse") && &mouse =~# '[anh]'))
309call s:NetrwInit("g:netrw_retmap"        , 0)
310if has("unix") || g:netrw_cygwin
311  call s:NetrwInit("g:netrw_chgperm"       , "chmod PERM FILENAME")
312elseif has("win32")
313  call s:NetrwInit("g:netrw_chgperm"       , "cacls FILENAME /e /p PERM")
314else
315  call s:NetrwInit("g:netrw_chgperm"       , "chmod PERM FILENAME")
316endif
317call s:NetrwInit("g:netrw_preview"       , 0)
318call s:NetrwInit("g:netrw_scpport"       , "-P")
319call s:NetrwInit("g:netrw_servername"    , "NETRWSERVER")
320call s:NetrwInit("g:netrw_sshport"       , "-p")
321call s:NetrwInit("g:netrw_rename_cmd"    , g:netrw_ssh_cmd." USEPORT HOSTNAME mv")
322call s:NetrwInit("g:netrw_rm_cmd"        , g:netrw_ssh_cmd." USEPORT HOSTNAME rm")
323call s:NetrwInit("g:netrw_rmdir_cmd"     , g:netrw_ssh_cmd." USEPORT HOSTNAME rmdir")
324call s:NetrwInit("g:netrw_rmf_cmd"       , g:netrw_ssh_cmd." USEPORT HOSTNAME rm -f ")
325" Default values - q-s ---------- {{{3
326call s:NetrwInit("g:netrw_quickhelp",0)
327let s:QuickHelp= ["-:go up dir  D:delete  R:rename  s:sort-by  x:special",
328      \              "(create new)  %:file  d:directory",
329      \              "(windows split&open) o:horz  v:vert  p:preview",
330      \              "i:style  qf:file info  O:obtain  r:reverse",
331      \              "(marks)  mf:mark file  mt:set target  mm:move  mc:copy",
332      \              "(bookmarks)  mb:make  mB:delete  qb:list  gb:go to",
333      \              "(history)  qb:list  u:go up  U:go down",
334      \              "(targets)  mt:target Tb:use bookmark  Th:use history"]
335" g:netrw_sepchr: picking a character that doesn't appear in filenames that can be used to separate priority from filename
336call s:NetrwInit("g:netrw_sepchr"        , (&enc == "euc-jp")? "\<Char-0x01>" : "\<Char-0xff>")
337if !exists("g:netrw_keepj") || g:netrw_keepj == "keepj"
338  call s:NetrwInit("s:netrw_silentxfer"    , (exists("g:netrw_silent") && g:netrw_silent != 0)? "sil keepj " : "keepj ")
339else
340  call s:NetrwInit("s:netrw_silentxfer"    , (exists("g:netrw_silent") && g:netrw_silent != 0)? "sil " : " ")
341endif
342call s:NetrwInit("g:netrw_sort_by"       , "name") " alternatives: date                                      , size
343call s:NetrwInit("g:netrw_sort_options"  , "")
344call s:NetrwInit("g:netrw_sort_direction", "normal") " alternative: reverse  (z y x ...)
345if !exists("g:netrw_sort_sequence")
346    let g:netrw_sort_sequence = !empty(&suffixes)
347                \ ? printf('[\/]$,*,\%(%s\)[*@]\=$', &suffixes->split(',')->map('escape(v:val, ".*$~")')->join('\|'))
348                \ : '[\/]$,*'
349endif
350call s:NetrwInit("g:netrw_special_syntax"   , 0)
351call s:NetrwInit("g:netrw_ssh_browse_reject", '^total\s\+\d\+$')
352call s:NetrwInit("g:netrw_use_noswf"        , 1)
353call s:NetrwInit("g:netrw_sizestyle"        ,"b")
354" Default values - t-w ---------- {{{3
355call s:NetrwInit("g:netrw_timefmt","%c")
356if !exists("g:netrw_xstrlen")
357  if exists("g:Align_xstrlen")
358    let g:netrw_xstrlen= g:Align_xstrlen
359  elseif exists("g:drawit_xstrlen")
360    let g:netrw_xstrlen= g:drawit_xstrlen
361  elseif &enc == "latin1" || !has("multi_byte")
362    let g:netrw_xstrlen= 0
363  else
364    let g:netrw_xstrlen= 1
365  endif
366endif
367call s:NetrwInit("g:NetrwTopLvlMenu","Netrw.")
368call s:NetrwInit("g:netrw_winsize",50)
369call s:NetrwInit("g:netrw_wiw",1)
370if g:netrw_winsize > 100|let g:netrw_winsize= 100|endif
371" Default values for netrw's script variables: {{{2
372call s:NetrwInit("g:netrw_fname_escape",' ?&;%')
373if has("win32")
374  call s:NetrwInit("g:netrw_glob_escape",'*?`{[]$')
375else
376  call s:NetrwInit("g:netrw_glob_escape",'*[]?`{~$\')
377endif
378call s:NetrwInit("g:netrw_menu_escape",'.&? \|')
379call s:NetrwInit("s:netrw_map_escape","<|\n\r\\\<C-V>\"")
380if has("gui_running") && (&enc == 'utf-8' || &enc == 'utf-16' || &enc == 'ucs-4')
381  let s:treedepthstring= "│ "
382else
383  let s:treedepthstring= "| "
384endif
385call s:NetrwInit("s:netrw_posn", {})
386
387" BufEnter event ignored by decho when following variable is true
388"  Has a side effect that doau BufReadPost doesn't work, so
389"  files read by network transfer aren't appropriately highlighted.
390
391"  Netrw Initialization: {{{1
392
393au WinEnter * if &ft == "netrw" | call s:NetrwInsureWinVars() | endif
394
395if g:netrw_keepj =~# "keepj"
396  com! -nargs=*  NetrwKeepj      keepj <args>
397else
398  let g:netrw_keepj= ""
399  com! -nargs=*  NetrwKeepj      <args>
400endif
401
402"  Netrw Utility Functions: {{{1
403" netrw#Explore: launch the local browser in the directory of the current file {{{2
404"          indx:  == -1: Nexplore
405"                 == -2: Pexplore
406"                 ==  +: this is overloaded:
407"                      * If Nexplore/Pexplore is in use, then this refers to the
408"                        indx'th item in the w:netrw_explore_list[] of items which
409"                        matched the */pattern **/pattern *//pattern **//pattern
410"                      * If Hexplore or Vexplore, then this will override
411"                        g:netrw_winsize to specify the qty of rows or columns the
412"                        newly split window should have.
413"          dosplit==0: the window will be split iff the current file has been modified and hidden not set
414"          dosplit==1: the window will be split before running the local browser
415"          style == 0: Explore     style == 1: Explore!
416"                == 2: Hexplore    style == 3: Hexplore!
417"                == 4: Vexplore    style == 5: Vexplore!
418"                == 6: Texplore
419function netrw#Explore(indx,dosplit,style,...)
420  if !exists("b:netrw_curdir")
421    let b:netrw_curdir= netrw#fs#Cwd(0)
422  endif
423
424  " record current file for Rexplore's benefit
425  if &ft != "netrw"
426    let w:netrw_rexfile= expand("%:p")
427  endif
428
429  " record current directory
430  let curdir     = simplify(b:netrw_curdir)
431  if !g:netrw_cygwin && has("win32")
432    let curdir= substitute(curdir,'\','/','g')
433  endif
434  let curfiledir = substitute(expand("%:p"),'^\(.*[/\\]\)[^/\\]*$','\1','e')
435  if &buftype == "terminal"
436      let curfiledir = curdir
437  endif
438
439  " using completion, directories with spaces in their names (thanks, Bill Gates, for a truly dumb idea)
440  " will end up with backslashes here.  Solution: strip off backslashes that precede white space and
441  " try Explore again.
442  if a:0 > 0
443    if a:1 =~ "\\\s" && !filereadable(s:NetrwFile(a:1)) && !isdirectory(s:NetrwFile(a:1))
444      let a1 = substitute(a:1, '\\\(\s\)', '\1', 'g')
445      if a1 != a:1
446        call netrw#Explore(a:indx, a:dosplit, a:style, a1)
447        return
448      endif
449    endif
450  endif
451
452  " save registers
453  if !has('nvim') && has("clipboard") && g:netrw_clipboard
454    sil! let keepregstar = @*
455    sil! let keepregplus = @+
456  endif
457  sil! let keepregslash= @/
458
459  " if   dosplit
460  " -or- buffer is not a terminal AND file has been modified AND file not hidden when abandoned
461  " -or- Texplore used
462  if a:dosplit || (&buftype != "terminal" && &modified && &hidden == 0 && &bufhidden != "hide") || a:style == 6
463    call s:SaveWinVars()
464    let winsz= g:netrw_winsize
465    if a:indx > 0
466      let winsz= a:indx
467    endif
468
469    if a:style == 0      " Explore, Sexplore
470      let winsz= (winsz > 0)? (winsz*winheight(0))/100 : -winsz
471      if winsz == 0|let winsz= ""|endif
472      exe "noswapfile ".(g:netrw_alto ? "below " : "above ").winsz."wincmd s"
473
474    elseif a:style == 1  " Explore!, Sexplore!
475      let winsz= (winsz > 0)? (winsz*winwidth(0))/100 : -winsz
476      if winsz == 0|let winsz= ""|endif
477      exe "keepalt noswapfile ".(g:netrw_altv ? "rightbelow " : "leftabove ").winsz."wincmd v"
478
479    elseif a:style == 2  " Hexplore
480      let winsz= (winsz > 0)? (winsz*winheight(0))/100 : -winsz
481      if winsz == 0|let winsz= ""|endif
482      exe "keepalt noswapfile ".(g:netrw_alto ? "below " : "above ").winsz."wincmd s"
483
484    elseif a:style == 3  " Hexplore!
485      let winsz= (winsz > 0)? (winsz*winheight(0))/100 : -winsz
486      if winsz == 0|let winsz= ""|endif
487      exe "keepalt noswapfile ".(!g:netrw_alto ? "below " : "above ").winsz."wincmd s"
488
489    elseif a:style == 4  " Vexplore
490      let winsz= (winsz > 0)? (winsz*winwidth(0))/100 : -winsz
491      if winsz == 0|let winsz= ""|endif
492      exe "keepalt noswapfile ".(g:netrw_altv ? "rightbelow " : "leftabove ").winsz."wincmd v"
493
494    elseif a:style == 5  " Vexplore!
495      let winsz= (winsz > 0)? (winsz*winwidth(0))/100 : -winsz
496      if winsz == 0|let winsz= ""|endif
497      exe "keepalt noswapfile ".(!g:netrw_altv ? "rightbelow " : "leftabove ").winsz."wincmd v"
498
499    elseif a:style == 6  " Texplore
500      call s:SaveBufVars()
501      exe "keepalt tabnew ".fnameescape(curdir)
502      call s:RestoreBufVars()
503    endif
504    call s:RestoreWinVars()
505  endif
506  NetrwKeepj norm! 0
507
508  if a:0 > 0
509    if a:1 =~ '^\~' && (has("unix") || has("win32") || g:netrw_cygwin)
510      let dirname= simplify(substitute(a:1,'^\~',escape(expand("$HOME"),'\&~'),''))
511    elseif a:1 == '.'
512      let dirname= simplify(exists("b:netrw_curdir")? b:netrw_curdir : getcwd())
513      if dirname !~ '/$'
514        let dirname= dirname."/"
515      endif
516    elseif a:1 =~ '\$'
517      let dirname= simplify(expand(a:1))
518    elseif a:1 !~ '^\*\{1,2}/' && a:1 !~ '^\a\{3,}://'
519      let dirname= simplify(a:1)
520    else
521      let dirname= a:1
522    endif
523  else
524    " clear explore
525    call s:NetrwClearExplore()
526    return
527  endif
528  " Win32: Use forward slashes
529  if !g:netrw_cygwin && has("win32")
530    let dirname= substitute(dirname,'\','/','g')
531  endif
532
533  if dirname =~ '\.\./\=$'
534    let dirname= simplify(fnamemodify(dirname,':p:h'))
535  elseif dirname =~ '\.\.' || dirname == '.'
536    let dirname= simplify(fnamemodify(dirname,':p'))
537  endif
538
539  if dirname =~ '^\*//'
540    " starpat=1: Explore *//pattern   (current directory only search for files containing pattern)
541    let pattern= substitute(dirname,'^\*//\(.*\)$','\1','')
542    let starpat= 1
543    if &hls | let keepregslash= s:ExplorePatHls(pattern) | endif
544
545  elseif dirname =~ '^\*\*//'
546    " starpat=2: Explore **//pattern  (recursive descent search for files containing pattern)
547    let pattern= substitute(dirname,'^\*\*//','','')
548    let starpat= 2
549
550  elseif dirname =~ '/\*\*/'
551    " handle .../**/.../filepat
552    let prefixdir= substitute(dirname,'^\(.\{-}\)\*\*.*$','\1','')
553    if prefixdir =~ '^/' || (prefixdir =~ '^\a:/' && has("win32"))
554      let b:netrw_curdir = prefixdir
555    else
556      let b:netrw_curdir= getcwd().'/'.prefixdir
557    endif
558    let dirname= substitute(dirname,'^.\{-}\(\*\*/.*\)$','\1','')
559    let starpat= 4
560
561  elseif dirname =~ '^\*/'
562    " case starpat=3: Explore */filepat   (search in current directory for filenames matching filepat)
563    let starpat= 3
564
565  elseif dirname=~ '^\*\*/'
566    " starpat=4: Explore **/filepat  (recursive descent search for filenames matching filepat)
567    let starpat= 4
568
569  else
570    let starpat= 0
571  endif
572
573  if starpat == 0 && a:indx >= 0
574    if dirname == ""
575      let dirname= curfiledir
576    endif
577    " [Explore Hexplore Vexplore Sexplore] [dirname]
578    if dirname =~# '^scp://' || dirname =~ '^ftp://'
579      call netrw#Nread(2,dirname)
580    else
581      if dirname == ""
582        let dirname= netrw#fs#Cwd(0)
583      elseif has("win32") && !g:netrw_cygwin
584        " Windows : check for a drive specifier, or else for a remote share name ('\\Foo' or '//Foo',
585        " depending on whether backslashes have been converted to forward slashes by earlier code).
586        if dirname !~ '^[a-zA-Z]:' && dirname !~ '^\\\\\w\+' && dirname !~ '^//\w\+'
587          let dirname= b:netrw_curdir."/".dirname
588        endif
589      elseif dirname !~ '^/'
590        let dirname= b:netrw_curdir."/".dirname
591      endif
592      call netrw#LocalBrowseCheck(dirname)
593    endif
594    if exists("w:netrw_bannercnt")
595      " done to handle P08-Ingelrest. :Explore will _Always_ go to the line just after the banner.
596      " If one wants to return the same place in the netrw window, use :Rex instead.
597      exe w:netrw_bannercnt
598    endif
599
600
601  " starpat=1: Explore *//pattern  (current directory only search for files containing pattern)
602  " starpat=2: Explore **//pattern (recursive descent search for files containing pattern)
603  " starpat=3: Explore */filepat   (search in current directory for filenames matching filepat)
604  " starpat=4: Explore **/filepat  (recursive descent search for filenames matching filepat)
605  elseif a:indx <= 0
606    " Nexplore, Pexplore, Explore: handle starpat
607    if !mapcheck("<s-up>","n") && !mapcheck("<s-down>","n") && exists("b:netrw_curdir")
608      let s:didstarstar= 1
609      nnoremap <buffer> <silent> <s-up>   :Pexplore<cr>
610      nnoremap <buffer> <silent> <s-down> :Nexplore<cr>
611    endif
612
613    if has("path_extra")
614      if !exists("w:netrw_explore_indx")
615        let w:netrw_explore_indx= 0
616      endif
617
618      let indx = a:indx
619
620      if indx == -1
621        " Nexplore
622        if !exists("w:netrw_explore_list") " sanity check
623          call netrw#msg#Notify('WARNING', 'using Nexplore or <s-down> improperly; see help for netrw-starstar')
624          if !has('nvim') && has("clipboard") && g:netrw_clipboard
625            if @* != keepregstar | sil! let @* = keepregstar | endif
626            if @+ != keepregplus | sil! let @+ = keepregplus | endif
627          endif
628          sil! let @/ = keepregslash
629          return
630        endif
631        let indx= w:netrw_explore_indx
632        if indx < 0                        | let indx= 0                           | endif
633        if indx >= w:netrw_explore_listlen | let indx= w:netrw_explore_listlen - 1 | endif
634        let curfile= w:netrw_explore_list[indx]
635        while indx < w:netrw_explore_listlen && curfile == w:netrw_explore_list[indx]
636          let indx= indx + 1
637        endwhile
638        if indx >= w:netrw_explore_listlen | let indx= w:netrw_explore_listlen - 1 | endif
639
640      elseif indx == -2
641        " Pexplore
642        if !exists("w:netrw_explore_list") " sanity check
643          call netrw#msg#Notify('WARNING', 'using Pexplore or <s-up> improperly; see help for netrw-starstar')
644          if !has('nvim') && has("clipboard") && g:netrw_clipboard
645            if @* != keepregstar | sil! let @* = keepregstar | endif
646            if @+ != keepregplus | sil! let @+ = keepregplus | endif
647          endif
648          sil! let @/ = keepregslash
649          return
650        endif
651        let indx= w:netrw_explore_indx
652        if indx < 0                        | let indx= 0                           | endif
653        if indx >= w:netrw_explore_listlen | let indx= w:netrw_explore_listlen - 1 | endif
654        let curfile= w:netrw_explore_list[indx]
655        while indx >= 0 && curfile == w:netrw_explore_list[indx]
656          let indx= indx - 1
657        endwhile
658        if indx < 0                        | let indx= 0                           | endif
659
660      else
661        " Explore -- initialize
662        " build list of files to Explore with Nexplore/Pexplore
663        NetrwKeepj keepalt call s:NetrwClearExplore()
664        let w:netrw_explore_indx= 0
665        if !exists("b:netrw_curdir")
666          let b:netrw_curdir= getcwd()
667        endif
668
669        " switch on starpat to build the w:netrw_explore_list of files
670        if starpat == 1
671          " starpat=1: Explore *//pattern  (current directory only search for files containing pattern)
672          try
673            exe "NetrwKeepj noautocmd vimgrep /".pattern."/gj ".fnameescape(b:netrw_curdir)."/*"
674          catch /^Vim\%((\a\+)\)\=:E480/
675            call netrw#msg#Notify('WARNING', printf("no match with pattern<%s>", pattern))
676            return
677          endtry
678          let w:netrw_explore_list = s:NetrwExploreListUniq(map(getqflist(),'bufname(v:val.bufnr)'))
679          if &hls | let keepregslash= s:ExplorePatHls(pattern) | endif
680
681        elseif starpat == 2
682          " starpat=2: Explore **//pattern (recursive descent search for files containing pattern)
683          try
684            exe "sil NetrwKeepj noautocmd keepalt vimgrep /".pattern."/gj "."**/*"
685          catch /^Vim\%((\a\+)\)\=:E480/
686            call netrw#msg#Notify('WARNING', printf('no files matched pattern<%s>', pattern))
687            if &hls | let keepregslash= s:ExplorePatHls(pattern) | endif
688            if !has('nvim') && has("clipboard") && g:netrw_clipboard
689              if @* != keepregstar | sil! let @* = keepregstar | endif
690              if @+ != keepregplus | sil! let @+ = keepregplus | endif
691            endif
692            sil! let @/ = keepregslash
693            return
694          endtry
695          let s:netrw_curdir       = b:netrw_curdir
696          let w:netrw_explore_list = getqflist()
697          let w:netrw_explore_list = s:NetrwExploreListUniq(map(w:netrw_explore_list,'s:netrw_curdir."/".bufname(v:val.bufnr)'))
698          if &hls | let keepregslash= s:ExplorePatHls(pattern) | endif
699
700        elseif starpat == 3
701          " starpat=3: Explore */filepat   (search in current directory for filenames matching filepat)
702          let filepat= substitute(dirname,'^\*/','','')
703          let filepat= substitute(filepat,'^[%#<]','\\&','')
704          let w:netrw_explore_list= s:NetrwExploreListUniq(split(expand(b:netrw_curdir."/".filepat),'\n'))
705          if &hls | let keepregslash= s:ExplorePatHls(filepat) | endif
706
707        elseif starpat == 4
708          " starpat=4: Explore **/filepat  (recursive descent search for filenames matching filepat)
709          let w:netrw_explore_list= s:NetrwExploreListUniq(split(expand(b:netrw_curdir."/".dirname),'\n'))
710          if &hls | let keepregslash= s:ExplorePatHls(dirname) | endif
711        endif " switch on starpat to build w:netrw_explore_list
712
713        let w:netrw_explore_listlen = len(w:netrw_explore_list)
714
715        if w:netrw_explore_listlen == 0 || (w:netrw_explore_listlen == 1 && w:netrw_explore_list[0] =~ '\*\*\/')
716          call netrw#msg#Notify('WARNING', 'no files matched')
717          if !has('nvim') && has("clipboard") && g:netrw_clipboard
718            if @* != keepregstar | sil! let @* = keepregstar | endif
719            if @+ != keepregplus | sil! let @+ = keepregplus | endif
720          endif
721          sil! let @/ = keepregslash
722          return
723        endif
724      endif  " if indx ... endif
725
726      " NetrwStatusLine support - for exploring support
727      let w:netrw_explore_indx= indx
728
729      " wrap the indx around, but issue a note
730      if indx >= w:netrw_explore_listlen || indx < 0
731        let indx                = (indx < 0)? ( w:netrw_explore_listlen - 1 ) : 0
732        let w:netrw_explore_indx= indx
733        call netrw#msg#Notify('NOTE', 'no more files match Explore pattern')
734      endif
735
736      exe "let dirfile= w:netrw_explore_list[".indx."]"
737      let newdir= substitute(dirfile,'/[^/]*$','','e')
738
739      call netrw#LocalBrowseCheck(newdir)
740      if !exists("w:netrw_liststyle")
741        let w:netrw_liststyle= g:netrw_liststyle
742      endif
743      if w:netrw_liststyle == s:THINLIST || w:netrw_liststyle == s:LONGLIST
744        keepalt NetrwKeepj call search('^'.substitute(dirfile,"^.*/","","").'\>',"W")
745      else
746        keepalt NetrwKeepj call search('\<'.substitute(dirfile,"^.*/","","").'\>',"w")
747      endif
748      let w:netrw_explore_mtchcnt = indx + 1
749      let w:netrw_explore_bufnr   = bufnr("%")
750      let w:netrw_explore_line    = line(".")
751      keepalt NetrwKeepj call s:SetupNetrwStatusLine('%f %h%m%r%=%9*%{NetrwStatusLine()}')
752
753    else
754      call netrw#msg#Notify('WARNING', 'your vim needs the +path_extra feature for Exploring with **!')
755      if !has('nvim') && has("clipboard") && g:netrw_clipboard
756        if @* != keepregstar | sil! let @* = keepregstar | endif
757        if @+ != keepregplus | sil! let @+ = keepregplus | endif
758      endif
759      sil! let @/ = keepregslash
760      return
761    endif
762
763  else
764    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && dirname =~ '/'
765      sil! unlet w:netrw_treedict
766      sil! unlet w:netrw_treetop
767    endif
768    let newdir= dirname
769    if !exists("b:netrw_curdir")
770      NetrwKeepj call netrw#LocalBrowseCheck(getcwd())
771    else
772      NetrwKeepj call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,newdir,0))
773    endif
774  endif
775
776  " visual display of **/ **// */ Exploration files
777  if exists("w:netrw_explore_indx") && exists("b:netrw_curdir")
778    if !exists("s:explore_prvdir") || s:explore_prvdir != b:netrw_curdir
779      " only update match list when current directory isn't the same as before
780      let s:explore_prvdir = b:netrw_curdir
781      let s:explore_match  = ""
782      let dirlen           = strlen(b:netrw_curdir)
783      if b:netrw_curdir !~ '/$'
784        let dirlen= dirlen + 1
785      endif
786      let prvfname= ""
787      for fname in w:netrw_explore_list
788        if fname =~ '^'.b:netrw_curdir
789          if s:explore_match == ""
790            let s:explore_match= '\<'.escape(strpart(fname,dirlen),g:netrw_markfileesc).'\>'
791          else
792            let s:explore_match= s:explore_match.'\|\<'.escape(strpart(fname,dirlen),g:netrw_markfileesc).'\>'
793          endif
794        elseif fname !~ '^/' && fname != prvfname
795          if s:explore_match == ""
796            let s:explore_match= '\<'.escape(fname,g:netrw_markfileesc).'\>'
797          else
798            let s:explore_match= s:explore_match.'\|\<'.escape(fname,g:netrw_markfileesc).'\>'
799          endif
800        endif
801        let prvfname= fname
802      endfor
803      if has("syntax") && exists("g:syntax_on") && g:syntax_on
804        exe "2match netrwMarkFile /".s:explore_match."/"
805      endif
806    endif
807    echo "<s-up>==Pexplore  <s-down>==Nexplore"
808  else
809    2match none
810    if exists("s:explore_match")  | unlet s:explore_match  | endif
811    if exists("s:explore_prvdir") | unlet s:explore_prvdir | endif
812  endif
813
814  " since Explore may be used to initialize netrw's browser,
815  " there's no danger of a late FocusGained event on initialization.
816  " Consequently, set s:netrw_events to 2.
817  let s:netrw_events= 2
818  if !has('nvim') && has("clipboard") && g:netrw_clipboard
819    if @* != keepregstar | sil! let @* = keepregstar | endif
820    if @+ != keepregplus | sil! let @+ = keepregplus | endif
821  endif
822  sil! let @/ = keepregslash
823endfunction
824
825" netrw#Lexplore: toggle Explorer window, keeping it on the left of the current tab {{{2
826"   Uses  g:netrw_chgwin  : specifies the window where Lexplore files are to be opened
827"         t:netrw_lexposn : winsaveview() output (used on Lexplore window)
828"         t:netrw_lexbufnr: the buffer number of the Lexplore buffer  (internal to this function)
829"         s:lexplore_win  : window number of Lexplore window (serves to indicate which window is a Lexplore window)
830"         w:lexplore_buf  : buffer number of Lexplore window (serves to indicate which window is a Lexplore window)
831function netrw#Lexplore(count,rightside,...)
832  let curwin= winnr()
833
834  if a:0 > 0 && a:1 != ""
835    " if a netrw window is already on the left-side of the tab
836    " and a directory has been specified, explore with that
837    " directory.
838    let a1 = expand(a:1)
839    exe "1wincmd w"
840    if &ft == "netrw"
841      exe "Explore ".fnameescape(a1)
842      exe curwin."wincmd w"
843      let s:lexplore_win= curwin
844      let w:lexplore_buf= bufnr("%")
845      if exists("t:netrw_lexposn")
846        unlet t:netrw_lexposn
847      endif
848      return
849    endif
850    exe curwin."wincmd w"
851  else
852    let a1= ""
853  endif
854
855  if exists("t:netrw_lexbufnr")
856    " check if t:netrw_lexbufnr refers to a netrw window
857    let lexwinnr = bufwinnr(t:netrw_lexbufnr)
858  else
859    let lexwinnr= 0
860  endif
861
862  if lexwinnr > 0
863    " close down netrw explorer window
864    exe lexwinnr."wincmd w"
865    let g:netrw_winsize = -winwidth(0)
866    let t:netrw_lexposn = winsaveview()
867    close
868    if lexwinnr < curwin
869      let curwin= curwin - 1
870    endif
871    if lexwinnr != curwin
872      exe curwin."wincmd w"
873    endif
874    unlet t:netrw_lexbufnr
875
876  else
877    " open netrw explorer window
878    exe "1wincmd w"
879    let keep_altv    = g:netrw_altv
880    let g:netrw_altv = 0
881    if a:count != 0
882      let netrw_winsize   = g:netrw_winsize
883      let g:netrw_winsize = a:count
884    endif
885    let curfile= expand("%")
886    exe (a:rightside? "botright" : "topleft")." vertical ".((g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize) . " new"
887    if a:0 > 0 && a1 != ""
888      call netrw#Explore(0,0,0,a1)
889      exe "Explore ".fnameescape(a1)
890    elseif curfile =~ '^\a\{3,}://'
891      call netrw#Explore(0,0,0,substitute(curfile,'[^/\\]*$','',''))
892    else
893      call netrw#Explore(0,0,0,".")
894    endif
895    if a:count != 0
896      let g:netrw_winsize = netrw_winsize
897    endif
898    setlocal winfixwidth
899    let g:netrw_altv     = keep_altv
900    let t:netrw_lexbufnr = bufnr("%")
901    " done to prevent build-up of hidden buffers due to quitting and re-invocation of :Lexplore.
902    " Since the intended use of :Lexplore is to have an always-present explorer window, the extra
903    " effort to prevent mis-use of :Lex is warranted.
904    set bh=wipe
905    if exists("t:netrw_lexposn")
906      call winrestview(t:netrw_lexposn)
907      unlet t:netrw_lexposn
908    endif
909  endif
910
911  " set up default window for editing via <cr>
912  if exists("g:netrw_chgwin") && g:netrw_chgwin == -1
913    if a:rightside
914      let g:netrw_chgwin= 1
915    else
916      let g:netrw_chgwin= 2
917    endif
918  endif
919
920endfunction
921
922" netrw#MakeTgt: make a target out of the directory name provided {{{2
923function netrw#MakeTgt(dname)
924  " simplify the target (eg. /abc/def/../ghi -> /abc/ghi)
925  let svpos               = winsaveview()
926  let s:netrwmftgt_islocal= (a:dname !~ '^\a\{3,}://')
927  if s:netrwmftgt_islocal
928    let netrwmftgt= simplify(a:dname)
929  else
930    let netrwmftgt= a:dname
931  endif
932  if exists("s:netrwmftgt") && netrwmftgt == s:netrwmftgt
933    " re-selected target, so just clear it
934    unlet s:netrwmftgt s:netrwmftgt_islocal
935  else
936    let s:netrwmftgt= netrwmftgt
937  endif
938  if g:netrw_fastbrowse <= 1
939    call s:NetrwRefresh((b:netrw_curdir !~ '\a\{3,}://'),b:netrw_curdir)
940  endif
941  call winrestview(svpos)
942endfunction
943
944" netrw#Obtain: {{{2
945"   netrw#Obtain(islocal,fname[,tgtdirectory])
946"     islocal=0  obtain from remote source
947"            =1  obtain from local source
948"     fname  :   a filename or a list of filenames
949"     tgtdir :   optional place where files are to go  (not present, uses getcwd())
950function netrw#Obtain(islocal,fname,...)
951  " NetrwStatusLine support - for obtaining support
952
953  if type(a:fname) == 1
954    let fnamelist= [ a:fname ]
955  elseif type(a:fname) == 3
956    let fnamelist= a:fname
957  else
958    call netrw#msg#Notify('ERROR', 'attempting to use NetrwObtain on something not a filename or a list')
959    return
960  endif
961  if a:0 > 0
962    let tgtdir= a:1
963  else
964    let tgtdir= getcwd()
965  endif
966
967  if exists("b:netrw_islocal") && b:netrw_islocal
968    " obtain a file from local b:netrw_curdir to (local) tgtdir
969    if exists("b:netrw_curdir") && getcwd() != b:netrw_curdir
970      let topath = netrw#fs#ComposePath(tgtdir,"")
971      if has("win32") && !g:netrw_cygwin
972        " transfer files one at time
973        for fname in fnamelist
974          call system(g:netrw_localcopycmd.g:netrw_localcopycmdopt." ".netrw#os#Escape(fname)." ".netrw#os#Escape(topath))
975          if v:shell_error != 0
976            call netrw#msg#Notify('WARNING', printf('consider setting g:netrw_localcopycmd<%s> to something that works', g:netrw_localcopycmd))
977            return
978          endif
979        endfor
980      else
981        " transfer files with one command
982        let filelist= join(map(deepcopy(fnamelist),"netrw#os#Escape(v:val)"))
983        call system(g:netrw_localcopycmd.g:netrw_localcopycmdopt." ".filelist." ".netrw#os#Escape(topath))
984        if v:shell_error != 0
985          call netrw#msg#Notify('WARNING', printf('consider setting g:netrw_localcopycmd<%s> to something that works', g:netrw_localcopycmd))
986          return
987        endif
988      endif
989    elseif !exists("b:netrw_curdir")
990      call netrw#msg#Notify('ERROR', "local browsing directory doesn't exist!")
991    else
992      call netrw#msg#Notify('WARNING', 'local browsing directory and current directory are identical')
993    endif
994
995  else
996    " obtain files from remote b:netrw_curdir to local tgtdir
997    if type(a:fname) == 1
998      call s:SetupNetrwStatusLine('%f %h%m%r%=%9*Obtaining '.a:fname)
999    endif
1000    call s:NetrwMethod(b:netrw_curdir)
1001    if !s:NetrwValidateHostname(g:netrw_machine)
1002        call netrw#msg#Notify('ERROR', 'Rejecting invalid hostname: <%s>', g:netrw_machine)
1003        return
1004    endif
1005
1006    if b:netrw_method == 4
1007      " obtain file using scp
1008      if exists("g:netrw_port") && g:netrw_port != ""
1009        let useport= " ".g:netrw_scpport." ".g:netrw_port
1010      else
1011        let useport= ""
1012      endif
1013      if b:netrw_fname =~ '/'
1014        let path= substitute(b:netrw_fname,'^\(.*/\).\{-}$','\1','')
1015      else
1016        let path= ""
1017      endif
1018      let filelist= join(map(deepcopy(fnamelist),'escape(netrw#os#Escape(g:netrw_machine.":".path.v:val,1)," ")'))
1019      call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_scp_cmd.netrw#os#Escape(useport,1)." ".filelist." ".netrw#os#Escape(tgtdir,1))
1020
1021    elseif b:netrw_method == 2
1022      " obtain file using ftp + .netrc
1023      call s:SaveBufVars()|sil NetrwKeepj new|call s:RestoreBufVars()
1024      let tmpbufnr= bufnr("%")
1025      setl ff=unix
1026      if exists("g:netrw_ftpmode") && g:netrw_ftpmode != ""
1027        NetrwKeepj put =g:netrw_ftpmode
1028      endif
1029
1030      if exists("b:netrw_fname") && b:netrw_fname != ""
1031        call setline(line("$")+1,'cd "'.b:netrw_fname.'"')
1032      endif
1033
1034      if exists("g:netrw_ftpextracmd")
1035        NetrwKeepj put =g:netrw_ftpextracmd
1036      endif
1037      for fname in fnamelist
1038        call setline(line("$")+1,'get "'.fname.'"')
1039      endfor
1040      if exists("g:netrw_port") && g:netrw_port != ""
1041        call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1)." ".netrw#os#Escape(g:netrw_port,1))
1042      else
1043        call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1))
1044      endif
1045      " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
1046      if getline(1) !~ "^$" && getline(1) !~ '^Trying '
1047        let debugkeep= &debug
1048        setl debug=msg
1049        call netrw#msg#Notify('ERROR', getline(1))
1050        let &debug= debugkeep
1051      endif
1052
1053    elseif b:netrw_method == 3
1054      " obtain with ftp + machine, id, passwd, and fname (ie. no .netrc)
1055      call s:SaveBufVars()|sil NetrwKeepj new|call s:RestoreBufVars()
1056      let tmpbufnr= bufnr("%")
1057      setl ff=unix
1058
1059      if exists("g:netrw_port") && g:netrw_port != ""
1060        NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
1061      else
1062        NetrwKeepj put ='open '.g:netrw_machine
1063      endif
1064
1065      if exists("g:netrw_uid") && g:netrw_uid != ""
1066        if exists("g:netrw_ftp") && g:netrw_ftp == 1
1067          NetrwKeepj put =g:netrw_uid
1068          if exists("s:netrw_passwd") && s:netrw_passwd != ""
1069            NetrwKeepj put ='\"'.s:netrw_passwd.'\"'
1070          endif
1071        elseif exists("s:netrw_passwd")
1072          NetrwKeepj put ='user \"'.g:netrw_uid.'\" \"'.s:netrw_passwd.'\"'
1073        endif
1074      endif
1075
1076      if exists("g:netrw_ftpmode") && g:netrw_ftpmode != ""
1077        NetrwKeepj put =g:netrw_ftpmode
1078      endif
1079
1080      if exists("b:netrw_fname") && b:netrw_fname != ""
1081        NetrwKeepj call setline(line("$")+1,'cd "'.b:netrw_fname.'"')
1082      endif
1083
1084      if exists("g:netrw_ftpextracmd")
1085        NetrwKeepj put =g:netrw_ftpextracmd
1086      endif
1087
1088      if exists("g:netrw_ftpextracmd")
1089        NetrwKeepj put =g:netrw_ftpextracmd
1090      endif
1091      for fname in fnamelist
1092        NetrwKeepj call setline(line("$")+1,'get "'.fname.'"')
1093      endfor
1094
1095      " perform ftp:
1096      " -i       : turns off interactive prompting from ftp
1097      " -n  unix : DON'T use <.netrc>, even though it exists
1098      " -n  win32: quit being obnoxious about password
1099      "  Note: using "_dd to delete to the black hole register; avoids messing up @@
1100      NetrwKeepj norm! 1G"_dd
1101      call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." ".g:netrw_ftp_options)
1102      " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
1103      if getline(1) !~ "^$"
1104          call netrw#msg#Notify('ERROR', getline(1))
1105      endif
1106
1107    elseif b:netrw_method == 9
1108      " obtain file using sftp
1109      if a:fname =~ '/'
1110        let localfile= substitute(a:fname,'^.*/','','')
1111      else
1112        let localfile= a:fname
1113      endif
1114      call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_sftp_cmd." ".netrw#os#Escape(g:netrw_machine.":".b:netrw_fname,1).netrw#os#Escape(localfile)." ".netrw#os#Escape(tgtdir))
1115
1116    elseif !exists("b:netrw_method") || b:netrw_method < 0
1117      " probably a badly formed url; protocol not recognized
1118      return
1119
1120    else
1121      " protocol recognized but not supported for Obtain (yet?)
1122        call netrw#msg#Notify('ERROR', 'current protocol not supported for obtaining file')
1123      return
1124    endif
1125
1126    " restore status line
1127    if type(a:fname) == 1 && exists("s:netrw_users_stl")
1128      NetrwKeepj call s:SetupNetrwStatusLine(s:netrw_users_stl)
1129    endif
1130
1131  endif
1132
1133  " cleanup
1134  if exists("tmpbufnr")
1135    if bufnr("%") != tmpbufnr
1136      exe tmpbufnr."bw!"
1137    else
1138      q!
1139    endif
1140  endif
1141
1142endfunction
1143
1144" netrw#Nread: save position, call netrw#NetRead(), and restore position {{{2
1145function netrw#Nread(mode,fname)
1146  let svpos= winsaveview()
1147  call netrw#NetRead(a:mode,a:fname)
1148  call winrestview(svpos)
1149
1150  if exists("w:netrw_liststyle") && w:netrw_liststyle != s:TREELIST
1151    if exists("w:netrw_bannercnt")
1152      " start with cursor just after the banner
1153      exe w:netrw_bannercnt
1154    endif
1155  endif
1156endfunction
1157
1158" s:NetrwOptionsSave: save options prior to setting to "netrw-buffer-standard" form {{{2
1159"             Options get restored by s:NetrwOptionsRestore()
1160"
1161"             Option handling:
1162"              * save user's options                                     (s:NetrwOptionsSave)
1163"              * set netrw-safe options                                  (s:NetrwOptionsSafe)
1164"                - change an option only when user option != safe option (s:netrwSetSafeSetting)
1165"              * restore user's options                                  (s:netrwOPtionsRestore)
1166"                - restore a user option when != safe option             (s:NetrwRestoreSetting)
1167"             vt: (variable type) normally its either "w:" or "s:"
1168function s:NetrwOptionsSave(vt)
1169
1170  if !exists("{a:vt}netrw_optionsave")
1171    let {a:vt}netrw_optionsave= 1
1172  else
1173    return
1174  endif
1175
1176  " Save current settings and current directory
1177  let s:yykeep          = @@
1178  if exists("&l:acd")|let {a:vt}netrw_acdkeep  = &l:acd|endif
1179  let {a:vt}netrw_aikeep    = &l:ai
1180  let {a:vt}netrw_awkeep    = &l:aw
1181  let {a:vt}netrw_bhkeep    = &l:bh
1182  let {a:vt}netrw_blkeep    = &l:bl
1183  let {a:vt}netrw_btkeep    = &l:bt
1184  let {a:vt}netrw_bombkeep  = &l:bomb
1185  let {a:vt}netrw_cedit     = &cedit
1186  let {a:vt}netrw_cikeep    = &l:ci
1187  let {a:vt}netrw_cinkeep   = &l:cin
1188  let {a:vt}netrw_cinokeep  = &l:cino
1189  let {a:vt}netrw_comkeep   = &l:com
1190  let {a:vt}netrw_cpokeep   = &l:cpo
1191  let {a:vt}netrw_cuckeep   = &l:cuc
1192  let {a:vt}netrw_culkeep   = &l:cul
1193  let {a:vt}netrw_diffkeep  = &l:diff
1194  let {a:vt}netrw_fenkeep   = &l:fen
1195  if !exists("g:netrw_ffkeep") || g:netrw_ffkeep
1196    let {a:vt}netrw_ffkeep    = &l:ff
1197  endif
1198  let {a:vt}netrw_fokeep    = &l:fo           " formatoptions
1199  let {a:vt}netrw_gdkeep    = &l:gd           " gdefault
1200  let {a:vt}netrw_gokeep    = &go             " guioptions
1201  let {a:vt}netrw_hidkeep   = &l:hidden
1202  let {a:vt}netrw_imkeep    = &l:im
1203  let {a:vt}netrw_iskkeep   = &l:isk
1204  let {a:vt}netrw_lines     = &lines
1205  let {a:vt}netrw_lskeep    = &l:ls
1206  let {a:vt}netrw_makeep    = &l:ma
1207  let {a:vt}netrw_magickeep = &l:magic
1208  let {a:vt}netrw_modkeep   = &l:mod
1209  let {a:vt}netrw_nukeep    = &l:nu
1210  let {a:vt}netrw_rnukeep   = &l:rnu
1211  let {a:vt}netrw_repkeep   = &l:report
1212  let {a:vt}netrw_rokeep    = &l:ro
1213  let {a:vt}netrw_selkeep   = &l:sel
1214  let {a:vt}netrw_spellkeep = &l:spell
1215  if !g:netrw_use_noswf
1216    let {a:vt}netrw_swfkeep  = &l:swf
1217  endif
1218  let {a:vt}netrw_tskeep    = &l:ts
1219  let {a:vt}netrw_twkeep    = &l:tw           " textwidth
1220  let {a:vt}netrw_wigkeep   = &l:wig          " wildignore
1221  let {a:vt}netrw_wrapkeep  = &l:wrap
1222  let {a:vt}netrw_writekeep = &l:write
1223
1224  " save a few selected netrw-related variables
1225  if g:netrw_keepdir
1226    let {a:vt}netrw_dirkeep  = getcwd()
1227  endif
1228  if !has('nvim') && has("clipboard") && g:netrw_clipboard
1229    sil! let {a:vt}netrw_starkeep = @*
1230    sil! let {a:vt}netrw_pluskeep = @+
1231  endif
1232  sil! let {a:vt}netrw_slashkeep= @/
1233
1234endfunction
1235
1236" s:NetrwOptionsSafe: sets options to help netrw do its job {{{2
1237"                     Use  s:NetrwSaveOptions() to save user settings
1238"                     Use  s:NetrwOptionsRestore() to restore user settings
1239function s:NetrwOptionsSafe(islocal)
1240  if exists("+acd") | call s:NetrwSetSafeSetting("&l:acd",0)|endif
1241  call s:NetrwSetSafeSetting("&l:ai",0)
1242  call s:NetrwSetSafeSetting("&l:aw",0)
1243  call s:NetrwSetSafeSetting("&l:bl",0)
1244  call s:NetrwSetSafeSetting("&l:bomb",0)
1245  if a:islocal
1246    call s:NetrwSetSafeSetting("&l:bt","nofile")
1247  else
1248    call s:NetrwSetSafeSetting("&l:bt","acwrite")
1249  endif
1250  call s:NetrwSetSafeSetting("&l:ci",0)
1251  call s:NetrwSetSafeSetting("&l:cin",0)
1252  if g:netrw_fastbrowse > a:islocal
1253    call s:NetrwSetSafeSetting("&l:bh","hide")
1254  else
1255    call s:NetrwSetSafeSetting("&l:bh","delete")
1256  endif
1257  call s:NetrwSetSafeSetting("&l:cino","")
1258  call s:NetrwSetSafeSetting("&l:com","")
1259  if &cpo =~ 'a' | call s:NetrwSetSafeSetting("&cpo",substitute(&cpo,'a','','g')) | endif
1260  if &cpo =~ 'A' | call s:NetrwSetSafeSetting("&cpo",substitute(&cpo,'A','','g')) | endif
1261  setl fo=nroql2
1262  if &go =~ 'a' | set go-=a | endif
1263  if &go =~ 'A' | set go-=A | endif
1264  if &go =~ 'P' | set go-=P | endif
1265  call s:NetrwSetSafeSetting("&l:hid",0)
1266  call s:NetrwSetSafeSetting("&l:im",0)
1267  setl isk+=@ isk+=* isk+=/
1268  call s:NetrwSetSafeSetting("&l:magic",1)
1269  if g:netrw_use_noswf
1270    call s:NetrwSetSafeSetting("swf",0)
1271  endif
1272  call s:NetrwSetSafeSetting("&l:report",10000)
1273  call s:NetrwSetSafeSetting("&l:sel","inclusive")
1274  call s:NetrwSetSafeSetting("&l:spell",0)
1275  call s:NetrwSetSafeSetting("&l:tw",0)
1276  call s:NetrwSetSafeSetting("&l:wig","")
1277  setl cedit&
1278
1279  " set up cuc and cul based on g:netrw_cursor and listing style
1280  " COMBAK -- cuc cul related
1281  call s:NetrwCursor(0)
1282
1283  " allow the user to override safe options
1284  if &ft == "netrw"
1285    keepalt NetrwKeepj doau FileType netrw
1286  endif
1287
1288endfunction
1289
1290" s:NetrwOptionsRestore: restore options (based on prior s:NetrwOptionsSave) {{{2
1291function s:NetrwOptionsRestore(vt)
1292  if !exists("{a:vt}netrw_optionsave")
1293    " filereadable() returns zero for remote files (e.g. scp://user@localhost//etc/fstab)
1294    " Note: @ may not be in 'isfname', so '^\w\+://\f\+/' may not match
1295    if filereadable(expand("%")) || expand("%") =~# '^\w\+://\f\+'
1296      filetype detect
1297    else
1298      setl ft=netrw
1299    endif
1300    return
1301  endif
1302  unlet {a:vt}netrw_optionsave
1303
1304  if exists("+acd")
1305    if exists("{a:vt}netrw_acdkeep")
1306      let curdir = getcwd()
1307      let &l:acd = {a:vt}netrw_acdkeep
1308      unlet {a:vt}netrw_acdkeep
1309      if &l:acd
1310        call s:NetrwLcd(curdir)
1311      endif
1312    endif
1313  endif
1314  call s:NetrwRestoreSetting(a:vt."netrw_aikeep","&l:ai")
1315  call s:NetrwRestoreSetting(a:vt."netrw_awkeep","&l:aw")
1316  call s:NetrwRestoreSetting(a:vt."netrw_blkeep","&l:bl")
1317  call s:NetrwRestoreSetting(a:vt."netrw_btkeep","&l:bt")
1318  call s:NetrwRestoreSetting(a:vt."netrw_bombkeep","&l:bomb")
1319  call s:NetrwRestoreSetting(a:vt."netrw_cedit","&cedit")
1320  call s:NetrwRestoreSetting(a:vt."netrw_cikeep","&l:ci")
1321  call s:NetrwRestoreSetting(a:vt."netrw_cinkeep","&l:cin")
1322  call s:NetrwRestoreSetting(a:vt."netrw_cinokeep","&l:cino")
1323  call s:NetrwRestoreSetting(a:vt."netrw_comkeep","&l:com")
1324  call s:NetrwRestoreSetting(a:vt."netrw_cpokeep","&l:cpo")
1325  call s:NetrwRestoreSetting(a:vt."netrw_diffkeep","&l:diff")
1326  call s:NetrwRestoreSetting(a:vt."netrw_fenkeep","&l:fen")
1327  if exists("g:netrw_ffkeep") && g:netrw_ffkeep
1328    call s:NetrwRestoreSetting(a:vt."netrw_ffkeep")","&l:ff")
1329  endif
1330  call s:NetrwRestoreSetting(a:vt."netrw_fokeep"   ,"&l:fo")
1331  call s:NetrwRestoreSetting(a:vt."netrw_gdkeep"   ,"&l:gd")
1332  call s:NetrwRestoreSetting(a:vt."netrw_gokeep"   ,"&go")
1333  call s:NetrwRestoreSetting(a:vt."netrw_hidkeep"  ,"&l:hidden")
1334  call s:NetrwRestoreSetting(a:vt."netrw_imkeep"   ,"&l:im")
1335  call s:NetrwRestoreSetting(a:vt."netrw_iskkeep"  ,"&l:isk")
1336  call s:NetrwRestoreSetting(a:vt."netrw_lines"    ,"&lines")
1337  call s:NetrwRestoreSetting(a:vt."netrw_lskeep"   ,"&l:ls")
1338  call s:NetrwRestoreSetting(a:vt."netrw_makeep"   ,"&l:ma")
1339  call s:NetrwRestoreSetting(a:vt."netrw_magickeep","&l:magic")
1340  call s:NetrwRestoreSetting(a:vt."netrw_modkeep"  ,"&l:mod")
1341  call s:NetrwRestoreSetting(a:vt."netrw_nukeep"   ,"&l:nu")
1342  call s:NetrwRestoreSetting(a:vt."netrw_rnukeep"  ,"&l:rnu")
1343  call s:NetrwRestoreSetting(a:vt."netrw_repkeep"  ,"&l:report")
1344  call s:NetrwRestoreSetting(a:vt."netrw_rokeep"   ,"&l:ro")
1345  call s:NetrwRestoreSetting(a:vt."netrw_selkeep"  ,"&l:sel")
1346  call s:NetrwRestoreSetting(a:vt."netrw_spellkeep","&l:spell")
1347  call s:NetrwRestoreSetting(a:vt."netrw_twkeep"   ,"&l:tw")
1348  call s:NetrwRestoreSetting(a:vt."netrw_wigkeep"  ,"&l:wig")
1349  call s:NetrwRestoreSetting(a:vt."netrw_wrapkeep" ,"&l:wrap")
1350  call s:NetrwRestoreSetting(a:vt."netrw_writekeep","&l:write")
1351  call s:NetrwRestoreSetting("s:yykeep","@@")
1352  " former problem: start with liststyle=0; press <i> : result, following line resets l:ts.
1353  " Fixed; in s:PerformListing, when w:netrw_liststyle is s:LONGLIST, will use a printf to pad filename with spaces
1354  "        rather than by appending a tab which previously was using "&ts" to set the desired spacing.  (Sep 28, 2018)
1355  call s:NetrwRestoreSetting(a:vt."netrw_tskeep","&l:ts")
1356
1357  if exists("{a:vt}netrw_swfkeep")
1358    if &directory == ""
1359      " user hasn't specified a swapfile directory;
1360      " netrw will temporarily set the swapfile directory
1361      " to the current directory as returned by getcwd().
1362      let &l:directory= getcwd()
1363      sil! let &l:swf = {a:vt}netrw_swfkeep
1364      setl directory=
1365      unlet {a:vt}netrw_swfkeep
1366    elseif &l:swf != {a:vt}netrw_swfkeep
1367      if !g:netrw_use_noswf
1368        " following line causes a Press ENTER in windows -- can't seem to work around it!!!
1369        sil! let &l:swf= {a:vt}netrw_swfkeep
1370      endif
1371      unlet {a:vt}netrw_swfkeep
1372    endif
1373  endif
1374  if exists("{a:vt}netrw_dirkeep") && isdirectory(s:NetrwFile({a:vt}netrw_dirkeep)) && g:netrw_keepdir
1375    let dirkeep = substitute({a:vt}netrw_dirkeep,'\\','/','g')
1376    if exists("{a:vt}netrw_dirkeep")
1377      call s:NetrwLcd(dirkeep)
1378      unlet {a:vt}netrw_dirkeep
1379    endif
1380  endif
1381  if !has('nvim') && has("clipboard") && g:netrw_clipboard
1382    call s:NetrwRestoreSetting(a:vt."netrw_starkeep","@*")
1383    call s:NetrwRestoreSetting(a:vt."netrw_pluskeep","@+")
1384  endif
1385  call s:NetrwRestoreSetting(a:vt."netrw_slashkeep","@/")
1386
1387  " Moved the filetype detect here from NetrwGetFile() because remote files
1388  " were having their filetype detect-generated settings overwritten by
1389  " NetrwOptionRestore.
1390  if &ft != "netrw"
1391    filetype detect
1392  endif
1393endfunction
1394
1395" s:NetrwSetSafeSetting: sets an option to a safe setting {{{2
1396"                        but only when the options' value and the safe setting differ
1397"                        Doing this means that netrw will not come up as having changed a
1398"                        setting last when it really didn't actually change it.
1399"
1400"                        Called from s:NetrwOptionsSafe
1401"                          ex. call s:NetrwSetSafeSetting("&l:sel","inclusive")
1402function s:NetrwSetSafeSetting(setting,safesetting)
1403
1404  if a:setting =~ '^&'
1405    exe "let settingval= ".a:setting
1406
1407    if settingval != a:safesetting
1408      if type(a:safesetting) == 0
1409        exe "let ".a:setting."=".a:safesetting
1410      elseif type(a:safesetting) == 1
1411        exe "let ".a:setting."= '".a:safesetting."'"
1412      else
1413        call netrw#msg#Notify('ERROR', printf("(s:NetrwRestoreSetting) doesn't know how to restore %s with a safesetting of type#%s", a:setting, type(a:safesetting)))
1414      endif
1415    endif
1416  endif
1417
1418endfunction
1419
1420" s:NetrwRestoreSetting: restores specified setting using associated keepvar, {{{2
1421"                        but only if the setting value differs from the associated keepvar.
1422"                        Doing this means that netrw will not come up as having changed a
1423"                        setting last when it really didn't actually change it.
1424"
1425"                        Used by s:NetrwOptionsRestore() to restore each netrw-sensitive setting
1426"                        keepvars are set up by s:NetrwOptionsSave
1427function s:NetrwRestoreSetting(keepvar,setting)
1428
1429  " typically called from s:NetrwOptionsRestore
1430  "   call s:NetrwRestoreSettings(keep-option-variable-name,'associated-option')
1431  "   ex. call s:NetrwRestoreSetting(a:vt."netrw_selkeep","&l:sel")
1432  "  Restores option (but only if different) from a:keepvar
1433  if exists(a:keepvar)
1434    exe "let keepvarval= ".a:keepvar
1435    exe "let setting= ".a:setting
1436
1437
1438    if setting != keepvarval
1439      if type(a:setting) == 0
1440        exe "let ".a:setting."= ".keepvarval
1441      elseif type(a:setting) == 1
1442        exe "let ".a:setting."= '".substitute(keepvarval,"'","''","g")."'"
1443      else
1444        call netrw#msg#Notify('ERROR', printf("(s:NetrwRestoreSetting) doesn't know how to restore %s with a setting of type#%s", a:keepvar, type(a:setting)))
1445      endif
1446    endif
1447
1448    exe "unlet ".a:keepvar
1449  endif
1450
1451endfunction
1452
1453" NetrwStatusLine: {{{2
1454
1455function NetrwStatusLine()
1456    if !exists("w:netrw_explore_bufnr") || w:netrw_explore_bufnr != bufnr("%") || !exists("w:netrw_explore_line") || w:netrw_explore_line != line(".") || !exists("w:netrw_explore_list")
1457        let &stl= s:netrw_explore_stl
1458        unlet! w:netrw_explore_bufnr w:netrw_explore_line
1459        return ""
1460    else
1461        return "Match ".w:netrw_explore_mtchcnt." of ".w:netrw_explore_listlen
1462    endif
1463endfunction
1464
1465"  Netrw Transfer Functions: {{{1
1466
1467" netrw#NetRead: responsible for reading a file over the net {{{2
1468"   mode: =0 read remote file and insert before current line
1469"         =1 read remote file and insert after current line
1470"         =2 replace with remote file
1471"         =3 obtain file, but leave in temporary format
1472function netrw#NetRead(mode,...)
1473
1474    " NetRead: save options {{{3
1475    call s:NetrwOptionsSave("w:")
1476    call s:NetrwOptionsSafe(0)
1477    call s:RestoreCursorline()
1478    " NetrwSafeOptions sets a buffer up for a netrw listing, which includes buflisting off.
1479    " However, this setting is not wanted for a remote editing session.  The buffer should be "nofile", still.
1480    setl bl
1481
1482    " NetRead: interpret mode into a readcmd {{{3
1483    if     a:mode == 0 " read remote file before current line
1484        let readcmd = "0r"
1485    elseif a:mode == 1 " read file after current line
1486        let readcmd = "r"
1487    elseif a:mode == 2 " replace with remote file
1488        let readcmd = "%r"
1489    elseif a:mode == 3 " skip read of file (leave as temporary)
1490        let readcmd = "t"
1491    else
1492        exe a:mode
1493        let readcmd = "r"
1494    endif
1495    let ichoice = (a:0 == 0)? 0 : 1
1496
1497    " NetRead: get temporary filename {{{3
1498    let tmpfile= s:GetTempfile("")
1499    if tmpfile == ""
1500        return
1501    endif
1502
1503    while ichoice <= a:0
1504
1505        " attempt to repeat with previous host-file-etc
1506        if exists("b:netrw_lastfile") && a:0 == 0
1507            let choice = b:netrw_lastfile
1508            let ichoice= ichoice + 1
1509
1510        else
1511            exe "let choice= a:" . ichoice
1512
1513            if match(choice,"?") == 0
1514                " give help
1515                echomsg 'NetRead Usage:'
1516                echomsg ':Nread machine:path                         uses rcp'
1517                echomsg ':Nread "machine path"                       uses ftp   with <.netrc>'
1518                echomsg ':Nread "machine id password path"           uses ftp'
1519                echomsg ':Nread dav://machine[:port]/path            uses cadaver'
1520                echomsg ':Nread fetch://machine/path                 uses fetch'
1521                echomsg ':Nread ftp://[user@]machine[:port]/path     uses ftp   autodetects <.netrc>'
1522                echomsg ':Nread http://[user@]machine/path           uses http  wget'
1523                echomsg ':Nread file:///path                         uses elinks'
1524                echomsg ':Nread https://[user@]machine/path          uses http  wget'
1525                echomsg ':Nread rcp://[user@]machine/path            uses rcp'
1526                echomsg ':Nread rsync://machine[:port]/path          uses rsync'
1527                echomsg ':Nread scp://[user@]machine[[:#]port]/path  uses scp'
1528                echomsg ':Nread sftp://[user@]machine[[:#]port]/path uses sftp'
1529                sleep 4
1530                break
1531
1532            elseif match(choice,'^"') != -1
1533                " Reconstruct Choice if choice starts with '"'
1534                if match(choice,'"$') != -1
1535                    " case "..."
1536                    let choice= strpart(choice,1,strlen(choice)-2)
1537                else
1538                    "  case "... ... ..."
1539                    let choice      = strpart(choice,1,strlen(choice)-1)
1540                    let wholechoice = ""
1541
1542                    while match(choice,'"$') == -1
1543                        let wholechoice = wholechoice . " " . choice
1544                        let ichoice     = ichoice + 1
1545                        if ichoice > a:0
1546                            call netrw#msg#Notify('ERROR', printf('Unbalanced string in filename "%s"', wholechoice))
1547                            return
1548                        endif
1549                        let choice= a:{ichoice}
1550                    endwhile
1551                    let choice= strpart(wholechoice,1,strlen(wholechoice)-1) . " " . strpart(choice,0,strlen(choice)-1)
1552                endif
1553            endif
1554        endif
1555
1556        let ichoice= ichoice + 1
1557
1558        " NetRead: Determine method of read (ftp, rcp, etc) {{{3
1559        call s:NetrwMethod(choice)
1560        if !exists("b:netrw_method") || b:netrw_method < 0
1561            return
1562        endif
1563        if !s:NetrwValidateHostname(g:netrw_machine)
1564            call netrw#msg#Notify('ERROR', printf('Rejecting invalid hostname: <%s>', g:netrw_machine))
1565            return
1566        endif
1567        let tmpfile= s:GetTempfile(b:netrw_fname) " apply correct suffix
1568
1569        " Check whether or not NetrwBrowse() should be handling this request
1570        if choice =~ "^.*[\/]$" && b:netrw_method != 5 && choice !~ '^https\=://'
1571            NetrwKeepj call s:NetrwBrowse(0,choice)
1572            return
1573        endif
1574
1575        " ============
1576        " NetRead: Perform Protocol-Based Read {{{3
1577        " ===========================
1578        if exists("g:netrw_silent") && g:netrw_silent == 0 && &ch >= 1
1579            echo "(netrw) Processing your read request..."
1580        endif
1581
1582        ".........................................
1583        " NetRead: (rcp)  NetRead Method #1 {{{3
1584        if  b:netrw_method == 1 " read with rcp
1585            " ER: nothing done with g:netrw_uid yet?
1586            " ER: on Win2K" rcp machine[.user]:file tmpfile
1587            " ER: when machine contains '.' adding .user is required (use $USERNAME)
1588            " ER: the tmpfile is full path: rcp sees C:\... as host C
1589            if s:netrw_has_nt_rcp == 1
1590                if exists("g:netrw_uid") && ( g:netrw_uid != "" )
1591                    let uid_machine = g:netrw_machine .'.'. g:netrw_uid
1592                else
1593                    " Any way needed it machine contains a '.'
1594                    let uid_machine = g:netrw_machine .'.'. $USERNAME
1595                endif
1596            else
1597                if exists("g:netrw_uid") && ( g:netrw_uid != "" )
1598                    let uid_machine = g:netrw_uid .'@'. g:netrw_machine
1599                else
1600                    let uid_machine = g:netrw_machine
1601                endif
1602            endif
1603            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_rcp_cmd." ".s:netrw_rcpmode." ".netrw#os#Escape(uid_machine.":".b:netrw_fname,1)." ".netrw#os#Escape(tmpfile,1))
1604            let result           = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1605            let b:netrw_lastfile = choice
1606
1607            ".........................................
1608        " NetRead: (ftp + <.netrc>)  NetRead Method #2 {{{3
1609        elseif b:netrw_method  == 2          " read with ftp + <.netrc>
1610            let netrw_fname= b:netrw_fname
1611            NetrwKeepj call s:SaveBufVars()|new|NetrwKeepj call s:RestoreBufVars()
1612            let filtbuf= bufnr("%")
1613            setl ff=unix
1614            NetrwKeepj put =g:netrw_ftpmode
1615            if exists("g:netrw_ftpextracmd")
1616                NetrwKeepj put =g:netrw_ftpextracmd
1617            endif
1618            call setline(line("$")+1,'get "'.netrw_fname.'" '.tmpfile)
1619            if exists("g:netrw_port") && g:netrw_port != ""
1620                call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1)." ".netrw#os#Escape(g:netrw_port,1))
1621            else
1622                call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1))
1623            endif
1624            " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
1625            if getline(1) !~ "^$" && getline(1) !~ '^Trying '
1626                let debugkeep = &debug
1627                setl debug=msg
1628                call netrw#msg#Notify('ERROR', getline(1))
1629                let &debug    = debugkeep
1630            endif
1631            call s:SaveBufVars()
1632            keepj bd!
1633            if bufname("%") == "" && getline("$") == "" && line('$') == 1
1634                " needed when one sources a file in a nolbl setting window via ftp
1635                q!
1636            endif
1637            call s:RestoreBufVars()
1638            let result           = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1639            let b:netrw_lastfile = choice
1640
1641            ".........................................
1642        " NetRead: (ftp + machine,id,passwd,filename)  NetRead Method #3 {{{3
1643        elseif b:netrw_method == 3           " read with ftp + machine, id, passwd, and fname
1644            " Construct execution string (four lines) which will be passed through filter
1645            let netrw_fname= escape(b:netrw_fname,g:netrw_fname_escape)
1646            NetrwKeepj call s:SaveBufVars()|new|NetrwKeepj call s:RestoreBufVars()
1647            let filtbuf= bufnr("%")
1648            setl ff=unix
1649            if exists("g:netrw_port") && g:netrw_port != ""
1650                NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
1651            else
1652                NetrwKeepj put ='open '.g:netrw_machine
1653            endif
1654
1655            if exists("g:netrw_uid") && g:netrw_uid != ""
1656                if exists("g:netrw_ftp") && g:netrw_ftp == 1
1657                    NetrwKeepj put =g:netrw_uid
1658                    if exists("s:netrw_passwd")
1659                        NetrwKeepj put ='\"'.s:netrw_passwd.'\"'
1660                    endif
1661                elseif exists("s:netrw_passwd")
1662                    NetrwKeepj put ='user \"'.g:netrw_uid.'\" \"'.s:netrw_passwd.'\"'
1663                endif
1664            endif
1665
1666            if exists("g:netrw_ftpmode") && g:netrw_ftpmode != ""
1667                NetrwKeepj put =g:netrw_ftpmode
1668            endif
1669            if exists("g:netrw_ftpextracmd")
1670                NetrwKeepj put =g:netrw_ftpextracmd
1671            endif
1672            NetrwKeepj put ='get \"'.netrw_fname.'\" '.tmpfile
1673
1674            " perform ftp:
1675            " -i       : turns off interactive prompting from ftp
1676            " -n  unix : DON'T use <.netrc>, even though it exists
1677            " -n  win32: quit being obnoxious about password
1678            NetrwKeepj norm! 1G"_dd
1679            call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." ".g:netrw_ftp_options)
1680            " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
1681            if getline(1) !~ "^$"
1682                call netrw#msg#Notify('ERROR', getline(1))
1683            endif
1684            call s:SaveBufVars()|keepj bd!|call s:RestoreBufVars()
1685            let result           = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1686            let b:netrw_lastfile = choice
1687
1688            ".........................................
1689        " NetRead: (scp) NetRead Method #4 {{{3
1690        elseif     b:netrw_method  == 4      " read with scp
1691            if exists("g:netrw_port") && g:netrw_port != ""
1692                let useport= " ".g:netrw_scpport." ".g:netrw_port
1693            else
1694                let useport= ""
1695            endif
1696            " Using UNC notation in windows to get a unix like path.
1697            " This is workaround to avoid mis-handle windows local-path:
1698            if g:netrw_scp_cmd =~ '^scp' && has("win32")
1699                let tmpfile_get = substitute(tr(tmpfile, '\', '/'), '^\(\a\):[/\\]\(.*\)$', '//' .. $COMPUTERNAME .. '/\1$/\2', '')
1700            else
1701                let tmpfile_get = tmpfile
1702            endif
1703            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_scp_cmd.useport." ".escape(netrw#os#Escape(g:netrw_machine.":".b:netrw_fname,1),' ')." ".netrw#os#Escape(tmpfile_get,1))
1704            let result           = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1705            let b:netrw_lastfile = choice
1706
1707            ".........................................
1708        " NetRead: (http) NetRead Method #5 (wget) {{{3
1709        elseif     b:netrw_method  == 5
1710            if g:netrw_http_cmd == ""
1711                call netrw#msg#Notify('ERROR', 'neither the wget nor the fetch command is available')
1712                return
1713            endif
1714
1715            if match(b:netrw_fname,"#") == -1 || exists("g:netrw_http_xcmd")
1716                " using g:netrw_http_cmd (usually elinks, links, curl, wget, or fetch)
1717                if exists("g:netrw_http_xcmd")
1718                    call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_http_cmd." ".netrw#os#Escape(b:netrw_http."://".g:netrw_machine.b:netrw_fname,1)." ".g:netrw_http_xcmd." ".netrw#os#Escape(tmpfile,1))
1719                else
1720                    call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_http_cmd." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(b:netrw_http."://".g:netrw_machine.b:netrw_fname,1))
1721                endif
1722                let result = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1723
1724            else
1725                " wget/curl/fetch plus a jump to an in-page marker (ie. http://abc/def.html#aMarker)
1726                let netrw_html= substitute(b:netrw_fname,"#.*$","","")
1727                let netrw_tag = substitute(b:netrw_fname,"^.*#","","")
1728                call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_http_cmd." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(b:netrw_http."://".g:netrw_machine.netrw_html,1))
1729                let result = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1730                exe 'NetrwKeepj norm! 1G/<\s*a\s*name=\s*"'.netrw_tag.'"/'."\<CR>"
1731            endif
1732            let b:netrw_lastfile = choice
1733            setl ro nomod
1734
1735            ".........................................
1736        " NetRead: (dav) NetRead Method #6 {{{3
1737        elseif     b:netrw_method  == 6
1738
1739            if !executable(g:netrw_dav_cmd)
1740                call netrw#msg#Notify('ERROR', printf('%s is not executable', g:netrw_dav_cmd))
1741                return
1742            endif
1743            if g:netrw_dav_cmd =~ "curl"
1744                call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_dav_cmd." ".netrw#os#Escape("dav://".g:netrw_machine.b:netrw_fname,1)." ".netrw#os#Escape(tmpfile,1))
1745            else
1746                " Construct execution string (four lines) which will be passed through filter
1747                let netrw_fname= escape(b:netrw_fname,g:netrw_fname_escape)
1748                new
1749                setl ff=unix
1750                if exists("g:netrw_port") && g:netrw_port != ""
1751                    NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
1752                else
1753                    NetrwKeepj put ='open '.g:netrw_machine
1754                endif
1755                if exists("g:netrw_uid") && exists("s:netrw_passwd") && g:netrw_uid != ""
1756                    NetrwKeepj put ='user '.g:netrw_uid.' '.s:netrw_passwd
1757                endif
1758                NetrwKeepj put ='get '.netrw_fname.' '.tmpfile
1759                NetrwKeepj put ='quit'
1760
1761                " perform cadaver operation:
1762                NetrwKeepj norm! 1G"_dd
1763                call netrw#os#Execute(s:netrw_silentxfer."%!".g:netrw_dav_cmd)
1764                keepj bd!
1765            endif
1766            let result           = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1767            let b:netrw_lastfile = choice
1768
1769            ".........................................
1770        " NetRead: (rsync) NetRead Method #7 {{{3
1771        elseif     b:netrw_method  == 7
1772            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_rsync_cmd." ".netrw#os#Escape(g:netrw_machine.g:netrw_rsync_sep.b:netrw_fname,1)." ".netrw#os#Escape(tmpfile,1))
1773            let result           = s:NetrwGetFile(readcmd,tmpfile, b:netrw_method)
1774            let b:netrw_lastfile = choice
1775
1776            ".........................................
1777        " NetRead: (fetch) NetRead Method #8 {{{3
1778        "    fetch://[user@]host[:http]/path
1779        elseif     b:netrw_method  == 8
1780            if g:netrw_fetch_cmd == ""
1781                call netrw#msg#Notify('ERROR', "fetch command not available")
1782                return
1783            endif
1784            if exists("g:netrw_option") && g:netrw_option =~ ":https\="
1785                let netrw_option= "http"
1786            else
1787                let netrw_option= "ftp"
1788            endif
1789
1790            if exists("g:netrw_uid") && g:netrw_uid != "" && exists("s:netrw_passwd") && s:netrw_passwd != ""
1791                call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_fetch_cmd." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(netrw_option."://".g:netrw_uid.':'.s:netrw_passwd.'@'.g:netrw_machine."/".b:netrw_fname,1))
1792            else
1793                call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_fetch_cmd." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(netrw_option."://".g:netrw_machine."/".b:netrw_fname,1))
1794            endif
1795
1796            let result          = s:NetrwGetFile(readcmd,tmpfile, b:netrw_method)
1797            let b:netrw_lastfile = choice
1798            setl ro nomod
1799
1800            ".........................................
1801        " NetRead: (sftp) NetRead Method #9 {{{3
1802        elseif     b:netrw_method  == 9
1803            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_sftp_cmd." ".netrw#os#Escape(g:netrw_machine.":".b:netrw_fname,1)." ".netrw#os#Escape(tmpfile,1))
1804            let result          = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1805            let b:netrw_lastfile = choice
1806
1807            ".........................................
1808        " NetRead: (file) NetRead Method #10 {{{3
1809        elseif      b:netrw_method == 10 && exists("g:netrw_file_cmd")
1810            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_file_cmd." ".netrw#os#Escape(b:netrw_fname,1)." ".netrw#os#Escape(tmpfile,1))
1811            let result           = s:NetrwGetFile(readcmd, tmpfile, b:netrw_method)
1812            let b:netrw_lastfile = choice
1813
1814            ".........................................
1815        " NetRead: Complain {{{3
1816        else
1817            call netrw#msg#Notify('WARNING', printf('unable to comply with your request<%s>', choice))
1818        endif
1819    endwhile
1820
1821    " NetRead: cleanup {{{3
1822    if exists("b:netrw_method")
1823        unlet b:netrw_method
1824        unlet b:netrw_fname
1825    endif
1826    if s:FileReadable(tmpfile) && tmpfile !~ '.tar.bz2$' && tmpfile !~ '.tar.gz$' && tmpfile !~ '.zip' && tmpfile !~ '.tar' && readcmd != 't' && tmpfile !~ '.tar.xz$' && tmpfile !~ '.txz'
1827        call netrw#fs#Remove(tmpfile)
1828    endif
1829    NetrwKeepj call s:NetrwOptionsRestore("w:")
1830
1831endfunction
1832
1833" netrw#NetWrite: responsible for writing a file over the net {{{2
1834function netrw#NetWrite(...) range
1835
1836    " NetWrite: option handling {{{3
1837    let mod= 0
1838    call s:NetrwOptionsSave("w:")
1839    call s:NetrwOptionsSafe(0)
1840
1841    " NetWrite: Get Temporary Filename {{{3
1842    let tmpfile= s:GetTempfile("")
1843    if tmpfile == ""
1844        return
1845    endif
1846
1847    if a:0 == 0
1848        let ichoice = 0
1849    else
1850        let ichoice = 1
1851    endif
1852
1853    let curbufname= expand("%")
1854    if &binary
1855        " For binary writes, always write entire file.
1856        " (line numbers don't really make sense for that).
1857        " Also supports the writing of tar and zip files.
1858        exe "sil NetrwKeepj w! ".fnameescape(v:cmdarg)." ".fnameescape(tmpfile)
1859    elseif g:netrw_cygwin
1860        " write (selected portion of) file to temporary
1861        let cygtmpfile= substitute(tmpfile,g:netrw_cygdrive.'/\(.\)','\1:','')
1862        exe "sil NetrwKeepj ".a:firstline."," . a:lastline . "w! ".fnameescape(v:cmdarg)." ".fnameescape(cygtmpfile)
1863    else
1864        " write (selected portion of) file to temporary
1865        exe "sil NetrwKeepj ".a:firstline."," . a:lastline . "w! ".fnameescape(v:cmdarg)." ".fnameescape(tmpfile)
1866    endif
1867
1868    if curbufname == ""
1869        " when the file is [No Name], and one attempts to Nwrite it, the buffer takes
1870        " on the temporary file's name.  Deletion of the temporary file during
1871        " cleanup then causes an error message.
1872        0file!
1873    endif
1874
1875    " NetWrite: while choice loop: {{{3
1876    while ichoice <= a:0
1877
1878        " Process arguments: {{{4
1879        " attempt to repeat with previous host-file-etc
1880        if exists("b:netrw_lastfile") && a:0 == 0
1881            let choice = b:netrw_lastfile
1882            let ichoice= ichoice + 1
1883        else
1884            exe "let choice= a:" . ichoice
1885
1886            " Reconstruct Choice when choice starts with '"'
1887            if match(choice,"?") == 0
1888                echomsg 'NetWrite Usage:"'
1889                echomsg ':Nwrite machine:path                        uses rcp'
1890                echomsg ':Nwrite "machine path"                      uses ftp with <.netrc>'
1891                echomsg ':Nwrite "machine id password path"          uses ftp'
1892                echomsg ':Nwrite dav://[user@]machine/path           uses cadaver'
1893                echomsg ':Nwrite fetch://[user@]machine/path         uses fetch'
1894                echomsg ':Nwrite ftp://machine[#port]/path           uses ftp  (autodetects <.netrc>)'
1895                echomsg ':Nwrite rcp://machine/path                  uses rcp'
1896                echomsg ':Nwrite rsync://[user@]machine/path         uses rsync'
1897                echomsg ':Nwrite scp://[user@]machine[[:#]port]/path uses scp'
1898                echomsg ':Nwrite sftp://[user@]machine/path          uses sftp'
1899                sleep 4
1900                break
1901
1902            elseif match(choice,"^\"") != -1
1903                if match(choice,"\"$") != -1
1904                    " case "..."
1905                    let choice=strpart(choice,1,strlen(choice)-2)
1906                else
1907                    "  case "... ... ..."
1908                    let choice      = strpart(choice,1,strlen(choice)-1)
1909                    let wholechoice = ""
1910
1911                    while match(choice,"\"$") == -1
1912                        let wholechoice= wholechoice . " " . choice
1913                        let ichoice    = ichoice + 1
1914                        if choice > a:0
1915                            call netrw#msg#Notify('ERROR', printf('Unbalanced string in filename "%s"', wholechoice))
1916                            return
1917                        endif
1918                        let choice= a:{ichoice}
1919                    endwhile
1920                    let choice= strpart(wholechoice,1,strlen(wholechoice)-1) . " " . strpart(choice,0,strlen(choice)-1)
1921                endif
1922            endif
1923        endif
1924        let ichoice= ichoice + 1
1925
1926        " Determine method of write (ftp, rcp, etc) {{{4
1927        NetrwKeepj call s:NetrwMethod(choice)
1928        if !exists("b:netrw_method") || b:netrw_method < 0
1929            return
1930        endif
1931        if !s:NetrwValidateHostname(g:netrw_machine)
1932            call netrw#msg#Notify('ERROR', printf('Rejecting invalid hostname: <%s>', g:netrw_machine))
1933            return
1934        endif
1935
1936        " =============
1937        " NetWrite: Perform Protocol-Based Write {{{3
1938        " ============================
1939        if exists("g:netrw_silent") && g:netrw_silent == 0 && &ch >= 1
1940            echo "(netrw) Processing your write request..."
1941        endif
1942
1943        ".........................................
1944        " NetWrite: (rcp) NetWrite Method #1 {{{3
1945        if  b:netrw_method == 1
1946            if s:netrw_has_nt_rcp == 1
1947                if exists("g:netrw_uid") &&  ( g:netrw_uid != "" )
1948                    let uid_machine = g:netrw_machine .'.'. g:netrw_uid
1949                else
1950                    let uid_machine = g:netrw_machine .'.'. $USERNAME
1951                endif
1952            else
1953                if exists("g:netrw_uid") &&  ( g:netrw_uid != "" )
1954                    let uid_machine = g:netrw_uid .'@'. g:netrw_machine
1955                else
1956                    let uid_machine = g:netrw_machine
1957                endif
1958            endif
1959            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_rcp_cmd." ".s:netrw_rcpmode." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(uid_machine.":".b:netrw_fname,1))
1960            let b:netrw_lastfile = choice
1961
1962            ".........................................
1963        " NetWrite: (ftp + <.netrc>) NetWrite Method #2 {{{3
1964        elseif b:netrw_method == 2
1965            let netrw_fname = b:netrw_fname
1966
1967            " formerly just a "new...bd!", that changed the window sizes when equalalways.  Using enew workaround instead
1968            let bhkeep      = &l:bh
1969            let curbuf      = bufnr("%")
1970            setl bh=hide
1971            keepj keepalt enew
1972
1973            setl ff=unix
1974            NetrwKeepj put =g:netrw_ftpmode
1975            if exists("g:netrw_ftpextracmd")
1976                NetrwKeepj put =g:netrw_ftpextracmd
1977            endif
1978            NetrwKeepj call setline(line("$")+1,'put "'.tmpfile.'" "'.netrw_fname.'"')
1979            if exists("g:netrw_port") && g:netrw_port != ""
1980                call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1)." ".netrw#os#Escape(g:netrw_port,1))
1981            else
1982                call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1))
1983            endif
1984            " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
1985            if getline(1) !~ "^$"
1986                call netrw#msg#Notify('ERROR', getline(1))
1987                let mod=1
1988            endif
1989
1990            " remove enew buffer (quietly)
1991            let filtbuf= bufnr("%")
1992            exe curbuf."b!"
1993            let &l:bh            = bhkeep
1994            exe filtbuf."bw!"
1995
1996            let b:netrw_lastfile = choice
1997
1998            ".........................................
1999        " NetWrite: (ftp + machine, id, passwd, filename) NetWrite Method #3 {{{3
2000        elseif b:netrw_method == 3
2001            " Construct execution string (three or more lines) which will be passed through filter
2002            let netrw_fname = b:netrw_fname
2003            let bhkeep      = &l:bh
2004
2005            " formerly just a "new...bd!", that changed the window sizes when equalalways.  Using enew workaround instead
2006            let curbuf      = bufnr("%")
2007            setl bh=hide
2008            keepj keepalt enew
2009            setl ff=unix
2010
2011            if exists("g:netrw_port") && g:netrw_port != ""
2012                NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
2013            else
2014                NetrwKeepj put ='open '.g:netrw_machine
2015            endif
2016            if exists("g:netrw_uid") && g:netrw_uid != ""
2017                if exists("g:netrw_ftp") && g:netrw_ftp == 1
2018                    NetrwKeepj put =g:netrw_uid
2019                    if exists("s:netrw_passwd") && s:netrw_passwd != ""
2020                        NetrwKeepj put ='\"'.s:netrw_passwd.'\"'
2021                    endif
2022                elseif exists("s:netrw_passwd") && s:netrw_passwd != ""
2023                    NetrwKeepj put ='user \"'.g:netrw_uid.'\" \"'.s:netrw_passwd.'\"'
2024                endif
2025            endif
2026            NetrwKeepj put =g:netrw_ftpmode
2027            if exists("g:netrw_ftpextracmd")
2028                NetrwKeepj put =g:netrw_ftpextracmd
2029            endif
2030            NetrwKeepj put ='put \"'.tmpfile.'\" \"'.netrw_fname.'\"'
2031            " save choice/id/password for future use
2032            let b:netrw_lastfile = choice
2033
2034            " perform ftp:
2035            " -i       : turns off interactive prompting from ftp
2036            " -n  unix : DON'T use <.netrc>, even though it exists
2037            " -n  win32: quit being obnoxious about password
2038            NetrwKeepj norm! 1G"_dd
2039            call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." ".g:netrw_ftp_options)
2040            " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
2041            if getline(1) !~ "^$"
2042                call netrw#msg#Notify('ERROR', getline(1))
2043                let mod=1
2044            endif
2045
2046            " remove enew buffer (quietly)
2047            let filtbuf= bufnr("%")
2048            exe curbuf."b!"
2049            let &l:bh= bhkeep
2050            exe filtbuf."bw!"
2051
2052            ".........................................
2053        " NetWrite: (scp) NetWrite Method #4 {{{3
2054        elseif     b:netrw_method == 4
2055            if exists("g:netrw_port") && g:netrw_port != ""
2056                let useport= " ".g:netrw_scpport." ".fnameescape(g:netrw_port)
2057            else
2058                let useport= ""
2059            endif
2060            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_scp_cmd.useport." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(g:netrw_machine.":".b:netrw_fname,1))
2061            let b:netrw_lastfile = choice
2062
2063            ".........................................
2064        " NetWrite: (http) NetWrite Method #5 {{{3
2065        elseif     b:netrw_method == 5
2066            let curl= substitute(g:netrw_http_put_cmd,'\s\+.*$',"","")
2067            if executable(curl)
2068                let url= g:netrw_choice
2069                call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_http_put_cmd." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(url,1) )
2070            else
2071                call netrw#msg#Notify('ERROR', printf("can't write to http using <%s>", g:netrw_http_put_cmd))
2072            endif
2073
2074            ".........................................
2075        " NetWrite: (dav) NetWrite Method #6 (cadaver) {{{3
2076        elseif     b:netrw_method == 6
2077
2078            " Construct execution string (four lines) which will be passed through filter
2079            let netrw_fname = escape(b:netrw_fname,g:netrw_fname_escape)
2080            let bhkeep      = &l:bh
2081
2082            " formerly just a "new...bd!", that changed the window sizes when equalalways.  Using enew workaround instead
2083            let curbuf      = bufnr("%")
2084            setl bh=hide
2085            keepj keepalt enew
2086
2087            setl ff=unix
2088            if exists("g:netrw_port") && g:netrw_port != ""
2089                NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
2090            else
2091                NetrwKeepj put ='open '.g:netrw_machine
2092            endif
2093            if exists("g:netrw_uid") && exists("s:netrw_passwd") && g:netrw_uid != ""
2094                NetrwKeepj put ='user '.g:netrw_uid.' '.s:netrw_passwd
2095            endif
2096            NetrwKeepj put ='put '.tmpfile.' '.netrw_fname
2097
2098            " perform cadaver operation:
2099            NetrwKeepj norm! 1G"_dd
2100            call netrw#os#Execute(s:netrw_silentxfer."%!".g:netrw_dav_cmd)
2101
2102            " remove enew buffer (quietly)
2103            let filtbuf= bufnr("%")
2104            exe curbuf."b!"
2105            let &l:bh            = bhkeep
2106            exe filtbuf."bw!"
2107
2108            let b:netrw_lastfile = choice
2109
2110            ".........................................
2111        " NetWrite: (rsync) NetWrite Method #7 {{{3
2112        elseif     b:netrw_method == 7
2113            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_rsync_cmd." ".netrw#os#Escape(tmpfile,1)." ".netrw#os#Escape(g:netrw_machine.g:netrw_rsync_sep.b:netrw_fname,1))
2114            let b:netrw_lastfile = choice
2115
2116            ".........................................
2117        " NetWrite: (sftp) NetWrite Method #9 {{{3
2118        elseif     b:netrw_method == 9
2119            let netrw_fname= escape(b:netrw_fname,g:netrw_fname_escape)
2120            if exists("g:netrw_uid") &&  ( g:netrw_uid != "" )
2121                let uid_machine = g:netrw_uid .'@'. g:netrw_machine
2122            else
2123                let uid_machine = g:netrw_machine
2124            endif
2125
2126            " formerly just a "new...bd!", that changed the window sizes when equalalways.  Using enew workaround instead
2127            let bhkeep = &l:bh
2128            let curbuf = bufnr("%")
2129            setl bh=hide
2130            keepj keepalt enew
2131
2132            setl ff=unix
2133            call setline(1,'put "'.escape(tmpfile,'\').'" '.netrw_fname)
2134            let sftpcmd= substitute(g:netrw_sftp_cmd,"%TEMPFILE%",escape(tmpfile,'\'),"g")
2135            call netrw#os#Execute(s:netrw_silentxfer."%!".sftpcmd.' '.netrw#os#Escape(uid_machine,1))
2136            let filtbuf= bufnr("%")
2137            exe curbuf."b!"
2138            let &l:bh            = bhkeep
2139            exe filtbuf."bw!"
2140            let b:netrw_lastfile = choice
2141
2142            ".........................................
2143        " NetWrite: Complain {{{3
2144        else
2145            call netrw#msg#Notify('WARNING', printf('unable to comply with your request<%s>', choice))
2146            let leavemod= 1
2147        endif
2148    endwhile
2149
2150    " NetWrite: Cleanup: {{{3
2151    if s:FileReadable(tmpfile)
2152        call netrw#fs#Remove(tmpfile)
2153    endif
2154    call s:NetrwOptionsRestore("w:")
2155
2156    if a:firstline == 1 && a:lastline == line("$")
2157        " restore modifiability; usually equivalent to set nomod
2158        let &l:mod= mod
2159    elseif !exists("leavemod")
2160        " indicate that the buffer has not been modified since last written
2161        setl nomod
2162    endif
2163
2164endfunction
2165
2166" netrw#NetSource: source a remotely hosted Vim script {{{2
2167" uses NetRead to get a copy of the file into a temporarily file,
2168"              then sources that file,
2169"              then removes that file.
2170function netrw#NetSource(...)
2171    if a:0 > 0 && a:1 == '?'
2172        " give help
2173        echomsg 'NetSource Usage:'
2174        echomsg ':Nsource dav://machine[:port]/path            uses cadaver'
2175        echomsg ':Nsource fetch://machine/path                 uses fetch'
2176        echomsg ':Nsource ftp://[user@]machine[:port]/path     uses ftp   autodetects <.netrc>'
2177        echomsg ':Nsource http[s]://[user@]machine/path        uses http  wget'
2178        echomsg ':Nsource rcp://[user@]machine/path            uses rcp'
2179        echomsg ':Nsource rsync://machine[:port]/path          uses rsync'
2180        echomsg ':Nsource scp://[user@]machine[[:#]port]/path  uses scp'
2181        echomsg ':Nsource sftp://[user@]machine[[:#]port]/path uses sftp'
2182        sleep 4
2183    else
2184        let i= 1
2185        while i <= a:0
2186            call netrw#NetRead(3,a:{i})
2187            if s:FileReadable(s:netrw_tmpfile)
2188                exe "so ".fnameescape(s:netrw_tmpfile)
2189                if delete(s:netrw_tmpfile)
2190                    call netrw#msg#Notify('ERROR', 'unable to delete directory <%s>', s:netrw_tmpfile)
2191                endif
2192                unlet s:netrw_tmpfile
2193            else
2194                call netrw#msg#Notify('ERROR', printf('unable to source <%s>!', a:{i}))
2195            endif
2196            let i= i + 1
2197        endwhile
2198    endif
2199endfunction
2200
2201" netrw#SetTreetop: resets the tree top to the current directory/specified directory {{{2
2202"                   (implements the :Ntree command)
2203function netrw#SetTreetop(iscmd,...)
2204
2205    " iscmd==0: netrw#SetTreetop called using gn mapping
2206    " iscmd==1: netrw#SetTreetop called using :Ntree from the command line
2207    " clear out the current tree
2208    if exists("w:netrw_treetop")
2209        let inittreetop= w:netrw_treetop
2210        unlet w:netrw_treetop
2211    endif
2212    if exists("w:netrw_treedict")
2213        unlet w:netrw_treedict
2214    endif
2215
2216    if (a:iscmd == 0 || a:1 == "") && exists("inittreetop")
2217        let treedir         = s:NetrwTreePath(inittreetop)
2218    else
2219        if isdirectory(s:NetrwFile(a:1))
2220            let treedir         = a:1
2221            let s:netrw_treetop = treedir
2222        elseif exists("b:netrw_curdir") && (isdirectory(s:NetrwFile(b:netrw_curdir."/".a:1)) || a:1 =~ '^\a\{3,}://')
2223            let treedir         = b:netrw_curdir."/".a:1
2224            let s:netrw_treetop = treedir
2225        else
2226            " normally the cursor is left in the message window.
2227            " However, here this results in the directory being listed in the message window, which is not wanted.
2228            let netrwbuf= bufnr("%")
2229            call netrw#msg#Notify('ERROR', printf("sorry, %s doesn't seem to be a directory!", a:1))
2230            exe bufwinnr(netrwbuf)."wincmd w"
2231            let treedir         = "."
2232            let s:netrw_treetop = getcwd()
2233        endif
2234    endif
2235
2236    " determine if treedir is remote or local
2237    let islocal= expand("%") !~ '^\a\{3,}://'
2238
2239    " browse the resulting directory
2240    if islocal
2241        call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(islocal,treedir,0))
2242    else
2243        call s:NetrwBrowse(islocal,s:NetrwBrowseChgDir(islocal,treedir,0))
2244    endif
2245
2246endfunction
2247
2248" s:NetrwGetFile: Function to read temporary file "tfile" with command "readcmd". {{{2
2249"    readcmd == %r : replace buffer with newly read file
2250"            == 0r : read file at top of buffer
2251"            == r  : read file after current line
2252"            == t  : leave file in temporary form (ie. don't read into buffer)
2253function s:NetrwGetFile(readcmd, tfile, method)
2254
2255    " readcmd=='t': simply do nothing
2256    if a:readcmd == 't'
2257        return
2258    endif
2259
2260    " get name of remote filename (ie. url and all)
2261    let rfile= bufname("%")
2262
2263    if exists("*NetReadFixup")
2264        " for the use of NetReadFixup (not otherwise used internally)
2265        let line2= line("$")
2266    endif
2267
2268    if a:readcmd[0] == '%'
2269        " get file into buffer
2270
2271        " rename the current buffer to the temp file (ie. tfile)
2272        if g:netrw_cygwin
2273            let tfile= substitute(a:tfile,g:netrw_cygdrive.'/\(.\)','\1:','')
2274        else
2275            let tfile= a:tfile
2276        endif
2277        call s:NetrwBufRename(tfile)
2278
2279        " edit temporary file (ie. read the temporary file in)
2280        if     rfile =~ '\.zip$'
2281            if exists("#zip")
2282                call zip#Browse(tfile)
2283            elseif exists("#nvim.zip")
2284                call s:NetrwBufRename(rfile)
2285                call luaeval("require('nvim.zip').browse(_A[1], _A[2])", [bufnr(), tfile])
2286            endif
2287        elseif rfile =~ '\.tar$'
2288            call tar#Browse(tfile)
2289        elseif rfile =~ '\.tar\.gz$'
2290            call tar#Browse(tfile)
2291        elseif rfile =~ '\.tar\.bz2$'
2292            call tar#Browse(tfile)
2293        elseif rfile =~ '\.tar\.xz$'
2294            call tar#Browse(tfile)
2295        elseif rfile =~ '\.txz$'
2296            call tar#Browse(tfile)
2297        else
2298            NetrwKeepj e!
2299        endif
2300
2301        " rename buffer back to remote filename
2302        call s:NetrwBufRename(rfile)
2303
2304        " Jan 19, 2022: COMBAK -- bram problem with https://github.com/vim/vim/pull/9554.diff filetype
2305        " Detect filetype of local version of remote file.
2306        " Note that isk must not include a "/" for scripts.vim
2307        " to process this detection correctly.
2308        "   setl ft=
2309        let iskkeep= &isk
2310        setl isk-=/
2311        filetype detect
2312        let &l:isk= iskkeep
2313        let line1 = 1
2314        let line2 = line("$")
2315
2316    elseif !&ma
2317        " attempting to read a file after the current line in the file, but the buffer is not modifiable
2318        call netrw#msg#Notify('WARNING', printf('attempt to read<%s> into a non-modifiable buffer!', a:tfile))
2319        return
2320
2321    elseif s:FileReadable(a:tfile)
2322        " read file after current line
2323        let curline = line(".")
2324        let lastline= line("$")
2325        exe "NetrwKeepj ".a:readcmd." ".fnameescape(v:cmdarg)." ".fnameescape(a:tfile)
2326        let line1= curline + 1
2327        let line2= line("$") - lastline + 1
2328
2329    else
2330        " not readable
2331        call netrw#msg#Notify('WARNING', printf('file <%s> not readable', a:tfile))
2332        return
2333    endif
2334
2335    " User-provided (ie. optional) fix-it-up command
2336    if exists("*NetReadFixup")
2337        NetrwKeepj call NetReadFixup(a:method, line1, line2)
2338    endif
2339
2340    if has("gui") && has("menu") && has("gui_running") && &go =~# 'm' && g:netrw_menu
2341        " update the Buffers menu
2342        NetrwKeepj call s:UpdateBuffersMenu()
2343    endif
2344
2345
2346    " make sure file is being displayed
2347    "  redraw!
2348
2349endfunction
2350
2351" s:NetrwMethod:  determine method of transfer {{{2
2352" Input:
2353"   choice = url   [protocol:]//[userid@]hostname[:port]/[path-to-file]
2354" Output:
2355"  b:netrw_method= 1: rcp
2356"                  2: ftp + <.netrc>
2357"                  3: ftp + machine, id, password, and [path]filename
2358"                  4: scp
2359"                  5: http[s] (wget)
2360"                  6: dav
2361"                  7: rsync
2362"                  8: fetch
2363"                  9: sftp
2364"                 10: file
2365"  g:netrw_machine= hostname
2366"  b:netrw_fname  = filename
2367"  g:netrw_port   = optional port number (for ftp)
2368"  g:netrw_choice = copy of input url (choice)
2369function s:NetrwMethod(choice)
2370
2371    " sanity check: choice should have at least three slashes in it
2372    if strlen(substitute(a:choice,'[^/]','','g')) < 3
2373        call netrw#msg#Notify('ERROR', 'not a netrw-style url; netrw uses protocol://[user@]hostname[:port]/[path])')
2374        let b:netrw_method = -1
2375        return
2376    endif
2377
2378    " record current g:netrw_machine, if any
2379    " curmachine used if protocol == ftp and no .netrc
2380    if exists("g:netrw_machine")
2381        let curmachine= g:netrw_machine
2382    else
2383        let curmachine= "N O T A HOST"
2384    endif
2385    if exists("g:netrw_port")
2386        let netrw_port= g:netrw_port
2387    endif
2388
2389    " insure that netrw_ftp_cmd starts off every method determination
2390    " with the current g:netrw_ftp_cmd
2391    let s:netrw_ftp_cmd= g:netrw_ftp_cmd
2392
2393    " initialization
2394    let b:netrw_method  = 0
2395    let g:netrw_machine = ""
2396    let b:netrw_fname   = ""
2397    let g:netrw_port    = ""
2398    let g:netrw_choice  = a:choice
2399
2400    " Patterns:
2401    " mipf     : a:machine a:id password filename      Use ftp
2402    " mf      : a:machine filename                     Use ftp + <.netrc> or g:netrw_uid s:netrw_passwd
2403    " ftpurm   : ftp://[user@]host[[#:]port]/filename  Use ftp + <.netrc> or g:netrw_uid s:netrw_passwd
2404    " rcpurm   : rcp://[user@]host/filename            Use rcp
2405    " rcphf    : [user@]host:filename                  Use rcp
2406    " scpurm   : scp://[user@]host[[#:]port]/filename  Use scp
2407    " httpurm  : http[s]://[user@]host/filename        Use wget
2408    " davurm   : dav[s]://host[:port]/path             Use cadaver/curl
2409    " rsyncurm : rsync://host[:port]/path              Use rsync
2410    " fetchurm : fetch://[user@]host[:http]/filename   Use fetch (defaults to ftp, override for http)
2411    " sftpurm  : sftp://[user@]host/filename  Use scp
2412    " fileurm  : file://[user@]host/filename           Use elinks or links
2413    let mipf     = '^\(\S\+\)\s\+\(\S\+\)\s\+\(\S\+\)\s\+\(\S\+\)$'
2414    let mf       = '^\(\S\+\)\s\+\(\S\+\)$'
2415    let ftpurm   = '^ftp://\(\([^/]*\)@\)\=\([^/#:]\{-}\)\([#:]\d\+\)\=/\(.*\)$'
2416    let rcpurm   = '^rcp://\%(\([^/]*\)@\)\=\([^/]\{-}\)/\(.*\)$'
2417    let rcphf    = '^\(\(\h\w*\)@\)\=\(\h\w*\):\([^@]\+\)$'
2418    let scpurm   = '^scp://\([^/#:]\+\)\%([#:]\(\d\+\)\)\=/\(.*\)$'
2419    let httpurm  = '^https\=://\([^/]\{-}\)\(/.*\)\=$'
2420    let davurm   = '^davs\=://\([^/]\+\)/\(.*/\)\([-_.~[:alnum:]]\+\)$'
2421    let rsyncurm = '^rsync://\([^/]\{-}\)/\(.*\)\=$'
2422    let fetchurm = '^fetch://\(\([^/]*\)@\)\=\([^/#:]\{-}\)\(:http\)\=/\(.*\)$'
2423    let sftpurm  = '^sftp://\([^/]\{-}\)/\(.*\)\=$'
2424    let fileurm  = '^file\=://\(.*\)$'
2425
2426    " Determine Method
2427    " Method#1: rcp://user@hostname/...path-to-file {{{3
2428    if match(a:choice,rcpurm) == 0
2429        let b:netrw_method  = 1
2430        let userid          = substitute(a:choice,rcpurm,'\1',"")
2431        let g:netrw_machine = substitute(a:choice,rcpurm,'\2',"")
2432        let b:netrw_fname   = substitute(a:choice,rcpurm,'\3',"")
2433        if userid != ""
2434            let g:netrw_uid= userid
2435        endif
2436
2437    " Method#4: scp://user@hostname/...path-to-file {{{3
2438    elseif match(a:choice,scpurm) == 0
2439        let b:netrw_method  = 4
2440        let g:netrw_machine = substitute(a:choice,scpurm,'\1',"")
2441        let g:netrw_port    = substitute(a:choice,scpurm,'\2',"")
2442        let b:netrw_fname   = substitute(a:choice,scpurm,'\3',"")
2443
2444    " Method#5: http[s]://user@hostname/...path-to-file {{{3
2445    elseif match(a:choice,httpurm) == 0
2446        let b:netrw_method = 5
2447        let g:netrw_machine= substitute(a:choice,httpurm,'\1',"")
2448        let b:netrw_fname  = substitute(a:choice,httpurm,'\2',"")
2449        let b:netrw_http   = (a:choice =~ '^https:')? "https" : "http"
2450
2451    " Method#6: dav://hostname[:port]/..path-to-file.. {{{3
2452    elseif match(a:choice,davurm) == 0
2453        let b:netrw_method= 6
2454        if a:choice =~ 'davs:'
2455            let g:netrw_machine= 'https://'.substitute(a:choice,davurm,'\1/\2',"")
2456        else
2457            let g:netrw_machine= 'http://'.substitute(a:choice,davurm,'\1/\2',"")
2458        endif
2459        let b:netrw_fname  = substitute(a:choice,davurm,'\3',"")
2460
2461    " Method#7: rsync://user@hostname/...path-to-file {{{3
2462    elseif match(a:choice,rsyncurm) == 0
2463        let b:netrw_method = 7
2464        let g:netrw_machine= substitute(a:choice,rsyncurm,'\1',"")
2465        let b:netrw_fname  = substitute(a:choice,rsyncurm,'\2',"")
2466
2467    " Methods 2,3: ftp://[user@]hostname[[:#]port]/...path-to-file {{{3
2468    elseif match(a:choice,ftpurm) == 0
2469        let userid         = substitute(a:choice,ftpurm,'\2',"")
2470        let g:netrw_machine= substitute(a:choice,ftpurm,'\3',"")
2471        let g:netrw_port   = substitute(a:choice,ftpurm,'\4',"")
2472        let b:netrw_fname  = substitute(a:choice,ftpurm,'\5',"")
2473        if userid != ""
2474            let g:netrw_uid= userid
2475        endif
2476
2477        if curmachine != g:netrw_machine
2478            if exists("s:netrw_hup[".g:netrw_machine."]")
2479                call netrw#NetUserPass("ftp:".g:netrw_machine)
2480            elseif exists("s:netrw_passwd")
2481                " if there's a change in hostname, require password re-entry
2482                unlet s:netrw_passwd
2483            endif
2484            if exists("netrw_port")
2485                unlet netrw_port
2486            endif
2487        endif
2488
2489        if exists("g:netrw_uid") && exists("s:netrw_passwd")
2490            let b:netrw_method = 3
2491        else
2492            let host= substitute(g:netrw_machine,'\..*$','','')
2493            if exists("s:netrw_hup[host]")
2494                call netrw#NetUserPass("ftp:".host)
2495
2496            elseif has("win32") && s:netrw_ftp_cmd =~# '-[sS]:'
2497                if g:netrw_ftp_cmd =~# '-[sS]:\S*MACHINE\>'
2498                    let s:netrw_ftp_cmd= substitute(g:netrw_ftp_cmd,'\<MACHINE\>',g:netrw_machine,'')
2499                endif
2500                let b:netrw_method= 2
2501            elseif s:FileReadable(expand("$HOME/.netrc")) && !g:netrw_ignorenetrc
2502                let b:netrw_method= 2
2503            else
2504                if !exists("g:netrw_uid") || g:netrw_uid == ""
2505                    call netrw#NetUserPass()
2506                elseif !exists("s:netrw_passwd") || s:netrw_passwd == ""
2507                    call netrw#NetUserPass(g:netrw_uid)
2508                    " else just use current g:netrw_uid and s:netrw_passwd
2509                endif
2510                let b:netrw_method= 3
2511            endif
2512        endif
2513
2514    " Method#8: fetch {{{3
2515    elseif match(a:choice,fetchurm) == 0
2516        let b:netrw_method = 8
2517        let g:netrw_userid = substitute(a:choice,fetchurm,'\2',"")
2518        let g:netrw_machine= substitute(a:choice,fetchurm,'\3',"")
2519        let b:netrw_option = substitute(a:choice,fetchurm,'\4',"")
2520        let b:netrw_fname  = substitute(a:choice,fetchurm,'\5',"")
2521
2522    " Method#3: Issue an ftp : "machine id password [path/]filename" {{{3
2523    elseif match(a:choice,mipf) == 0
2524        let b:netrw_method  = 3
2525        let g:netrw_machine = substitute(a:choice,mipf,'\1',"")
2526        let g:netrw_uid     = substitute(a:choice,mipf,'\2',"")
2527        let s:netrw_passwd  = substitute(a:choice,mipf,'\3',"")
2528        let b:netrw_fname   = substitute(a:choice,mipf,'\4',"")
2529        call netrw#NetUserPass(g:netrw_machine,g:netrw_uid,s:netrw_passwd)
2530
2531    " Method#3: Issue an ftp: "hostname [path/]filename" {{{3
2532    elseif match(a:choice,mf) == 0
2533        if exists("g:netrw_uid") && exists("s:netrw_passwd")
2534            let b:netrw_method  = 3
2535            let g:netrw_machine = substitute(a:choice,mf,'\1',"")
2536            let b:netrw_fname   = substitute(a:choice,mf,'\2',"")
2537
2538        elseif s:FileReadable(expand("$HOME/.netrc"))
2539            let b:netrw_method  = 2
2540            let g:netrw_machine = substitute(a:choice,mf,'\1',"")
2541            let b:netrw_fname   = substitute(a:choice,mf,'\2',"")
2542        endif
2543
2544    " Method#9: sftp://user@hostname/...path-to-file {{{3
2545    elseif match(a:choice,sftpurm) == 0
2546        let b:netrw_method = 9
2547        let g:netrw_machine= substitute(a:choice,sftpurm,'\1',"")
2548        let b:netrw_fname  = substitute(a:choice,sftpurm,'\2',"")
2549
2550    " Method#1: Issue an rcp: hostname:filename"  (this one should be last) {{{3
2551    elseif match(a:choice,rcphf) == 0
2552        let b:netrw_method  = 1
2553        let userid          = substitute(a:choice,rcphf,'\2',"")
2554        let g:netrw_machine = substitute(a:choice,rcphf,'\3',"")
2555        let b:netrw_fname   = substitute(a:choice,rcphf,'\4',"")
2556        if userid != ""
2557            let g:netrw_uid= userid
2558        endif
2559
2560    " Method#10: file://user@hostname/...path-to-file {{{3
2561    elseif match(a:choice,fileurm) == 0 && exists("g:netrw_file_cmd")
2562        let b:netrw_method = 10
2563        let b:netrw_fname  = substitute(a:choice,fileurm,'\1',"")
2564
2565    " Cannot Determine Method {{{3
2566    else
2567        call netrw#msg#Notify('WARNING', 'cannot determine method (format: protocol://[user@]hostname[:port]/[path])')
2568        let b:netrw_method  = -1
2569    endif
2570    "}}}3
2571
2572    if g:netrw_port != ""
2573        " remove any leading [:#] from port number
2574        let g:netrw_port = substitute(g:netrw_port,'[#:]\+','','')
2575    elseif exists("netrw_port")
2576        " retain port number as implicit for subsequent ftp operations
2577        let g:netrw_port= netrw_port
2578    endif
2579
2580endfunction
2581
2582" s:NetrwValidateHostname:  Validate that the hostname is valid {{{2
2583" Input:
2584"   hostname, may include an optional username and port number, e.g.
2585"       user@hostname:port
2586"   allow a alphanumeric hostname or an IPv(4/6) address
2587" Output:
2588"  true if g:netrw_machine is valid according to RFC1123 #Section 2
2589function s:NetrwValidateHostname(hostname)
2590  " Username:
2591  let user_pat = '\%([a-zA-Z0-9._-]\+@\)\?'
2592  " Hostname: 1-64 chars, alphanumeric/dots/hyphens.
2593  " No leading/trailing dots/hyphens.
2594  let host_pat = '[a-zA-Z0-9_]\%([-a-zA-Z0-9._]\{0,62}[a-zA-Z0-9_]\)\?'
2595  " Port: 16 bit unsigned integer
2596  let port_pat = '\%(:\d\{1,5\}\)\?$'
2597
2598  " IPv4: 1-3 digits separated by dots
2599  let ipv4_pat = '\%(\d\{1,3}\.\)\{3\}\d\{1,3\}'
2600
2601  " IPv6: Hex, colons, and optional brackets
2602  let ipv6_pat = '\[\?\%([a-fA-F0-9:]\{2,}\)\+\]\?'
2603
2604  return a:hostname =~? '^'.user_pat.host_pat.port_pat ||
2605       \ a:hostname =~? '^'.user_pat.ipv4_pat.port_pat ||
2606       \ a:hostname =~? '^'.user_pat.ipv6_pat.port_pat
2607endfunction
2608
2609" NetUserPass: set username and password for subsequent ftp transfer {{{2
2610"   Usage:  :call netrw#NetUserPass()                        -- will prompt for userid and password
2611"           :call netrw#NetUserPass("uid")                   -- will prompt for password
2612"           :call netrw#NetUserPass("uid","password")        -- sets global userid and password
2613"           :call netrw#NetUserPass("ftp:host")              -- looks up userid and password using hup dictionary
2614"           :call netrw#NetUserPass("host","uid","password") -- sets hup dictionary with host, userid, password
2615function netrw#NetUserPass(...)
2616
2617
2618    if !exists('s:netrw_hup')
2619        let s:netrw_hup= {}
2620    endif
2621
2622    if a:0 == 0
2623        " case: no input arguments
2624
2625        " change host and username if not previously entered; get new password
2626        if !exists("g:netrw_machine")
2627            let g:netrw_machine= input('Enter hostname: ')
2628        endif
2629        if !exists("g:netrw_uid") || g:netrw_uid == ""
2630            " get username (user-id) via prompt
2631            let g:netrw_uid= input('Enter username: ')
2632        endif
2633        " get password via prompting
2634        let s:netrw_passwd= inputsecret("Enter Password: ")
2635
2636        " set up hup database
2637        let host = substitute(g:netrw_machine,'\..*$','','')
2638        if !exists('s:netrw_hup[host]')
2639            let s:netrw_hup[host]= {}
2640        endif
2641        let s:netrw_hup[host].uid    = g:netrw_uid
2642        let s:netrw_hup[host].passwd = s:netrw_passwd
2643
2644    elseif a:0 == 1
2645        " case: one input argument
2646
2647        if a:1 =~ '^ftp:'
2648            " get host from ftp:... url
2649            " access userid and password from hup (host-user-passwd) dictionary
2650            let host = substitute(a:1,'^ftp:','','')
2651            let host = substitute(host,'\..*','','')
2652            if exists("s:netrw_hup[host]")
2653                let g:netrw_uid    = s:netrw_hup[host].uid
2654                let s:netrw_passwd = s:netrw_hup[host].passwd
2655            else
2656                let g:netrw_uid    = input("Enter UserId: ")
2657                let s:netrw_passwd = inputsecret("Enter Password: ")
2658            endif
2659
2660        else
2661            " case: one input argument, not an url.  Using it as a new user-id.
2662            if exists("g:netrw_machine")
2663                if g:netrw_machine =~ '[0-9.]\+'
2664                    let host= g:netrw_machine
2665                else
2666                    let host= substitute(g:netrw_machine,'\..*$','','')
2667                endif
2668            else
2669                let g:netrw_machine= input('Enter hostname: ')
2670            endif
2671            let g:netrw_uid = a:1
2672            if exists("g:netrw_passwd")
2673                " ask for password if one not previously entered
2674                let s:netrw_passwd= g:netrw_passwd
2675            else
2676                let s:netrw_passwd = inputsecret("Enter Password: ")
2677            endif
2678        endif
2679
2680        if exists("host")
2681            if !exists('s:netrw_hup[host]')
2682                let s:netrw_hup[host]= {}
2683            endif
2684            let s:netrw_hup[host].uid    = g:netrw_uid
2685            let s:netrw_hup[host].passwd = s:netrw_passwd
2686        endif
2687
2688    elseif a:0 == 2
2689        let g:netrw_uid    = a:1
2690        let s:netrw_passwd = a:2
2691
2692    elseif a:0 == 3
2693        " enter hostname, user-id, and password into the hup dictionary
2694        let host = substitute(a:1,'^\a\+:','','')
2695        let host = substitute(host,'\..*$','','')
2696        if !exists('s:netrw_hup[host]')
2697            let s:netrw_hup[host]= {}
2698        endif
2699        let s:netrw_hup[host].uid    = a:2
2700        let s:netrw_hup[host].passwd = a:3
2701        let g:netrw_uid              = s:netrw_hup[host].uid
2702        let s:netrw_passwd           = s:netrw_hup[host].passwd
2703    endif
2704
2705endfunction
2706
2707"  Shared Browsing Support:    {{{1
2708
2709" s:ExplorePatHls: converts an Explore pattern into a regular expression search pattern {{{2
2710function s:ExplorePatHls(pattern)
2711    let repat= substitute(a:pattern,'^**/\{1,2}','','')
2712    let repat= escape(repat,'][.\')
2713    let repat= '\<'.substitute(repat,'\*','\\(\\S\\+ \\)*\\S\\+','g').'\>'
2714    return repat
2715endfunction
2716
2717"  s:NetrwBookHistHandler: {{{2
2718"    0: (user: <mb>)   bookmark current directory
2719"    1: (user: <gb>)   change to the bookmarked path
2720"    2: (user: <qb>)   list bookmarks
2721"    3: (browsing)     records current directory history
2722"    4: (user: <u>)    go up   (previous) directory, using history
2723"    5: (user: <U>)    go down (next)     directory, using history
2724"    6: (user: <mB>)   delete bookmark
2725function s:NetrwBookHistHandler(chg,curdir)
2726    if !exists("g:netrw_dirhistmax") || g:netrw_dirhistmax <= 0
2727        return
2728    endif
2729
2730    let ykeep    = @@
2731    let curbufnr = bufnr("%")
2732
2733    if a:chg == 0
2734        " bookmark the current directory
2735        if exists("s:netrwmarkfilelist_{curbufnr}")
2736            call s:NetrwBookmark(0)
2737            echo "bookmarked marked files"
2738        else
2739            call s:MakeBookmark(a:curdir)
2740            echo "bookmarked the current directory"
2741        endif
2742
2743        try
2744            call s:NetrwBookHistSave()
2745        catch
2746        endtry
2747
2748    elseif a:chg == 1
2749        " change to bookmarked path
2750        if exists("g:netrw_bookmarklist") && !empty(g:netrw_bookmarklist)
2751            let len_bookmarklist = len(g:netrw_bookmarklist)
2752            let bookmark_num = v:count
2753
2754            " v:count value is set to zero if no count (prefix) is given to the `gb` map
2755            if bookmark_num == 0
2756                " list bookmarks and prompt for a bookmark number
2757                let goto_list = [" # | Goto Bookmark:"]
2758                let i = 0
2759                while i < len_bookmarklist
2760                    call add(goto_list, printf("%3d| %s", i + 1, g:netrw_bookmarklist[i]))
2761                    let i += 1
2762                endwhile
2763                let bookmark_num = inputlist(goto_list)
2764            endif
2765
2766            if bookmark_num > 0
2767                if bookmark_num <= len_bookmarklist
2768                    exe "NetrwKeepj e " . fnameescape(g:netrw_bookmarklist[bookmark_num - 1])
2769                else
2770                    echomsg "Sorry, bookmark#" . bookmark_num . " doesn't exist!"
2771                endif
2772            endif
2773            " Exit silently if user cancels with `q` or empty after inputlist()
2774        else
2775            echo "Bookmark list is empty."
2776        endif
2777
2778    elseif a:chg == 2
2779        "   redraw!
2780        let didwork= 0
2781        " list user's bookmarks
2782        if exists("g:netrw_bookmarklist")
2783            let cnt= 1
2784            for bmd in g:netrw_bookmarklist
2785                echo printf("Netrw Bookmark#%-2d: %s",cnt,g:netrw_bookmarklist[cnt-1])
2786                let didwork = 1
2787                let cnt     = cnt + 1
2788            endfor
2789        endif
2790
2791        " list directory history
2792        " Note: history is saved only when PerformListing is done;
2793        "       ie. when netrw can re-use a netrw buffer, the current directory is not saved in the history.
2794        let cnt     = g:netrw_dirhistcnt
2795        let first   = 1
2796        let histcnt = 0
2797        if g:netrw_dirhistmax > 0
2798            while ( first || cnt != g:netrw_dirhistcnt )
2799                if exists("g:netrw_dirhist_{cnt}")
2800                    echo printf("Netrw  History#%-2d: %s",histcnt,g:netrw_dirhist_{cnt})
2801                    let didwork= 1
2802                endif
2803                let histcnt = histcnt + 1
2804                let first   = 0
2805                let cnt     = ( cnt - 1 ) % g:netrw_dirhistmax
2806                if cnt < 0
2807                    let cnt= cnt + g:netrw_dirhistmax
2808                endif
2809            endwhile
2810        else
2811            let g:netrw_dirhistcnt= 0
2812        endif
2813        if didwork
2814            call inputsave()|call input("Press <cr> to continue")|call inputrestore()
2815        endif
2816
2817    elseif a:chg == 3
2818        " saves most recently visited directories (when they differ)
2819        if !exists("g:netrw_dirhistcnt") || !exists("g:netrw_dirhist_{g:netrw_dirhistcnt}") || g:netrw_dirhist_{g:netrw_dirhistcnt} != a:curdir
2820            if g:netrw_dirhistmax > 0
2821                let g:netrw_dirhistcnt                   = ( g:netrw_dirhistcnt + 1 ) % g:netrw_dirhistmax
2822                let g:netrw_dirhist_{g:netrw_dirhistcnt} = a:curdir
2823            endif
2824        endif
2825
2826    elseif a:chg == 4
2827        " u: change to the previous directory stored on the history list
2828        if g:netrw_dirhistmax > 0
2829            let g:netrw_dirhistcnt= ( g:netrw_dirhistcnt - v:count1 ) % g:netrw_dirhistmax
2830            if g:netrw_dirhistcnt < 0
2831                let g:netrw_dirhistcnt= g:netrw_dirhistcnt + g:netrw_dirhistmax
2832            endif
2833        else
2834            let g:netrw_dirhistcnt= 0
2835        endif
2836        if exists("g:netrw_dirhist_{g:netrw_dirhistcnt}")
2837            if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("b:netrw_curdir")
2838                setl ma noro
2839                sil! NetrwKeepj %d _
2840                setl nomod
2841            endif
2842            exe "NetrwKeepj e! ".fnameescape(g:netrw_dirhist_{g:netrw_dirhistcnt})
2843        else
2844            if g:netrw_dirhistmax > 0
2845                let g:netrw_dirhistcnt= ( g:netrw_dirhistcnt + v:count1 ) % g:netrw_dirhistmax
2846            else
2847                let g:netrw_dirhistcnt= 0
2848            endif
2849            echo "Sorry, no predecessor directory exists yet"
2850        endif
2851
2852    elseif a:chg == 5
2853        " U: change to the subsequent directory stored on the history list
2854        if g:netrw_dirhistmax > 0
2855            let g:netrw_dirhistcnt= ( g:netrw_dirhistcnt + 1 ) % g:netrw_dirhistmax
2856            if exists("g:netrw_dirhist_{g:netrw_dirhistcnt}")
2857                if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("b:netrw_curdir")
2858                    setl ma noro
2859                    sil! NetrwKeepj %d _
2860                    setl nomod
2861                endif
2862                exe "NetrwKeepj e! ".fnameescape(g:netrw_dirhist_{g:netrw_dirhistcnt})
2863            else
2864                let g:netrw_dirhistcnt= ( g:netrw_dirhistcnt - 1 ) % g:netrw_dirhistmax
2865                if g:netrw_dirhistcnt < 0
2866                    let g:netrw_dirhistcnt= g:netrw_dirhistcnt + g:netrw_dirhistmax
2867                endif
2868                echo "Sorry, no successor directory exists yet"
2869            endif
2870        else
2871            let g:netrw_dirhistcnt= 0
2872            echo "Sorry, no successor directory exists yet (g:netrw_dirhistmax is ".g:netrw_dirhistmax.")"
2873        endif
2874
2875    elseif a:chg == 6
2876        if exists("s:netrwmarkfilelist_{curbufnr}") && !empty(s:netrwmarkfilelist_{curbufnr})
2877            call s:NetrwBookmark(1)
2878            echo "removed marked files from bookmarks"
2879        elseif exists("g:netrw_bookmarklist") && !empty(g:netrw_bookmarklist)
2880            let len_bookmarklist = len(g:netrw_bookmarklist)
2881            let bookmark_num = v:count
2882
2883            " v:count value is set to zero if no count (prefix) is given to the `gb` map
2884            if bookmark_num == 0
2885                " list bookmarks and prompt for a bookmark number
2886                let goto_list = [" # | Delete Bookmark:"]
2887                let i = 0
2888                while i < len_bookmarklist
2889                    call add(goto_list, printf("%3d| %s", i + 1, g:netrw_bookmarklist[i]))
2890                    let i += 1
2891                endwhile
2892                let bookmark_num = inputlist(goto_list)
2893            endif
2894
2895            if bookmark_num > 0
2896                if bookmark_num <= len_bookmarklist
2897                    let bookmark_path = g:netrw_bookmarklist[bookmark_num - 1]
2898                    call s:MergeBookmarks()
2899                    NetrwKeepj call remove(g:netrw_bookmarklist, bookmark_num - 1)
2900                    echo "removed " . bookmark_path . " from g:netrw_bookmarklist."
2901                else
2902                    echomsg "Sorry, bookmark#" . bookmark_num . " doesn't exist!"
2903                endif
2904            endif
2905            " Exit silently if user cancels with `q` or empty after inputlist()
2906        else
2907            echo "Bookmark list is empty."
2908        endif
2909
2910        try
2911            call s:NetrwBookHistSave()
2912        catch
2913        endtry
2914    endif
2915    call s:NetrwBookmarkMenu()
2916    call s:NetrwTgtMenu()
2917    let @@= ykeep
2918endfunction
2919
2920" s:NetrwBookHistRead: this function reads bookmarks and history {{{2
2921"  Will source the history file (.netrwhist) only if the g:netrw_disthistmax is > 0.
2922"                      Sister function: s:NetrwBookHistSave()
2923function s:NetrwBookHistRead()
2924    if !exists("g:netrw_dirhistmax") || g:netrw_dirhistmax <= 0
2925        return
2926    endif
2927    let ykeep= @@
2928
2929    " read bookmarks
2930    if !exists("s:netrw_initbookhist")
2931        let home    = s:NetrwHome()
2932        let savefile= home."/.netrwbook"
2933        if filereadable(s:NetrwFile(savefile))
2934            exe "keepalt NetrwKeepj so ".savefile
2935        endif
2936
2937        " read history
2938        if g:netrw_dirhistmax > 0
2939            let savefile= home."/.netrwhist"
2940            if filereadable(s:NetrwFile(savefile))
2941                exe "keepalt NetrwKeepj so ".savefile
2942            endif
2943            let s:netrw_initbookhist= 1
2944            au VimLeave * call s:NetrwBookHistSave()
2945        endif
2946    endif
2947
2948    let @@= ykeep
2949endfunction
2950
2951" s:NetrwBookHistSave: this function saves bookmarks and history to files {{{2
2952"                      Sister function: s:NetrwBookHistRead()
2953"                      I used to do this via viminfo but that appears to
2954"                      be unreliable for long-term storage
2955"                      If g:netrw_dirhistmax is <= 0, no history or bookmarks
2956"                      will be saved.
2957"                      (s:NetrwBookHistHandler(3,...) used to record history)
2958function s:NetrwBookHistSave()
2959    if !exists("g:netrw_dirhistmax") || g:netrw_dirhistmax <= 0
2960        return
2961    endif
2962
2963    let savefile= s:NetrwHome()."/.netrwhist"
2964    1split
2965
2966    " setting up a new buffer which will become .netrwhist
2967    call s:NetrwEnew()
2968    if g:netrw_use_noswf
2969        setl cino= com= cpo-=a cpo-=A fo=nroql2 tw=0 report=10000 noswf
2970    else
2971        setl cino= com= cpo-=a cpo-=A fo=nroql2 tw=0 report=10000
2972    endif
2973    setl nocin noai noci magic nospell nohid wig= noaw
2974    setl ma noro write
2975    if exists("+acd") | setl noacd | endif
2976    sil! NetrwKeepj keepalt %d _
2977
2978    " rename enew'd file: .netrwhist -- no attempt to merge
2979    " record dirhistmax and current dirhistcnt
2980    " save history
2981    sil! keepalt file .netrwhist
2982    call setline(1,"let g:netrw_dirhistmax  =".g:netrw_dirhistmax)
2983    call setline(2,"let g:netrw_dirhistcnt =".g:netrw_dirhistcnt)
2984    if g:netrw_dirhistmax > 0
2985        let lastline = line("$")
2986        let cnt      = g:netrw_dirhistcnt
2987        let first    = 1
2988        while ( first || cnt != g:netrw_dirhistcnt )
2989            let lastline= lastline + 1
2990            if exists("g:netrw_dirhist_{cnt}")
2991                call setline(lastline,'let g:netrw_dirhist_'.cnt.'='.string(g:netrw_dirhist_{cnt}))
2992            endif
2993            let first   = 0
2994            let cnt     = ( cnt - 1 ) % g:netrw_dirhistmax
2995            if cnt < 0
2996                let cnt= cnt + g:netrw_dirhistmax
2997            endif
2998        endwhile
2999        exe "sil! w! ".savefile
3000    endif
3001
3002    " save bookmarks
3003    sil NetrwKeepj %d _
3004    if exists("g:netrw_bookmarklist") && g:netrw_bookmarklist != []
3005        " merge and write .netrwbook
3006        let savefile= s:NetrwHome()."/.netrwbook"
3007
3008        if filereadable(s:NetrwFile(savefile))
3009            let booklist= deepcopy(g:netrw_bookmarklist)
3010            exe "sil NetrwKeepj keepalt so ".savefile
3011            for bdm in booklist
3012                if index(g:netrw_bookmarklist,bdm) == -1
3013                    call add(g:netrw_bookmarklist,bdm)
3014                endif
3015            endfor
3016            call sort(g:netrw_bookmarklist)
3017        endif
3018
3019        " construct and save .netrwbook
3020        call setline(1,"let g:netrw_bookmarklist= ".string(g:netrw_bookmarklist))
3021        exe "sil! w! ".savefile
3022    endif
3023
3024    " cleanup -- remove buffer used to construct history
3025    let bgone= bufnr("%")
3026    q!
3027    exe "keepalt ".bgone."bwipe!"
3028
3029endfunction
3030
3031" s:NetrwBrowse: This function uses the command in g:netrw_list_cmd to provide a {{{2
3032"  list of the contents of a local or remote directory.  It is assumed that the
3033"  g:netrw_list_cmd has a string, USEPORT HOSTNAME, that needs to be substituted
3034"  with the requested remote hostname first.
3035"    Often called via:  Explore/e dirname/etc -> netrw#LocalBrowseCheck() -> s:NetrwBrowse()
3036function s:NetrwBrowse(islocal,dirname)
3037    if !exists("w:netrw_liststyle")|let w:netrw_liststyle= g:netrw_liststyle|endif
3038
3039    " save alternate-file's filename if w:netrw_rexlocal doesn't exist
3040    " This is useful when one edits a local file, then :e ., then :Rex
3041    if a:islocal && !exists("w:netrw_rexfile") && bufname("#") != ""
3042        let w:netrw_rexfile= bufname("#")
3043    endif
3044
3045    " s:NetrwBrowse : initialize history {{{3
3046    if !exists("s:netrw_initbookhist")
3047        NetrwKeepj call s:NetrwBookHistRead()
3048    endif
3049
3050    " s:NetrwBrowse : simplify the dirname (especially for ".."s in dirnames) {{{3
3051    if a:dirname !~ '^\a\{3,}://'
3052        let dirname= simplify(a:dirname)
3053    else
3054        let dirname= a:dirname
3055    endif
3056
3057    " repoint t:netrw_lexbufnr if appropriate
3058    if exists("t:netrw_lexbufnr") && bufnr("%") == t:netrw_lexbufnr
3059        let repointlexbufnr= 1
3060    endif
3061
3062    " s:NetrwBrowse : sanity checks: {{{3
3063    if exists("s:netrw_skipbrowse")
3064        unlet s:netrw_skipbrowse
3065        return
3066    endif
3067    if !exists("*shellescape")
3068        call netrw#msg#Notify('ERROR', "netrw can't run -- your vim is missing shellescape()")
3069        return
3070    endif
3071    if !exists("*fnameescape")
3072        call netrw#msg#Notify('ERROR', "netrw can't run -- your vim is missing fnameescape()")
3073        return
3074    endif
3075
3076    " s:NetrwBrowse : save options: {{{3
3077    call s:NetrwOptionsSave("w:")
3078
3079    " s:NetrwBrowse : re-instate any marked files {{{3
3080    if has("syntax") && exists("g:syntax_on") && g:syntax_on
3081        if exists("s:netrwmarkfilelist_{bufnr('%')}")
3082            exe "2match netrwMarkFile /".s:netrwmarkfilemtch_{bufnr("%")}."/"
3083        endif
3084    endif
3085
3086    if a:islocal && exists("w:netrw_acdkeep") && w:netrw_acdkeep
3087        " s:NetrwBrowse : set up "safe" options for local directory/file {{{3
3088        if s:NetrwLcd(dirname)
3089            return
3090        endif
3091
3092    elseif !a:islocal && dirname !~ '[\/]$' && dirname !~ '^"'
3093        " s:NetrwBrowse :  remote regular file handler {{{3
3094        if bufname(dirname) != ""
3095            exe "NetrwKeepj b ".fnameescape(bufname(dirname))
3096        else
3097            " attempt transfer of remote regular file
3098
3099            " remove any filetype indicator from end of dirname, except for the
3100            " "this is a directory" indicator (/).
3101            " There shouldn't be one of those here, anyway.
3102            let path= substitute(dirname,'[*=@|]\r\=$','','e')
3103            call s:RemotePathAnalysis(dirname)
3104
3105            " s:NetrwBrowse : remote-read the requested file into current buffer {{{3
3106            call s:NetrwEnew(dirname)
3107            call s:NetrwOptionsSafe(a:islocal)
3108            setl ma noro
3109            let b:netrw_curdir = dirname
3110            let url            = s:method."://".((s:user == "")? "" : s:user."@").s:machine.(s:port ? ":".s:port : "")."/".s:path
3111            call s:NetrwBufRename(url)
3112            exe "sil! NetrwKeepj keepalt doau BufReadPre ".fnameescape(s:fname)
3113            sil call netrw#NetRead(2,url)
3114            " netrw.vim and tar.vim have already handled decompression of the tarball; avoiding gzip.vim error
3115            if s:path =~ '\.bz2$'
3116                exe "sil NetrwKeepj keepalt doau BufReadPost ".fnameescape(substitute(s:fname,'\.bz2$','',''))
3117            elseif s:path =~ '\.gz$'
3118                exe "sil NetrwKeepj keepalt doau BufReadPost ".fnameescape(substitute(s:fname,'\.gz$','',''))
3119            elseif s:path =~ '\.xz$'
3120                exe "sil NetrwKeepj keepalt doau BufReadPost ".fnameescape(substitute(s:fname,'\.xz$','',''))
3121            else
3122                exe "sil NetrwKeepj keepalt doau BufReadPost ".fnameescape(s:fname)
3123            endif
3124        endif
3125
3126        " s:NetrwBrowse : save certain window-oriented variables into buffer-oriented variables {{{3
3127        call s:SetBufWinVars()
3128        call s:NetrwOptionsRestore("w:")
3129        setl ma nomod noro
3130        return
3131    endif
3132
3133    " use buffer-oriented WinVars if buffer variables exist but associated window variables don't {{{3
3134    call s:UseBufWinVars()
3135
3136    " set up some variables {{{3
3137    let b:netrw_browser_active = 1
3138    let dirname                = dirname
3139    let s:last_sort_by         = g:netrw_sort_by
3140
3141    " set up menu {{{3
3142    NetrwKeepj call s:NetrwMenu(1)
3143
3144    " get/set-up buffer {{{3
3145    let svpos  = winsaveview()
3146
3147    " NetrwGetBuffer might change buffers but s:rexposn_X was set for the
3148    " previous buffer
3149    let prevbufnr = bufnr('%')
3150    let reusing= s:NetrwGetBuffer(a:islocal,dirname)
3151    if exists("s:rexposn_".prevbufnr) && exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3152        let s:rexposn_{bufnr('%')} = s:rexposn_{prevbufnr}
3153    endif
3154
3155    " maintain markfile highlighting
3156    if has("syntax") && exists("g:syntax_on") && g:syntax_on
3157        if exists("s:netrwmarkfilemtch_{bufnr('%')}") && s:netrwmarkfilemtch_{bufnr("%")} != ""
3158            exe "2match netrwMarkFile /".s:netrwmarkfilemtch_{bufnr("%")}."/"
3159        else
3160            2match none
3161        endif
3162    endif
3163    if reusing && line("$") > 1
3164        call s:NetrwOptionsRestore("w:")
3165        setl noma nomod nowrap
3166        return
3167    endif
3168
3169    " set b:netrw_curdir to the new directory name {{{3
3170    let b:netrw_curdir= dirname
3171    if b:netrw_curdir =~ '[/\\]$'
3172        let b:netrw_curdir= substitute(b:netrw_curdir,'[/\\]$','','e')
3173    endif
3174    if b:netrw_curdir =~ '\a:$' && has("win32")
3175        let b:netrw_curdir= b:netrw_curdir."/"
3176    endif
3177    if b:netrw_curdir == ''
3178        if has("amiga")
3179            " On the Amiga, the empty string connotes the current directory
3180            let b:netrw_curdir= getcwd()
3181        else
3182            " under unix, when the root directory is encountered, the result
3183            " from the preceding substitute is an empty string.
3184            let b:netrw_curdir= '/'
3185        endif
3186    endif
3187    if !a:islocal && b:netrw_curdir !~ '/$'
3188        let b:netrw_curdir= b:netrw_curdir.'/'
3189    endif
3190
3191    " ------------
3192    " (local only) {{{3
3193    " ------------
3194    if a:islocal
3195        " Set up ShellCmdPost handling.  Append current buffer to browselist
3196        call s:LocalFastBrowser()
3197
3198        " handle g:netrw_keepdir: set vim's current directory to netrw's notion of the current directory {{{3
3199        if !g:netrw_keepdir
3200            if !exists("&l:acd") || !&l:acd
3201                if s:NetrwLcd(b:netrw_curdir)
3202                    return
3203                endif
3204            endif
3205        endif
3206
3207    " --------------------------------
3208    " remote handling: {{{3
3209    " --------------------------------
3210    else
3211
3212        " analyze dirname and g:netrw_list_cmd {{{3
3213        if dirname =~# "^NetrwTreeListing\>"
3214            let dirname= b:netrw_curdir
3215        elseif exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("b:netrw_curdir")
3216            let dirname= substitute(b:netrw_curdir,'\\','/','g')
3217            if dirname !~ '/$'
3218                let dirname= dirname.'/'
3219            endif
3220            let b:netrw_curdir = dirname
3221        else
3222            let dirname = substitute(dirname,'\\','/','g')
3223        endif
3224
3225        let dirpat  = '^\(\w\{-}\)://\(\w\+@\)\=\([^/]\+\)/\(.*\)$'
3226        if dirname !~ dirpat
3227            call netrw#msg#Notify('ERROR', printf("netrw doesn't understand your dirname<%s>", dirname))
3228            NetrwKeepj call s:NetrwOptionsRestore("w:")
3229            setl noma nomod nowrap
3230            return
3231        endif
3232        let b:netrw_curdir= dirname
3233    endif  " (additional remote handling)
3234
3235    " -------------------------------
3236    " Perform Directory Listing: {{{3
3237    " -------------------------------
3238    NetrwKeepj call s:NetrwMaps(a:islocal)
3239    NetrwKeepj call s:NetrwCommands(a:islocal)
3240    NetrwKeepj call s:PerformListing(a:islocal)
3241
3242    " restore option(s)
3243    call s:NetrwOptionsRestore("w:")
3244
3245    " If there is a rexposn: restore position with rexposn
3246    " Otherwise            : set rexposn
3247    if exists("s:rexposn_".bufnr("%"))
3248        NetrwKeepj call winrestview(s:rexposn_{bufnr('%')})
3249        if exists("w:netrw_bannercnt") && line(".") < w:netrw_bannercnt
3250            NetrwKeepj exe w:netrw_bannercnt
3251        endif
3252    else
3253        NetrwKeepj call s:SetRexDir(a:islocal,b:netrw_curdir)
3254    endif
3255
3256    " repoint t:netrw_lexbufnr if appropriate
3257    if exists("repointlexbufnr")
3258        let t:netrw_lexbufnr= bufnr("%")
3259    endif
3260
3261    " restore position
3262    if reusing
3263        call winrestview(svpos)
3264    endif
3265
3266    " The s:LocalBrowseRefresh() function is called by an autocmd
3267    " installed by s:LocalFastBrowser() when g:netrw_fastbrowse <= 1 (ie. slow or medium speed).
3268    " However, s:NetrwBrowse() causes the FocusGained event to fire the first time.
3269    return
3270endfunction
3271
3272" s:NetrwFile: because of g:netrw_keepdir, isdirectory(), type(), etc may or {{{2
3273" may not apply correctly; ie. netrw's idea of the current directory may
3274" differ from vim's.  This function insures that netrw's idea of the current
3275" directory is used.
3276" Returns a path to the file specified by a:fname
3277function s:NetrwFile(fname)
3278
3279    " clean up any leading treedepthstring
3280    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3281        let fname= substitute(a:fname,'^'.s:treedepthstring.'\+','','')
3282    else
3283        let fname= a:fname
3284    endif
3285
3286    if g:netrw_keepdir
3287        " vim's idea of the current directory possibly may differ from netrw's
3288        if !exists("b:netrw_curdir")
3289            let b:netrw_curdir= getcwd()
3290        endif
3291
3292        if !g:netrw_cygwin && has("win32")
3293            if isabsolutepath(fname)
3294                " windows, but full path given
3295                let ret= fname
3296            else
3297                " windows, relative path given
3298                let ret= netrw#fs#ComposePath(b:netrw_curdir,fname)
3299            endif
3300
3301        elseif fname =~ '^/'
3302            " not windows, full path given
3303            let ret= fname
3304        else
3305            " not windows, relative path given
3306            let ret= netrw#fs#ComposePath(b:netrw_curdir,fname)
3307        endif
3308    else
3309        " vim and netrw agree on the current directory
3310        let ret= fname
3311    endif
3312
3313    return ret
3314endfunction
3315
3316" s:NetrwFileInfo: supports qf (query for file information) {{{2
3317function s:NetrwFileInfo(islocal,fname)
3318    let ykeep= @@
3319    if a:islocal
3320        let lsopt= "-lsad"
3321        if g:netrw_sizestyle =~# 'H'
3322            let lsopt= "-lsadh"
3323        elseif g:netrw_sizestyle =~# 'h'
3324            let lsopt= "-lsadh --si"
3325        endif
3326        if (has("unix") || has("macunix")) && executable("/bin/ls")
3327
3328            if getline(".") == "../"
3329                echo system("/bin/ls ".lsopt." ".netrw#os#Escape(".."))
3330
3331            elseif w:netrw_liststyle == s:TREELIST && getline(".") !~ '^'.s:treedepthstring
3332                echo system("/bin/ls ".lsopt." ".netrw#os#Escape(b:netrw_curdir))
3333
3334            elseif exists("b:netrw_curdir")
3335                echo system("/bin/ls ".lsopt." ".netrw#os#Escape(netrw#fs#ComposePath(b:netrw_curdir,a:fname)))
3336
3337            else
3338                echo system("/bin/ls ".lsopt." ".netrw#os#Escape(s:NetrwFile(a:fname)))
3339            endif
3340        else
3341            " use vim functions to return information about file below cursor
3342            if !isdirectory(s:NetrwFile(a:fname)) && !filereadable(s:NetrwFile(a:fname)) && a:fname =~ '[*@/]'
3343                let fname= substitute(a:fname,".$","","")
3344            else
3345                let fname= a:fname
3346            endif
3347            let t  = getftime(s:NetrwFile(fname))
3348            let sz = getfsize(s:NetrwFile(fname))
3349            if g:netrw_sizestyle =~# "[hH]"
3350                let sz= s:NetrwHumanReadable(sz)
3351            endif
3352            echo a:fname.":  ".sz."  ".strftime(g:netrw_timefmt,getftime(s:NetrwFile(fname)))
3353        endif
3354    else
3355        echo "sorry, \"qf\" not supported yet for remote files"
3356    endif
3357    let @@= ykeep
3358endfunction
3359
3360" s:NetrwGetBuffer: [get a new|find an old netrw] buffer for a netrw listing {{{2
3361"   returns 0=cleared buffer
3362"           1=re-used buffer (buffer not cleared)
3363"  Nov 09, 2020: tst952 shows that when user does :set hidden that NetrwGetBuffer will come up with a [No Name] buffer (hid fix)
3364function s:NetrwGetBuffer(islocal,dirname)
3365    let dirname= a:dirname
3366
3367    " re-use buffer if possible {{{3
3368    if !exists("s:netrwbuf")
3369        let s:netrwbuf= {}
3370    endif
3371
3372    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3373        let bufnum = -1
3374
3375        if !empty(s:netrwbuf) && has_key(s:netrwbuf,netrw#fs#AbsPath(dirname))
3376            if has_key(s:netrwbuf,"NetrwTreeListing")
3377                let bufnum= s:netrwbuf["NetrwTreeListing"]
3378            else
3379                let bufnum= s:netrwbuf[netrw#fs#AbsPath(dirname)]
3380            endif
3381            if !bufexists(bufnum)
3382                call remove(s:netrwbuf,"NetrwTreeListing")
3383                let bufnum= -1
3384            endif
3385        elseif bufnr("NetrwTreeListing") != -1
3386            let bufnum= bufnr("NetrwTreeListing")
3387        else
3388            let bufnum= -1
3389        endif
3390
3391    elseif has_key(s:netrwbuf,netrw#fs#AbsPath(dirname))
3392        let bufnum= s:netrwbuf[netrw#fs#AbsPath(dirname)]
3393        if !bufexists(bufnum)
3394            call remove(s:netrwbuf,netrw#fs#AbsPath(dirname))
3395            let bufnum= -1
3396        endif
3397
3398    else
3399        let bufnum= -1
3400    endif
3401
3402    " highjack the current buffer
3403    "   IF the buffer already has the desired name
3404    "   AND it is empty
3405    let curbuf = bufname("%")
3406    if curbuf == '.'
3407        let curbuf = getcwd()
3408    endif
3409    if dirname == curbuf && line("$") == 1 && getline("%") == ""
3410        return 0
3411    else  " DEBUG
3412    endif
3413    " Aug 14, 2021: was thinking about looking for a [No Name] buffer here and using it, but that might cause problems
3414
3415    " get enew buffer and name it -or- re-use buffer {{{3
3416    if bufnum < 0      " get enew buffer and name it
3417        call s:NetrwEnew(dirname)
3418        " name the buffer
3419        if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3420            " Got enew buffer; transform into a NetrwTreeListing
3421            let w:netrw_treebufnr = bufnr("%")
3422            call s:NetrwBufRename("NetrwTreeListing")
3423            if g:netrw_use_noswf
3424                setl nobl bt=nofile noswf
3425            else
3426                setl nobl bt=nofile
3427            endif
3428            nnoremap <silent> <buffer> [[       :sil call <SID>TreeListMove('[[')<cr>
3429            nnoremap <silent> <buffer> ]]       :sil call <SID>TreeListMove(']]')<cr>
3430            nnoremap <silent> <buffer> []       :sil call <SID>TreeListMove('[]')<cr>
3431            nnoremap <silent> <buffer> ][       :sil call <SID>TreeListMove('][')<cr>
3432        else
3433            call s:NetrwBufRename(dirname)
3434            " enter the new buffer into the s:netrwbuf dictionary
3435            let s:netrwbuf[netrw#fs#AbsPath(dirname)]= bufnr("%")
3436        endif
3437
3438    else " Re-use the buffer
3439        " ignore all events
3440        let eikeep= &ei
3441        setl ei=all
3442
3443        if &ft == "netrw"
3444            exe "sil! NetrwKeepj noswapfile b ".bufnum
3445        else
3446            call s:NetrwEditBuf(bufnum)
3447        endif
3448        if bufname("%") == '.'
3449            call s:NetrwBufRename(getcwd())
3450        endif
3451
3452        " restore ei
3453        let &ei= eikeep
3454
3455        if line("$") <= 1 && getline(1) == ""
3456            " empty buffer
3457            NetrwKeepj call s:NetrwListSettings(a:islocal)
3458            return 0
3459
3460        elseif g:netrw_fastbrowse == 0 || (a:islocal && g:netrw_fastbrowse == 1)
3461            NetrwKeepj call s:NetrwListSettings(a:islocal)
3462            sil NetrwKeepj %d _
3463            return 0
3464
3465        elseif exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3466            setl ma
3467            sil NetrwKeepj %d _
3468            NetrwKeepj call s:NetrwListSettings(a:islocal)
3469            return 0
3470
3471        else
3472            return 1
3473        endif
3474    endif
3475
3476    " do netrw settings: make this buffer not-a-file, modifiable, not line-numbered, etc {{{3
3477    "     fastbrowse  Local  Remote   Hiding a buffer implies it may be re-used (fast)
3478    "  slow   0         D      D      Deleting a buffer implies it will not be re-used (slow)
3479    "  med    1         D      H
3480    "  fast   2         H      H
3481    let fname= expand("%")
3482    NetrwKeepj call s:NetrwListSettings(a:islocal)
3483    call s:NetrwBufRename(fname)
3484
3485    " delete all lines from buffer {{{3
3486    sil! keepalt NetrwKeepj %d _
3487
3488    return 0
3489endfunction
3490
3491"  s:NetrwGetWord: it gets the directory/file named under the cursor {{{2
3492function s:NetrwGetWord()
3493    let keepsol= &l:sol
3494    setl nosol
3495
3496    call s:UseBufWinVars()
3497
3498    " insure that w:netrw_liststyle is set up
3499    if !exists("w:netrw_liststyle")
3500        if exists("g:netrw_liststyle")
3501            let w:netrw_liststyle= g:netrw_liststyle
3502        else
3503            let w:netrw_liststyle= s:THINLIST
3504        endif
3505    endif
3506
3507    if exists("w:netrw_bannercnt") && line(".") < w:netrw_bannercnt
3508        " Active Banner support
3509        NetrwKeepj norm! 0
3510        let dirname= "./"
3511        let curline= getline('.')
3512
3513        if curline =~# '"\s*Sorted by\s'
3514            NetrwKeepj norm! "_s
3515            let s:netrw_skipbrowse= 1
3516            echo 'Pressing "s" also works'
3517
3518        elseif curline =~# '"\s*Sort sequence:'
3519            let s:netrw_skipbrowse= 1
3520            echo 'Press "S" to edit sorting sequence'
3521
3522        elseif curline =~# '"\s*Quick Help:'
3523            NetrwKeepj norm! ?
3524            let s:netrw_skipbrowse= 1
3525
3526        elseif curline =~# '"\s*\%(Hiding\|Showing\):'
3527            NetrwKeepj norm! a
3528            let s:netrw_skipbrowse= 1
3529            echo 'Pressing "a" also works'
3530
3531        elseif line("$") > w:netrw_bannercnt
3532            exe 'sil NetrwKeepj '.w:netrw_bannercnt
3533        endif
3534
3535    elseif w:netrw_liststyle == s:THINLIST
3536        NetrwKeepj norm! 0
3537        let dirname= substitute(getline('.'),'\t -->.*$','','')
3538
3539    elseif w:netrw_liststyle == s:LONGLIST
3540        NetrwKeepj norm! 0
3541        let dirname= substitute(getline('.'),'^\(\%(\S\+ \)*\S\+\).\{-}$','\1','e')
3542
3543    elseif exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3544        let dirname= substitute(getline('.'),'^\('.s:treedepthstring.'\)*','','e')
3545        let dirname= substitute(dirname,'\t -->.*$','','')
3546
3547    else
3548        let dirname= getline('.')
3549
3550        if !exists("b:netrw_cpf")
3551            let b:netrw_cpf= 0
3552            exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$g/^./if virtcol("$") > b:netrw_cpf|let b:netrw_cpf= virtcol("$")|endif'
3553            call histdel("/",-1)
3554        endif
3555
3556        let filestart = (virtcol(".")/b:netrw_cpf)*b:netrw_cpf
3557        if filestart == 0
3558            NetrwKeepj norm! 0ma
3559        else
3560            call cursor(line("."),filestart+1)
3561            NetrwKeepj norm! ma
3562        endif
3563
3564        let dict={}
3565        " save the unnamed register and register 0-9 and a
3566        let dict.a=[getreg('a'), getregtype('a')]
3567        for i in range(0, 9)
3568            let dict[i] = [getreg(i), getregtype(i)]
3569        endfor
3570        let dict.unnamed = [getreg(''), getregtype('')]
3571
3572        let eofname= filestart + b:netrw_cpf + 1
3573        if eofname <= col("$")
3574            call cursor(line("."),filestart+b:netrw_cpf+1)
3575            NetrwKeepj norm! "ay`a
3576        else
3577            NetrwKeepj norm! "ay$
3578        endif
3579
3580        let dirname = @a
3581        call s:RestoreRegister(dict)
3582
3583        let dirname= substitute(dirname,'\s\+$','','e')
3584    endif
3585
3586    " symlinks are indicated by a trailing "@".  Remove it before further processing.
3587    let dirname= substitute(dirname,"@$","","")
3588
3589    " executables are indicated by a trailing "*".  Remove it before further processing.
3590    let dirname= substitute(dirname,"\*$","","")
3591
3592    let &l:sol= keepsol
3593
3594    return dirname
3595endfunction
3596
3597" s:NetrwListSettings: make standard settings for making a netrw listing {{{2
3598"                      g:netrw_bufsettings will be used after the listing is produced.
3599"                      Called by s:NetrwGetBuffer()
3600function s:NetrwListSettings(islocal)
3601    let fname= bufname("%")
3602    "              nobl noma nomod nonu noma nowrap ro   nornu  (std g:netrw_bufsettings)
3603    setl bt=nofile nobl ma         nonu      nowrap noro nornu
3604    call s:NetrwBufRename(fname)
3605    if g:netrw_use_noswf
3606        setl noswf
3607    endif
3608    exe "setl ts=".(g:netrw_maxfilenamelen+1)
3609    setl isk+=.,~,-
3610    if g:netrw_fastbrowse > a:islocal
3611        setl bh=hide
3612    else
3613        setl bh=delete
3614    endif
3615endfunction
3616
3617"  s:NetrwListStyle: change list style (thin - long - wide - tree) {{{2
3618"  islocal=0: remote browsing
3619"         =1: local browsing
3620function s:NetrwListStyle(islocal)
3621    let ykeep             = @@
3622    let fname             = s:NetrwGetWord()
3623    if !exists("w:netrw_liststyle")|let w:netrw_liststyle= g:netrw_liststyle|endif
3624    let svpos            = winsaveview()
3625    let w:netrw_liststyle = (w:netrw_liststyle + 1) % s:MAXLIST
3626
3627    " repoint t:netrw_lexbufnr if appropriate
3628    if exists("t:netrw_lexbufnr") && bufnr("%") == t:netrw_lexbufnr
3629        let repointlexbufnr= 1
3630    endif
3631
3632    if w:netrw_liststyle == s:THINLIST
3633        " use one column listing
3634        let g:netrw_list_cmd = substitute(g:netrw_list_cmd,' -l','','ge')
3635
3636    elseif w:netrw_liststyle == s:LONGLIST
3637        " use long list
3638        let g:netrw_list_cmd = g:netrw_list_cmd." -l"
3639
3640    elseif w:netrw_liststyle == s:WIDELIST
3641        " give wide list
3642        let g:netrw_list_cmd = substitute(g:netrw_list_cmd,' -l','','ge')
3643
3644    elseif exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
3645        let g:netrw_list_cmd = substitute(g:netrw_list_cmd,' -l','','ge')
3646
3647    else
3648        call netrw#msg#Notify('WARNING', printf('bad value for g:netrw_liststyle (=%s)', w:netrw_liststyle))
3649        let g:netrw_liststyle = s:THINLIST
3650        let w:netrw_liststyle = g:netrw_liststyle
3651        let g:netrw_list_cmd  = substitute(g:netrw_list_cmd,' -l','','ge')
3652    endif
3653    setl ma noro
3654
3655    " clear buffer - this will cause NetrwBrowse/LocalBrowseCheck to do a refresh
3656    sil! NetrwKeepj %d _
3657    " following prevents tree listing buffer from being marked "modified"
3658    setl nomod
3659
3660    " refresh the listing
3661    NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
3662    NetrwKeepj call s:NetrwCursor(0)
3663
3664    " repoint t:netrw_lexbufnr if appropriate
3665    if exists("repointlexbufnr")
3666        let t:netrw_lexbufnr= bufnr("%")
3667    endif
3668
3669    " restore position; keep cursor on the filename
3670    NetrwKeepj call winrestview(svpos)
3671    let @@= ykeep
3672
3673endfunction
3674
3675" s:NetrwBannerCtrl: toggles the display of the banner {{{2
3676function s:NetrwBannerCtrl(islocal)
3677    let ykeep= @@
3678    " toggle the banner (enable/suppress)
3679    let g:netrw_banner= !g:netrw_banner
3680
3681    " refresh the listing
3682    let svpos= winsaveview()
3683    call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
3684
3685    " keep cursor on the filename
3686    if g:netrw_banner && exists("w:netrw_bannercnt") && line(".") >= w:netrw_bannercnt
3687        let fname= s:NetrwGetWord()
3688        sil NetrwKeepj $
3689        let result= search('\%(^\%(|\+\s\)\=\|\s\{2,}\)\zs'.escape(fname,'.\[]*$^').'\%(\s\{2,}\|$\)','bc')
3690        if result <= 0 && exists("w:netrw_bannercnt")
3691            exe "NetrwKeepj ".w:netrw_bannercnt
3692        endif
3693    endif
3694    let @@= ykeep
3695endfunction
3696
3697" s:NetrwBookmark: supports :NetrwMB[!] [file]s                 {{{2
3698"
3699"  No bang: enters files/directories into Netrw's bookmark system
3700"   No argument and in netrw buffer:
3701"     if there are marked files: bookmark marked files
3702"     otherwise                : bookmark file/directory under cursor
3703"   No argument and not in netrw buffer: bookmarks current open file
3704"   Has arguments: globs them individually and bookmarks them
3705"
3706"  With bang: deletes files/directories from Netrw's bookmark system
3707function s:NetrwBookmark(del,...)
3708    if a:0 == 0
3709        if &ft == "netrw"
3710            let curbufnr = bufnr("%")
3711
3712            if exists("s:netrwmarkfilelist_{curbufnr}")
3713                " for every filename in the marked list
3714                let svpos  = winsaveview()
3715                let islocal= expand("%") !~ '^\a\{3,}://'
3716                for fname in s:netrwmarkfilelist_{curbufnr}
3717                    if a:del|call s:DeleteBookmark(fname)|else|call s:MakeBookmark(fname)|endif
3718                endfor
3719                let curdir  = exists("b:netrw_curdir")? b:netrw_curdir : getcwd()
3720                call s:NetrwUnmarkList(curbufnr,curdir)
3721                NetrwKeepj call s:NetrwRefresh(islocal,s:NetrwBrowseChgDir(islocal,'./',0))
3722                NetrwKeepj call winrestview(svpos)
3723            else
3724                let fname= s:NetrwGetWord()
3725                if a:del|call s:DeleteBookmark(fname)|else|call s:MakeBookmark(fname)|endif
3726            endif
3727
3728        else
3729            " bookmark currently open file
3730            let fname= expand("%")
3731            if a:del|call s:DeleteBookmark(fname)|else|call s:MakeBookmark(fname)|endif
3732        endif
3733
3734    else
3735        " bookmark specified files
3736        "  attempts to infer if working remote or local
3737        "  by deciding if the current file begins with an url
3738        "  Globbing cannot be done remotely.
3739        let islocal= expand("%") !~ '^\a\{3,}://'
3740        let i = 1
3741        while i <= a:0
3742            if islocal
3743                let mbfiles = glob(fnameescape(a:{i}), 0, 1, 1)
3744            else
3745                let mbfiles = [a:{i}]
3746            endif
3747            for mbfile in mbfiles
3748                if a:del
3749                    call s:DeleteBookmark(mbfile)
3750                else
3751                    call s:MakeBookmark(mbfile)
3752                endif
3753            endfor
3754            let i= i + 1
3755        endwhile
3756    endif
3757
3758    " update the menu
3759    call s:NetrwBookmarkMenu()
3760endfunction
3761
3762" s:NetrwBookmarkMenu: Uses menu priorities {{{2
3763"                      .2.[cnt] for bookmarks, and
3764"                      .3.[cnt] for history
3765"                      (see s:NetrwMenu())
3766function s:NetrwBookmarkMenu()
3767    if !exists("s:netrw_menucnt")
3768        return
3769    endif
3770
3771    " the following test assures that gvim is running, has menus available, and has menus enabled.
3772    if has("gui") && has("menu") && has("gui_running") && &go =~# 'm' && g:netrw_menu
3773        if exists("g:NetrwTopLvlMenu")
3774            exe 'sil! unmenu '.g:NetrwTopLvlMenu.'Bookmarks'
3775            exe 'sil! unmenu '.g:NetrwTopLvlMenu.'Bookmarks\ and\ History.Bookmark\ Delete'
3776        endif
3777        if !exists("s:netrw_initbookhist")
3778            call s:NetrwBookHistRead()
3779        endif
3780
3781        " show bookmarked places
3782        if exists("g:netrw_bookmarklist") && g:netrw_bookmarklist != [] && g:netrw_dirhistmax > 0
3783            let cnt= 1
3784            for bmd in g:netrw_bookmarklist
3785                let ebmd= escape(bmd,g:netrw_menu_escape)
3786                let fbmd= escape(fnameescape(bmd),'|')
3787
3788                " show bookmarks for goto menu
3789                exe 'sil! menu '.g:NetrwMenuPriority.".2.".cnt." ".g:NetrwTopLvlMenu.'Bookmarks.'.ebmd.'    :e '.fbmd."\<cr>"
3790
3791                " show bookmarks for deletion menu
3792                exe 'sil! menu '.g:NetrwMenuPriority.".8.2.".cnt." ".g:NetrwTopLvlMenu.'Bookmarks\ and\ History.Bookmark\ Delete.'.ebmd.'   '.cnt."mB"
3793                let cnt= cnt + 1
3794            endfor
3795
3796        endif
3797
3798        " show directory browsing history
3799        if g:netrw_dirhistmax > 0
3800            let cnt     = g:netrw_dirhistcnt
3801            let first   = 1
3802            let histcnt = 0
3803            while ( first || cnt != g:netrw_dirhistcnt )
3804                let histcnt  = histcnt + 1
3805                let priority = g:netrw_dirhistcnt + histcnt
3806                if exists("g:netrw_dirhist_{cnt}")
3807                    let histdir= escape(g:netrw_dirhist_{cnt},g:netrw_menu_escape)
3808                    let ehistdir= escape(fnameescape(g:netrw_dirhist_{cnt}),'|')
3809                    exe 'sil! menu '.g:NetrwMenuPriority.".3.".priority." ".g:NetrwTopLvlMenu.'History.'.histdir.'    :e '.ehistdir."\<cr>"
3810                endif
3811                let first = 0
3812                let cnt   = ( cnt - 1 ) % g:netrw_dirhistmax
3813                if cnt < 0
3814                    let cnt= cnt + g:netrw_dirhistmax
3815                endif
3816            endwhile
3817        endif
3818
3819    endif
3820endfunction
3821
3822"  s:NetrwBrowseChgDir: constructs a new directory based on the current {{{2
3823"                       directory and a new directory name.  Also, if the
3824"                       "new directory name" is actually a file,
3825"                       NetrwBrowseChgDir() edits the file.
3826"    cursor=0: newdir is relative to b:netrw_curdir
3827"          =1: newdir is relative to the path to the word under the cursor in
3828"              tree view
3829function s:NetrwBrowseChgDir(islocal, newdir, cursor, ...)
3830    let ykeep= @@
3831    if !exists("b:netrw_curdir")
3832        let @@= ykeep
3833        return
3834    endif
3835
3836    " NetrwBrowseChgDir; save options and initialize {{{3
3837    call s:SavePosn(s:netrw_posn)
3838    NetrwKeepj call s:NetrwOptionsSave("s:")
3839    NetrwKeepj call s:NetrwOptionsSafe(a:islocal)
3840
3841    let newdir = a:newdir
3842    let dirname = b:netrw_curdir
3843
3844    if a:cursor && w:netrw_liststyle == s:TREELIST
3845        " dirname is the path to the word under the cursor
3846        let dirname = s:NetrwTreePath(w:netrw_treetop)
3847        " If the word under the cursor is a directory (except for ../), NetrwTreePath
3848        " returns the full path, including the word under the cursor, remove it
3849        if newdir != "../"
3850            let dirname = fnamemodify(dirname, ":h")
3851        endif
3852    endif
3853
3854    if has("win32")
3855        let dirname = substitute(dirname, '\\', '/', 'ge')
3856    endif
3857
3858    let dolockout = 0
3859    let dorestore = 1
3860
3861    " ignore <cr>s when done in the banner
3862    if g:netrw_banner
3863        if exists("w:netrw_bannercnt") && line(".") < w:netrw_bannercnt && line("$") >= w:netrw_bannercnt
3864            if getline(".") =~# 'Quick Help'
3865                let g:netrw_quickhelp= (g:netrw_quickhelp + 1)%len(s:QuickHelp)
3866                setl ma noro nowrap
3867                NetrwKeepj call setline(line('.'),'"   Quick Help: <F1>:help  '.s:QuickHelp[g:netrw_quickhelp])
3868                setl noma nomod nowrap
3869                NetrwKeepj call s:NetrwOptionsRestore("s:")
3870            endif
3871        endif
3872    endif
3873
3874    " set up o/s-dependent directory recognition pattern
3875    let dirpat = has("amiga") || has('win32') ? '[\/:]$' : '/$'
3876
3877    if newdir !~ dirpat && !(a:islocal && isdirectory(s:NetrwFile(netrw#fs#ComposePath(dirname, newdir))))
3878        " ------------------------------
3879        " NetrwBrowseChgDir: edit a file {{{3
3880        " ------------------------------
3881
3882        " save position for benefit of Rexplore
3883        let s:rexposn_{bufnr("%")}= winsaveview()
3884
3885        let dirname = isabsolutepath(newdir)
3886                    \ ? netrw#fs#AbsPath(newdir)
3887                    \ : netrw#fs#ComposePath(dirname, newdir)
3888
3889        " this lets netrw#BrowseX avoid the edit
3890        if a:0 < 1
3891            NetrwKeepj call s:NetrwOptionsRestore("s:")
3892            let curdir= b:netrw_curdir
3893            if !exists("s:didsplit")
3894                if type(g:netrw_browse_split) == 3
3895                    " open file in server
3896                    " Note that g:netrw_browse_split is a List: [servername,tabnr,winnr]
3897                    call s:NetrwServerEdit(a:islocal,dirname)
3898                    return
3899
3900                elseif g:netrw_browse_split == 1
3901                    " horizontally splitting the window first
3902                    let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winheight(0))/100 : -g:netrw_winsize
3903                    exe "keepalt ".(g:netrw_alto? "bel " : "abo ").winsz."wincmd s"
3904                    if !&ea
3905                        keepalt wincmd _
3906                    else
3907                        exe "keepalt wincmd ="
3908                    endif
3909                    call s:SetRexDir(a:islocal,curdir)
3910
3911                elseif g:netrw_browse_split == 2
3912                    " vertically splitting the window first
3913                    let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize
3914                    exe "keepalt ".(g:netrw_alto? "top " : "bot ")."vert ".winsz."wincmd s"
3915                    if !&ea
3916                        keepalt wincmd |
3917                    else
3918                        exe "keepalt wincmd ="
3919                    endif
3920                    call s:SetRexDir(a:islocal,curdir)
3921
3922                elseif g:netrw_browse_split == 3
3923                    " open file in new tab
3924                    keepalt tabnew
3925                    if !exists("b:netrw_curdir")
3926                        let b:netrw_curdir= getcwd()
3927                    endif
3928                    call s:SetRexDir(a:islocal,curdir)
3929
3930                elseif g:netrw_browse_split == 4
3931                    " act like "P" (ie. open previous window)
3932                    if s:NetrwPrevWinOpen(2) == 3
3933                        let @@= ykeep
3934                        return
3935                    endif
3936                    call s:SetRexDir(a:islocal,curdir)
3937
3938                else
3939                    " handling a file, didn't split, so remove menu
3940                    call s:NetrwMenu(0)
3941                    " optional change to window
3942                    if g:netrw_chgwin >= 1
3943                        if winnr("$")+1 == g:netrw_chgwin
3944                            " if g:netrw_chgwin is set to one more than the last window, then
3945                            " vertically split the last window to make that window available.
3946                            let curwin= winnr()
3947                            exe "NetrwKeepj keepalt ".winnr("$")."wincmd w"
3948                            vs
3949                            exe "NetrwKeepj keepalt ".curwin."wincmd w"
3950                        endif
3951                        exe "NetrwKeepj keepalt ".g:netrw_chgwin."wincmd w"
3952                    endif
3953                    call s:SetRexDir(a:islocal,curdir)
3954                endif
3955
3956            endif
3957
3958            " the point where netrw actually edits the (local) file
3959            " if its local only: LocalBrowseCheck() doesn't edit a file, but NetrwBrowse() will
3960            " use keepalt to support  :e #  to return to a directory listing
3961            if !&mod
3962                " if e the new file would fail due to &mod, then don't change any of the flags
3963                let dolockout= 1
3964            endif
3965
3966            if a:islocal
3967                " some like c-^ to return to the last edited file
3968                " others like c-^ to return to the netrw buffer
3969                " Apr 30, 2020: used to have e! here.  That can cause loss of a modified file,
3970                " so emit error E37 instead.
3971                call s:NetrwEditFile("e","",dirname)
3972                call s:NetrwCursor(1)
3973                if &hidden || &bufhidden == "hide"
3974                    " file came from vim's hidden storage.  Don't "restore" options with it.
3975                    let dorestore= 0
3976                endif
3977            endif
3978
3979            " handle g:Netrw_funcref -- call external-to-netrw functions
3980            "   This code will handle g:Netrw_funcref as an individual function reference
3981            "   or as a list of function references.  It will ignore anything that's not
3982            "   a function reference.  See  :help Funcref  for information about function references.
3983            if exists("g:Netrw_funcref")
3984                if type(g:Netrw_funcref) == 2
3985                    NetrwKeepj call g:Netrw_funcref()
3986                elseif type(g:Netrw_funcref) == 3
3987                    for Fncref in g:Netrw_funcref
3988                        if type(Fncref) == 2
3989                            NetrwKeepj call Fncref()
3990                        endif
3991                    endfor
3992                endif
3993            endif
3994        endif
3995
3996    elseif newdir =~ '^/'
3997        " ----------------------------------------------------
3998        " NetrwBrowseChgDir: just go to the new directory spec {{{3
3999        " ----------------------------------------------------
4000        let dirname = newdir
4001        NetrwKeepj call s:SetRexDir(a:islocal,dirname)
4002        NetrwKeepj call s:NetrwOptionsRestore("s:")
4003        norm! m`
4004
4005    elseif newdir == './'
4006        " ---------------------------------------------
4007        " NetrwBrowseChgDir: refresh the directory list {{{3
4008        " ---------------------------------------------
4009        NetrwKeepj call s:SetRexDir(a:islocal,dirname)
4010        norm! m`
4011
4012    elseif newdir == '../'
4013        " --------------------------------------
4014        " NetrwBrowseChgDir: go up one directory {{{3
4015        " --------------------------------------
4016
4017        " The following regexps expect '/' as path separator
4018        let dirname = substitute(netrw#fs#AbsPath(dirname), '\\', '/', 'ge') . '/'
4019
4020        if w:netrw_liststyle == s:TREELIST && exists("w:netrw_treedict")
4021            " force a refresh
4022            setl noro ma
4023            NetrwKeepj %d _
4024        endif
4025
4026        if has("amiga")
4027            " amiga
4028            if a:islocal
4029                let dirname= substitute(dirname,'^\(.*[/:]\)\([^/]\+$\)','\1','')
4030                let dirname= substitute(dirname,'/$','','')
4031            else
4032                let dirname= substitute(dirname,'^\(.*[/:]\)\([^/]\+/$\)','\1','')
4033            endif
4034
4035        elseif !g:netrw_cygwin && has("win32")
4036            " windows
4037            if a:islocal
4038                let dirname= substitute(dirname,'^\(.*\)/\([^/]\+\)/$','\1','')
4039                if dirname == ""
4040                    let dirname= '/'
4041                endif
4042            else
4043                let dirname= substitute(dirname,'^\(\a\{3,}://.\{-}/\{1,2}\)\(.\{-}\)\([^/]\+\)/$','\1\2','')
4044            endif
4045            if dirname =~ '^\a:$'
4046                let dirname= dirname.'/'
4047            endif
4048
4049        else
4050            " unix or cygwin
4051            if a:islocal
4052                let dirname= substitute(dirname,'^\(.*\)/\([^/]\+\)/$','\1','')
4053                if dirname == ""
4054                    let dirname= '/'
4055                endif
4056            else
4057                let dirname= substitute(dirname,'^\(\a\{3,}://.\{-}/\{1,2}\)\(.\{-}\)\([^/]\+\)/$','\1\2','')
4058            endif
4059        endif
4060        NetrwKeepj call s:SetRexDir(a:islocal,dirname)
4061        norm! m`
4062
4063    elseif exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("w:netrw_treedict")
4064        " --------------------------------------
4065        " NetrwBrowseChgDir: Handle Tree Listing {{{3
4066        " --------------------------------------
4067        " force a refresh (for TREELIST, NetrwTreeDir() will force the refresh)
4068        setl noro ma
4069        if !(exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("b:netrw_curdir"))
4070            NetrwKeepj %d _
4071        endif
4072        let treedir      = s:NetrwTreeDir(a:islocal)
4073        let s:treecurpos = winsaveview()
4074        let haskey       = 0
4075
4076        " search treedict for tree dir as-is
4077        if has_key(w:netrw_treedict,treedir)
4078            let haskey= 1
4079        else
4080        endif
4081
4082        " search treedict for treedir with a [/@] appended
4083        if !haskey && treedir !~ '[/@]$'
4084            if has_key(w:netrw_treedict,treedir."/")
4085                let treedir= treedir."/"
4086                let haskey = 1
4087            else
4088            endif
4089        endif
4090
4091        " search treedict for treedir with any trailing / elided
4092        if !haskey && treedir =~ '/$'
4093            let treedir= substitute(treedir,'/$','','')
4094            if has_key(w:netrw_treedict,treedir)
4095                let haskey = 1
4096            else
4097            endif
4098        endif
4099
4100        if haskey
4101            " close tree listing for selected subdirectory
4102            call remove(w:netrw_treedict,treedir)
4103            let dirname= w:netrw_treetop
4104        else
4105            " go down one directory
4106            let dirname= substitute(treedir,'/*$','/','')
4107        endif
4108        NetrwKeepj call s:SetRexDir(a:islocal,dirname)
4109        let s:treeforceredraw = 1
4110
4111    else
4112        " ----------------------------------------
4113        " NetrwBrowseChgDir: Go down one directory {{{3
4114        " ----------------------------------------
4115        let dirname    = netrw#fs#ComposePath(dirname,newdir)
4116        NetrwKeepj call s:SetRexDir(a:islocal,dirname)
4117        norm! m`
4118    endif
4119
4120    " --------------------------------------
4121    " NetrwBrowseChgDir: Restore and Cleanup {{{3
4122    " --------------------------------------
4123    if dorestore
4124        " dorestore is zero'd when a local file was hidden or bufhidden;
4125        " in such a case, we want to keep whatever settings it may have.
4126        NetrwKeepj call s:NetrwOptionsRestore("s:")
4127    endif
4128    if dolockout && dorestore
4129        if filewritable(dirname)
4130            setl ma noro nomod
4131        else
4132            setl ma ro nomod
4133        endif
4134    endif
4135    call s:RestorePosn(s:netrw_posn)
4136    let @@= ykeep
4137
4138    return dirname
4139endfunction
4140
4141" s:NetrwBrowseUpDir: implements the "-" mappings {{{2
4142"    for thin, long, and wide: cursor placed just after banner
4143"    for tree, keeps cursor on current filename
4144function s:NetrwBrowseUpDir(islocal)
4145    if exists("w:netrw_bannercnt") && line(".") < w:netrw_bannercnt-1
4146        " this test needed because occasionally this function seems to be incorrectly called
4147        " when multiple leftmouse clicks are taken when atop the one line help in the banner.
4148        " I'm allowing the very bottom line to permit a "-" exit so that one may escape empty
4149        " directories.
4150        return
4151    endif
4152
4153    norm! 0
4154    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("w:netrw_treedict")
4155        let curline= getline(".")
4156        let swwline= winline() - 1
4157        if exists("w:netrw_treetop")
4158            let b:netrw_curdir= w:netrw_treetop
4159        elseif exists("b:netrw_curdir")
4160            let w:netrw_treetop= b:netrw_curdir
4161        else
4162            let w:netrw_treetop= getcwd()
4163            let b:netrw_curdir = w:netrw_treetop
4164        endif
4165        let curfile = getline(".")
4166        let curpath = s:NetrwTreePath(w:netrw_treetop)
4167        if a:islocal
4168            call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,'../',0))
4169        else
4170            call s:NetrwBrowse(0,s:NetrwBrowseChgDir(0,'../',0))
4171        endif
4172        if w:netrw_treetop == '/'
4173            keepj call search('^\M'.curfile,"w")
4174        elseif curfile == '../'
4175            keepj call search('^\M'.curfile,"wb")
4176        else
4177            while 1
4178                keepj call search('^\M'.s:treedepthstring.curfile,"wb")
4179                let treepath= s:NetrwTreePath(w:netrw_treetop)
4180                if treepath == curpath
4181                    break
4182                endif
4183            endwhile
4184        endif
4185
4186    else
4187        call s:SavePosn(s:netrw_posn)
4188        if exists("b:netrw_curdir")
4189            let curdir= b:netrw_curdir
4190        else
4191            let curdir= expand(getcwd())
4192        endif
4193        if a:islocal
4194            call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,'../',0))
4195        else
4196            call s:NetrwBrowse(0,s:NetrwBrowseChgDir(0,'../',0))
4197        endif
4198        call s:RestorePosn(s:netrw_posn)
4199        let curdir= substitute(curdir,'^.*[\/]','','')
4200        let curdir= '\<'. escape(curdir, '~'). '/'
4201        call search(curdir,'wc')
4202    endif
4203endfunction
4204
4205" netrw#BrowseX:  (implements "x") executes a special "viewer" script or program for the {{{2
4206"                 given filename; typically this means given their extension.
4207function netrw#BrowseX(fname)
4208    " special core dump handler
4209    if a:fname =~ '/core\(\.\d\+\)\=$' && exists("g:Netrw_corehandler")
4210        if type(g:Netrw_corehandler) == v:t_func
4211            " g:Netrw_corehandler is a function reference (see :help Funcref)
4212            call g:Netrw_corehandler(s:NetrwFile(a:fname))
4213        elseif type(g:Netrw_corehandler) == v:t_list
4214            " g:Netrw_corehandler is a List of function references (see :help Funcref)
4215            for Fncref in g:Netrw_corehandler
4216                if type(Fncref) == v:t_func
4217                    call Fncref(a:fname)
4218                endif
4219            endfor
4220        endif
4221        return
4222    endif
4223
4224    let fname = a:fname
4225    " special ~ handler for local
4226    if fname =~ '^\~' && expand("$HOME") != ""
4227        let fname = substitute(fname, '^\~', expand("$HOME"), '')
4228    endif
4229
4230    if fname =~ '^[a-z]\+://'
4231        " open a remote file
4232        call netrw#os#Open(fname)
4233    else
4234        call netrw#os#Open(s:NetrwFile(fname))
4235    endif
4236endfunction
4237
4238" s:NetrwBufRename: renames a buffer without the side effect of retaining an unlisted buffer having the old name {{{2
4239"                   Using the file command on a "[No Name]" buffer does not seem to cause the old "[No Name]" buffer
4240"                   to become an unlisted buffer, so in that case don't bwipe it.
4241function s:NetrwBufRename(newname)
4242    let oldbufname= bufname(bufnr("%"))
4243
4244    if oldbufname != a:newname
4245        let b:junk= 1
4246        exe 'sil! keepj keepalt file '.fnameescape(a:newname)
4247        let oldbufnr= bufnr(oldbufname)
4248        if oldbufname != "" && oldbufnr != -1 && oldbufnr != bufnr("%")
4249            exe "bwipe! ".oldbufnr
4250        endif
4251    endif
4252
4253endfunction
4254
4255" netrw#CheckIfRemote: returns 1 if current file looks like an url, 0 else {{{2
4256function netrw#CheckIfRemote(...)
4257    if a:0 > 0
4258        let curfile= a:1
4259    else
4260        let curfile= expand("%")
4261    endif
4262    " Ignore terminal buffers
4263    if &buftype ==# 'terminal'
4264        return 0
4265    endif
4266    if curfile =~ '^\a\{3,}://'
4267        return 1
4268    else
4269        return 0
4270    endif
4271endfunction
4272
4273" s:NetrwChgPerm: (implements "gp") change file permission {{{2
4274function s:NetrwChgPerm(islocal,curdir)
4275    let ykeep  = @@
4276    call inputsave()
4277    let newperm= input("Enter new permission: ")
4278    call inputrestore()
4279    let fullpath = fnamemodify(netrw#fs#PathJoin(a:curdir, expand("<cfile>")), ':p')
4280    let chgperm= substitute(g:netrw_chgperm,'\<FILENAME\>',netrw#os#Escape(fullpath),'')
4281    let chgperm= substitute(chgperm,'\<PERM\>',netrw#os#Escape(newperm),'')
4282    call system(chgperm)
4283    if v:shell_error != 0
4284        NetrwKeepj call netrw#msg#Notify('WARNING', printf('changing permission on file<%s> seems to have failed', fullpath))
4285    endif
4286    if a:islocal
4287        NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
4288    endif
4289    let @@= ykeep
4290endfunction
4291
4292" s:NetrwClearExplore: clear explore variables (if any) {{{2
4293function s:NetrwClearExplore()
4294    2match none
4295    if exists("s:explore_match")        |unlet s:explore_match        |endif
4296    if exists("s:explore_indx")         |unlet s:explore_indx         |endif
4297    if exists("s:netrw_explore_prvdir") |unlet s:netrw_explore_prvdir |endif
4298    if exists("s:dirstarstar")          |unlet s:dirstarstar          |endif
4299    if exists("s:explore_prvdir")       |unlet s:explore_prvdir       |endif
4300    if exists("w:netrw_explore_indx")   |unlet w:netrw_explore_indx   |endif
4301    if exists("w:netrw_explore_listlen")|unlet w:netrw_explore_listlen|endif
4302    if exists("w:netrw_explore_list")   |unlet w:netrw_explore_list   |endif
4303    if exists("w:netrw_explore_bufnr")  |unlet w:netrw_explore_bufnr  |endif
4304    "   redraw!
4305endfunction
4306
4307" s:NetrwEditBuf: decides whether or not to use keepalt to edit a buffer {{{2
4308function s:NetrwEditBuf(bufnum)
4309    if exists("g:netrw_altfile") && g:netrw_altfile && &ft == "netrw"
4310        exe "sil! NetrwKeepj keepalt noswapfile b ".fnameescape(a:bufnum)
4311    else
4312        exe "sil! NetrwKeepj noswapfile b ".fnameescape(a:bufnum)
4313    endif
4314endfunction
4315
4316" s:NetrwEditFile: decides whether or not to use keepalt to edit a file {{{2
4317"    NetrwKeepj [keepalt] <OPT> <CMD> <FILENAME>
4318function s:NetrwEditFile(cmd,opt,fname)
4319    if exists("g:netrw_altfile") && g:netrw_altfile && &ft == "netrw"
4320        exe "NetrwKeepj noswapfile keepalt ".a:opt." ".a:cmd." ".fnameescape(a:fname)
4321    else
4322        if a:cmd =~# 'e\%[new]!' && !&hidden && getbufvar(bufname('%'), '&modified', 0)
4323            call setbufvar(bufname('%'), '&bufhidden', 'hide')
4324        endif
4325        exe "NetrwKeepj noswapfile ".a:opt." ".a:cmd." ".fnameescape(a:fname)
4326    endif
4327endfunction
4328
4329" s:NetrwExploreListUniq: {{{2
4330function s:NetrwExploreListUniq(explist)
4331    " this assumes that the list is already sorted
4332    let newexplist= []
4333    for member in a:explist
4334        if !exists("uniqmember") || member != uniqmember
4335            let uniqmember = member
4336            let newexplist = newexplist + [ member ]
4337        endif
4338    endfor
4339    return newexplist
4340endfunction
4341
4342" s:NetrwForceChgDir: (gd support) Force treatment as a directory {{{2
4343function s:NetrwForceChgDir(islocal,newdir)
4344    let ykeep= @@
4345    if a:newdir !~ '/$'
4346        " ok, looks like force is needed to get directory-style treatment
4347        if a:newdir =~ '@$'
4348            let newdir= substitute(a:newdir,'@$','/','')
4349        elseif a:newdir =~ '[*=|\\]$'
4350            let newdir= substitute(a:newdir,'.$','/','')
4351        else
4352            let newdir= a:newdir.'/'
4353        endif
4354    else
4355        " should already be getting treatment as a directory
4356        let newdir= a:newdir
4357    endif
4358    let newdir= s:NetrwBrowseChgDir(a:islocal,newdir,0)
4359    call s:NetrwBrowse(a:islocal,newdir)
4360    let @@= ykeep
4361endfunction
4362
4363" s:NetrwForceFile: (gf support) Force treatment as a file {{{2
4364function s:NetrwForceFile(islocal,newfile)
4365    if a:newfile =~ '[/@*=|\\]$'
4366        let newfile= substitute(a:newfile,'.$','','')
4367    else
4368        let newfile= a:newfile
4369    endif
4370    if a:islocal
4371        call s:NetrwBrowseChgDir(a:islocal,newfile,0)
4372    else
4373        call s:NetrwBrowse(a:islocal,s:NetrwBrowseChgDir(a:islocal,newfile,0))
4374    endif
4375endfunction
4376
4377" s:NetrwHide: this function is invoked by the "a" map for browsing {{{2
4378"          and switches the hiding mode.  The actual hiding is done by
4379"          s:NetrwListHide().
4380"             g:netrw_hide= 0: show all
4381"                           1: show not-hidden files
4382"                           2: show hidden files only
4383function s:NetrwHide(islocal)
4384    let ykeep= @@
4385    let svpos= winsaveview()
4386
4387    if exists("s:netrwmarkfilelist_{bufnr('%')}")
4388
4389        " hide the files in the markfile list
4390        for fname in s:netrwmarkfilelist_{bufnr("%")}
4391            if match(g:netrw_list_hide,'\<'.fname.'\>') != -1
4392                " remove fname from hiding list
4393                let g:netrw_list_hide= substitute(g:netrw_list_hide,'..\<'.escape(fname,g:netrw_fname_escape).'\>..','','')
4394                let g:netrw_list_hide= substitute(g:netrw_list_hide,',,',',','g')
4395                let g:netrw_list_hide= substitute(g:netrw_list_hide,'^,\|,$','','')
4396            else
4397                " append fname to hiding list
4398                if exists("g:netrw_list_hide") && g:netrw_list_hide != ""
4399                    let g:netrw_list_hide= g:netrw_list_hide.',\<'.escape(fname,g:netrw_fname_escape).'\>'
4400                else
4401                    let g:netrw_list_hide= '\<'.escape(fname,g:netrw_fname_escape).'\>'
4402                endif
4403            endif
4404        endfor
4405        NetrwKeepj call s:NetrwUnmarkList(bufnr("%"),b:netrw_curdir)
4406        let g:netrw_hide= 1
4407
4408    else
4409
4410        " switch between show-all/show-not-hidden/show-hidden
4411        let g:netrw_hide=(g:netrw_hide+1)%3
4412        exe "NetrwKeepj norm! 0"
4413        if g:netrw_hide && g:netrw_list_hide == ""
4414            call netrw#msg#Notify('WARNING', 'your hiding list is empty!')
4415            let @@= ykeep
4416            return
4417        endif
4418    endif
4419
4420    NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
4421    NetrwKeepj call winrestview(svpos)
4422    let @@= ykeep
4423endfunction
4424
4425" s:NetrwHideEdit: allows user to edit the file/directory hiding list {{{2
4426function s:NetrwHideEdit(islocal)
4427    let ykeep= @@
4428    " save current cursor position
4429    let svpos= winsaveview()
4430
4431    " get new hiding list from user
4432    call inputsave()
4433    let newhide= input("Edit Hiding List: ",g:netrw_list_hide)
4434    call inputrestore()
4435    let g:netrw_list_hide= newhide
4436
4437    " refresh the listing
4438    sil NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,"./",0))
4439
4440    " restore cursor position
4441    call winrestview(svpos)
4442    let @@= ykeep
4443endfunction
4444
4445" s:NetrwHidden: invoked by "gh" {{{2
4446function s:NetrwHidden(islocal)
4447    let ykeep= @@
4448    "  save current position
4449    let svpos  = winsaveview()
4450
4451    if g:netrw_list_hide =~ '\(^\|,\)\\(^\\|\\s\\s\\)\\zs\\.\\S\\+'
4452        " remove .file pattern from hiding list
4453        let g:netrw_list_hide= substitute(g:netrw_list_hide,'\(^\|,\)\\(^\\|\\s\\s\\)\\zs\\.\\S\\+','','')
4454    elseif strdisplaywidth(g:netrw_list_hide) >= 1
4455        let g:netrw_list_hide= g:netrw_list_hide . ',\(^\|\s\s\)\zs\.\S\+'
4456    else
4457        let g:netrw_list_hide= '\(^\|\s\s\)\zs\.\S\+'
4458    endif
4459    if g:netrw_list_hide =~ '^,'
4460        let g:netrw_list_hide= strpart(g:netrw_list_hide,1)
4461    endif
4462
4463    " refresh screen and return to saved position
4464    NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
4465    NetrwKeepj call winrestview(svpos)
4466    let @@= ykeep
4467endfunction
4468
4469"  s:NetrwHome: this function determines a "home" for saving bookmarks and history {{{2
4470function s:NetrwHome()
4471    if exists('g:netrw_home')
4472        let home = expand(g:netrw_home)
4473    elseif has('nvim')
4474        let home = netrw#fs#PathJoin(stdpath('state'), 'netrw')
4475    elseif exists('$MYVIMDIR')
4476        let home = expand('$MYVIMDIR')->substitute('/$', '', '')
4477    else
4478        " Pick the first redable directory in 'runtimepath'
4479        for path in split(&rtp, ',')
4480            if isdirectory(s:NetrwFile(path)) && filewritable(s:NetrwFile(path))
4481                let home = path
4482                break
4483            endif
4484        endfor
4485
4486        if empty(path)
4487            " just pick the first directory
4488            let home = substitute(&rtp, ',.*$', '', '')
4489        endif
4490    endif
4491
4492    " insure that the home directory exists
4493    if g:netrw_dirhistmax > 0 && !isdirectory(s:NetrwFile(home))
4494        if exists("g:netrw_mkdir")
4495            call system(g:netrw_mkdir." ".s:ShellEscape(s:NetrwFile(home)))
4496        else
4497            call mkdir(home, 'p')
4498        endif
4499    endif
4500
4501    " Normalize directory if on Windows
4502    if has("win32")
4503        let home = substitute(home, '/', '\\', 'g')
4504    endif
4505
4506    let g:netrw_home = home
4507    return home
4508endfunction
4509
4510" s:NetrwLeftmouse: handles the <leftmouse> when in a netrw browsing window {{{2
4511function s:NetrwLeftmouse(islocal)
4512    if exists("s:netrwdrag")
4513        return
4514    endif
4515    if &ft != "netrw"
4516        return
4517    endif
4518
4519    let ykeep= @@
4520    " check if the status bar was clicked on instead of a file/directory name
4521    while getchar(0) != 0
4522        "clear the input stream
4523    endwhile
4524    call feedkeys("\<LeftMouse>")
4525    let c          = getchar()
4526    let mouse_lnum = v:mouse_lnum
4527    let wlastline  = line('w$')
4528    let lastline   = line('$')
4529    if mouse_lnum >= wlastline + 1 || v:mouse_win != winnr()
4530        " appears to be a status bar leftmouse click
4531        let @@= ykeep
4532        return
4533    endif
4534    " Dec 04, 2013: following test prevents leftmouse selection/deselection of directories and files in treelist mode
4535    " Windows are separated by vertical separator bars - but the mouse seems to be doing what it should when dragging that bar
4536    " without this test when its disabled.
4537    " May 26, 2014: edit file, :Lex, resize window -- causes refresh.  Reinstated a modified test.  See if problems develop.
4538    if v:mouse_col > virtcol('.')
4539        let @@= ykeep
4540        return
4541    endif
4542
4543    if a:islocal
4544        if exists("b:netrw_curdir")
4545            NetrwKeepj call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,s:NetrwGetWord(),1))
4546        endif
4547    else
4548        if exists("b:netrw_curdir")
4549            NetrwKeepj call s:NetrwBrowse(0,s:NetrwBrowseChgDir(0,s:NetrwGetWord(),1))
4550        endif
4551    endif
4552    let @@= ykeep
4553endfunction
4554
4555" s:NetrwCLeftmouse: used to select a file/directory for a target {{{2
4556function s:NetrwCLeftmouse(islocal)
4557    if &ft != "netrw"
4558        return
4559    endif
4560    call s:NetrwMarkFileTgt(a:islocal)
4561endfunction
4562
4563" s:NetrwServerEdit: edit file in a server gvim, usually NETRWSERVER  (implements <c-r>){{{2
4564"   a:islocal=0 : <c-r> not used, remote
4565"   a:islocal=1 : <c-r> not used, local
4566"   a:islocal=2 : <c-r>     used, remote
4567"   a:islocal=3 : <c-r>     used, local
4568function s:NetrwServerEdit(islocal,fname)
4569    let islocal = a:islocal%2      " =0: remote           =1: local
4570    let ctrlr   = a:islocal >= 2   " =0: <c-r> not used   =1: <c-r> used
4571
4572    if (islocal && isdirectory(s:NetrwFile(a:fname))) || (!islocal && a:fname =~ '/$')
4573        " handle directories in the local window -- not in the remote vim server
4574        " user must have closed the NETRWSERVER window.  Treat as normal editing from netrw.
4575        let g:netrw_browse_split= 0
4576        if exists("s:netrw_browse_split") && exists("s:netrw_browse_split_".winnr())
4577            let g:netrw_browse_split= s:netrw_browse_split_{winnr()}
4578            unlet s:netrw_browse_split_{winnr()}
4579        endif
4580        call s:NetrwBrowse(islocal,s:NetrwBrowseChgDir(islocal,a:fname,0))
4581        return
4582    endif
4583
4584    if has("clientserver") && executable("gvim")
4585
4586        if exists("g:netrw_browse_split") && type(g:netrw_browse_split) == 3
4587            let srvrname = g:netrw_browse_split[0]
4588            let tabnum   = g:netrw_browse_split[1]
4589            let winnum   = g:netrw_browse_split[2]
4590
4591            if serverlist() !~ '\<'.srvrname.'\>'
4592                if !ctrlr
4593                    " user must have closed the server window and the user did not use <c-r>, but
4594                    " used something like <cr>.
4595                    if exists("g:netrw_browse_split")
4596                        unlet g:netrw_browse_split
4597                    endif
4598                    let g:netrw_browse_split= 0
4599                    if exists("s:netrw_browse_split_".winnr())
4600                        let g:netrw_browse_split= s:netrw_browse_split_{winnr()}
4601                    endif
4602                    call s:NetrwBrowseChgDir(islocal,a:fname,0)
4603                    return
4604
4605                elseif has("win32") && executable("start")
4606                    " start up remote netrw server under windows
4607                    call system("start gvim --servername ".srvrname)
4608
4609                else
4610                    " start up remote netrw server under linux
4611                    call system("gvim --servername ".srvrname)
4612                endif
4613            endif
4614
4615            call remote_send(srvrname,":tabn ".tabnum."\<cr>")
4616            call remote_send(srvrname,":".winnum."wincmd w\<cr>")
4617            call remote_send(srvrname,":e ".fnameescape(s:NetrwFile(a:fname))."\<cr>")
4618        else
4619
4620            if serverlist() !~ '\<'.g:netrw_servername.'\>'
4621
4622                if !ctrlr
4623                    if exists("g:netrw_browse_split")
4624                        unlet g:netrw_browse_split
4625                    endif
4626                    let g:netrw_browse_split= 0
4627                    call s:NetrwBrowse(islocal,s:NetrwBrowseChgDir(islocal,a:fname,0))
4628                    return
4629
4630                else
4631                    if has("win32") && executable("start")
4632                        " start up remote netrw server under windows
4633                        call system("start gvim --servername ".g:netrw_servername)
4634                    else
4635                        " start up remote netrw server under linux
4636                        call system("gvim --servername ".g:netrw_servername)
4637                    endif
4638                endif
4639            endif
4640
4641            while 1
4642                try
4643                    call remote_send(g:netrw_servername,":e ".fnameescape(s:NetrwFile(a:fname))."\<cr>")
4644                    break
4645                catch /^Vim\%((\a\+)\)\=:E241/
4646                    sleep 200m
4647                endtry
4648            endwhile
4649
4650            if exists("g:netrw_browse_split")
4651                if type(g:netrw_browse_split) != 3
4652                    let s:netrw_browse_split_{winnr()}= g:netrw_browse_split
4653                endif
4654                unlet g:netrw_browse_split
4655            endif
4656            let g:netrw_browse_split= [g:netrw_servername,1,1]
4657        endif
4658
4659    else
4660        call netrw#msg#Notify('ERROR', 'you need a gui-capable vim and client-server to use <ctrl-r>')
4661    endif
4662
4663endfunction
4664
4665" s:NetrwSLeftmouse: marks the file under the cursor.  May be dragged to select additional files {{{2
4666function s:NetrwSLeftmouse(islocal)
4667    if &ft != "netrw"
4668        return
4669    endif
4670
4671    let s:ngw= s:NetrwGetWord()
4672    call s:NetrwMarkFile(a:islocal,s:ngw)
4673
4674endfunction
4675
4676" s:NetrwSLeftdrag: invoked via a shift-leftmouse and dragging {{{2
4677"                   Used to mark multiple files.
4678function s:NetrwSLeftdrag(islocal)
4679    if !exists("s:netrwdrag")
4680        let s:netrwdrag = winnr()
4681        if a:islocal
4682            nno <silent> <s-leftrelease> <leftmouse>:<c-u>call <SID>NetrwSLeftrelease(1)<cr>
4683        else
4684            nno <silent> <s-leftrelease> <leftmouse>:<c-u>call <SID>NetrwSLeftrelease(0)<cr>
4685        endif
4686    endif
4687    let ngw = s:NetrwGetWord()
4688    if !exists("s:ngw") || s:ngw != ngw
4689        call s:NetrwMarkFile(a:islocal,ngw)
4690    endif
4691    let s:ngw= ngw
4692endfunction
4693
4694" s:NetrwSLeftrelease: terminates shift-leftmouse dragging {{{2
4695function s:NetrwSLeftrelease(islocal)
4696    if exists("s:netrwdrag")
4697        nunmap <s-leftrelease>
4698        let ngw = s:NetrwGetWord()
4699        if !exists("s:ngw") || s:ngw != ngw
4700            call s:NetrwMarkFile(a:islocal,ngw)
4701        endif
4702        if exists("s:ngw")
4703            unlet s:ngw
4704        endif
4705        unlet s:netrwdrag
4706    endif
4707endfunction
4708
4709" s:NetrwListHide: uses [range]g~...~d to delete files that match       {{{2
4710"                  comma-separated patterns given in g:netrw_list_hide
4711function s:NetrwListHide()
4712    let ykeep= @@
4713
4714    " find a character not in the "hide" string to use as a separator for :g and :v commands
4715    " How-it-works: take the hiding command, convert it into a range.
4716    " Duplicate characters don't matter.
4717    " Remove all such characters from the '/~@#...890' string.
4718    " Use the first character left as a separator character.
4719    let listhide= g:netrw_list_hide
4720    let sep     = strpart(substitute('~@#$%^&*{};:,<.>?|1234567890','['.escape(listhide,'-]^\').']','','ge'),1,1)
4721
4722    while listhide != ""
4723        if listhide =~ ','
4724            let hide     = substitute(listhide,',.*$','','e')
4725            let listhide = substitute(listhide,'^.\{-},\(.*\)$','\1','e')
4726        else
4727            let hide     = listhide
4728            let listhide = ""
4729        endif
4730        if g:netrw_sort_by =~ '^[ts]'
4731            if hide =~ '^\^'
4732                let hide= substitute(hide,'^\^','^\(\\d\\+/\)','')
4733            elseif hide =~ '^\\(\^'
4734                let hide= substitute(hide,'^\\(\^','\\(^\\(\\d\\+/\\)','')
4735            endif
4736        endif
4737
4738        " Prune the list by hiding any files which match
4739        if g:netrw_hide == 1
4740            exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$g'.sep.hide.sep.'d'
4741        elseif g:netrw_hide == 2
4742            exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$g'.sep.hide.sep.'s@^@ /-KEEP-/ @'
4743        endif
4744    endwhile
4745
4746    if g:netrw_hide == 2
4747        exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$v@^ /-KEEP-/ @d'
4748        exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s@^\%( /-KEEP-/ \)\+@@e'
4749    endif
4750
4751    " remove any blank lines that have somehow remained.
4752    " This seems to happen under Windows.
4753    exe 'sil! NetrwKeepj 1,$g@^\s*$@d'
4754
4755    let @@= ykeep
4756endfunction
4757
4758" s:NetrwMakeDir: this function makes a directory (both local and remote) {{{2
4759"                 implements the "d" mapping.
4760function s:NetrwMakeDir(usrhost)
4761
4762    let ykeep= @@
4763    " get name of new directory from user.  A bare <CR> will skip.
4764    " if its currently a directory, also request will be skipped, but with
4765    " a message.
4766    call inputsave()
4767    let newdirname= input("Please give directory name: ")
4768    call inputrestore()
4769
4770    if newdirname == ""
4771        let @@= ykeep
4772        return
4773    endif
4774
4775    if a:usrhost == ""
4776
4777        " Local mkdir:
4778        " sanity checks
4779        let fullnewdir= b:netrw_curdir.'/'.newdirname
4780        if isdirectory(s:NetrwFile(fullnewdir))
4781            call netrw#msg#Notify('WARNING', printf('<%s> is already a directory!', newdirname))
4782            let @@= ykeep
4783            return
4784        endif
4785        if s:FileReadable(fullnewdir)
4786            call netrw#msg#Notify('WARNING', printf('<%s> is already a file!', newdirname))
4787            let @@= ykeep
4788            return
4789        endif
4790
4791        " requested new local directory is neither a pre-existing file or
4792        " directory, so make it!
4793        if has("unix")
4794            call mkdir(fullnewdir,"p",xor(0777, system("umask")))
4795        else
4796            call mkdir(fullnewdir,"p")
4797        endif
4798
4799        " on success refresh listing
4800        let svpos= winsaveview()
4801        call s:NetrwRefresh(1,s:NetrwBrowseChgDir(1,'./',0))
4802        call winrestview(svpos)
4803
4804    elseif !exists("b:netrw_method") || b:netrw_method == 4
4805        " Remote mkdir:  using ssh
4806        let mkdircmd  = s:MakeSshCmd(g:netrw_mkdir_cmd)
4807        let newdirname= substitute(b:netrw_curdir,'^\%(.\{-}/\)\{3}\(.*\)$','\1','').newdirname
4808        call netrw#os#Execute("sil! !".mkdircmd." ".netrw#os#Escape(newdirname,1))
4809        if v:shell_error == 0
4810            " refresh listing
4811            let svpos= winsaveview()
4812            NetrwKeepj call s:NetrwRefresh(0,s:NetrwBrowseChgDir(0,'./',0))
4813            NetrwKeepj call winrestview(svpos)
4814        else
4815            call netrw#msg#Notify('ERROR', printf('unable to make directory<%s>', newdirname))
4816        endif
4817
4818    elseif b:netrw_method == 2
4819        " Remote mkdir:  using ftp+.netrc
4820        let svpos= winsaveview()
4821        if exists("b:netrw_fname")
4822            let remotepath= b:netrw_fname
4823        else
4824            let remotepath= ""
4825        endif
4826        call s:NetrwRemoteFtpCmd(remotepath,g:netrw_remote_mkdir.' "'.newdirname.'"')
4827        NetrwKeepj call s:NetrwRefresh(0,s:NetrwBrowseChgDir(0,'./',0))
4828        NetrwKeepj call winrestview(svpos)
4829
4830    elseif b:netrw_method == 3
4831        " Remote mkdir: using ftp + machine, id, passwd, and fname (ie. no .netrc)
4832        let svpos= winsaveview()
4833        if exists("b:netrw_fname")
4834            let remotepath= b:netrw_fname
4835        else
4836            let remotepath= ""
4837        endif
4838        call s:NetrwRemoteFtpCmd(remotepath,g:netrw_remote_mkdir.' "'.newdirname.'"')
4839        NetrwKeepj call s:NetrwRefresh(0,s:NetrwBrowseChgDir(0,'./',0))
4840        NetrwKeepj call winrestview(svpos)
4841    endif
4842
4843    let @@= ykeep
4844endfunction
4845
4846" s:TreeSqueezeDir: allows a shift-cr (gvim only) to squeeze the current tree-listing directory {{{2
4847function s:TreeSqueezeDir(islocal)
4848    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("w:netrw_treedict")
4849        " its a tree-listing style
4850        let curdepth = substitute(getline('.'),'^\(\%('.s:treedepthstring.'\)*\)[^'.s:treedepthstring.'].\{-}$','\1','e')
4851        let stopline = (exists("w:netrw_bannercnt")? (w:netrw_bannercnt + 1) : 1)
4852        let depth    = strchars(substitute(curdepth,' ','','g'))
4853        let srch     = -1
4854        if depth >= 2
4855            NetrwKeepj norm! 0
4856            let curdepthm1= substitute(curdepth,'^'.s:treedepthstring,'','')
4857            let srch      = search('^'.curdepthm1.'\%('.s:treedepthstring.'\)\@!','bW',stopline)
4858        elseif depth == 1
4859            NetrwKeepj norm! 0
4860            let treedepthchr= substitute(s:treedepthstring,' ','','')
4861            let srch        = search('^[^'.treedepthchr.']','bW',stopline)
4862        endif
4863        if srch > 0
4864            call s:NetrwBrowse(a:islocal,s:NetrwBrowseChgDir(a:islocal,s:NetrwGetWord(),1))
4865            exe srch
4866        endif
4867    endif
4868endfunction
4869
4870" s:NetrwMaps: {{{2
4871function s:NetrwMaps(islocal)
4872    " remove B flag from 'cpo' so that \<CR>, \<Bar>, etc. inside
4873    " interpolated path names play back as literal text rather than
4874    " the actual key — without this, a crafted directory name can
4875    " inject keystrokes into the cmdline the mapping is typing
4876    let _cpo = &cpo
4877    set cpo-=B
4878
4879    " mouse <Plug> maps: {{{3
4880    if g:netrw_mousemaps && g:netrw_retmap
4881        if !hasmapto("<Plug>NetrwReturn")
4882            if maparg("<2-leftmouse>","n") == "" || maparg("<2-leftmouse>","n") =~ '^-$'
4883                nmap <unique> <silent> <2-leftmouse>       <Plug>NetrwReturn
4884            elseif maparg("<c-leftmouse>","n") == ""
4885                nmap <unique> <silent> <c-leftmouse>       <Plug>NetrwReturn
4886            endif
4887        endif
4888        nno <silent> <Plug>NetrwReturn       :Rexplore<cr>
4889    endif
4890
4891    " generate default <Plug> maps {{{3
4892    if !hasmapto('<Plug>NetrwHide')              |nmap <buffer> <silent> <nowait> a       <Plug>NetrwHide_a|endif
4893    if !hasmapto('<Plug>NetrwBrowseUpDir')       |nmap <buffer> <silent> <nowait> -       <Plug>NetrwBrowseUpDir|endif
4894    if !hasmapto('<Plug>NetrwOpenFile')          |nmap <buffer> <silent> <nowait> %       <Plug>NetrwOpenFile|endif
4895    if !hasmapto('<Plug>NetrwBadd_cb')           |nmap <buffer> <silent> <nowait> cb      <Plug>NetrwBadd_cb|endif
4896    if !hasmapto('<Plug>NetrwBadd_cB')           |nmap <buffer> <silent> <nowait> cB      <Plug>NetrwBadd_cB|endif
4897    if !hasmapto('<Plug>NetrwLcd')               |nmap <buffer> <silent> <nowait> cd      <Plug>NetrwLcd|endif
4898    if !hasmapto('<Plug>NetrwSetChgwin')         |nmap <buffer> <silent> <nowait> C       <Plug>NetrwSetChgwin|endif
4899    if !hasmapto('<Plug>NetrwRefresh')           |nmap <buffer> <silent> <nowait> <c-l>   <Plug>NetrwRefresh|endif
4900    if !hasmapto('<Plug>NetrwLocalBrowseCheck')  |nmap <buffer> <silent> <nowait> <cr>    <Plug>NetrwLocalBrowseCheck|endif
4901    if !hasmapto('<Plug>NetrwServerEdit')        |nmap <buffer> <silent> <nowait> <c-r>   <Plug>NetrwServerEdit|endif
4902    if !hasmapto('<Plug>NetrwMakeDir')           |nmap <buffer> <silent> <nowait> d       <Plug>NetrwMakeDir|endif
4903    if !hasmapto('<Plug>NetrwBookHistHandler_gb')|nmap <buffer> <silent> <nowait> gb      <Plug>NetrwBookHistHandler_gb|endif
4904
4905    if a:islocal
4906        " local normal-mode maps {{{3
4907        nnoremap <buffer> <silent> <Plug>NetrwHide_a                 :<c-u>call <SID>NetrwHide(1)<cr>
4908        nnoremap <buffer> <silent> <Plug>NetrwBrowseUpDir            :<c-u>call <SID>NetrwBrowseUpDir(1)<cr>
4909        nnoremap <buffer> <silent> <Plug>NetrwOpenFile               :<c-u>call <SID>NetrwOpenFile(1)<cr>
4910        nnoremap <buffer> <silent> <Plug>NetrwBadd_cb                :<c-u>call <SID>NetrwBadd(1,0)<cr>
4911        nnoremap <buffer> <silent> <Plug>NetrwBadd_cB                :<c-u>call <SID>NetrwBadd(1,1)<cr>
4912        nnoremap <buffer> <silent> <Plug>NetrwLcd                    :<c-u>call <SID>NetrwLcd(b:netrw_curdir)<cr>
4913        nnoremap <buffer> <silent> <Plug>NetrwSetChgwin              :<c-u>call <SID>NetrwSetChgwin()<cr>
4914        nnoremap <buffer> <silent> <Plug>NetrwLocalBrowseCheck       :<c-u>call netrw#LocalBrowseCheck(<SID>NetrwBrowseChgDir(1,<SID>NetrwGetWord(),1))<cr>
4915        nnoremap <buffer> <silent> <Plug>NetrwServerEdit             :<c-u>call <SID>NetrwServerEdit(3,<SID>NetrwGetWord())<cr>
4916        nnoremap <buffer> <silent> <Plug>NetrwMakeDir                :<c-u>call <SID>NetrwMakeDir("")<cr>
4917        nnoremap <buffer> <silent> <Plug>NetrwBookHistHandler_gb     :<c-u>call <SID>NetrwBookHistHandler(1,b:netrw_curdir)<cr>
4918        " ---------------------------------------------------------------------
4919        nnoremap <buffer> <silent> <nowait> gd       :<c-u>call <SID>NetrwForceChgDir(1,<SID>NetrwGetWord())<cr>
4920        nnoremap <buffer> <silent> <nowait> gf       :<c-u>call <SID>NetrwForceFile(1,<SID>NetrwGetWord())<cr>
4921        nnoremap <buffer> <silent> <nowait> gh       :<c-u>call <SID>NetrwHidden(1)<cr>
4922        nnoremap <buffer> <silent> <nowait> gn       :<c-u>call netrw#SetTreetop(0,<SID>NetrwGetWord())<cr>
4923        nnoremap <buffer> <silent> <nowait> gp       :<c-u>call <SID>NetrwChgPerm(1,b:netrw_curdir)<cr>
4924        nnoremap <buffer> <silent> <nowait> I        :<c-u>call <SID>NetrwBannerCtrl(1)<cr>
4925        nnoremap <buffer> <silent> <nowait> i        :<c-u>call <SID>NetrwListStyle(1)<cr>
4926        nnoremap <buffer> <silent> <nowait> ma       :<c-u>call <SID>NetrwMarkFileArgList(1,0)<cr>
4927        nnoremap <buffer> <silent> <nowait> mA       :<c-u>call <SID>NetrwMarkFileArgList(1,1)<cr>
4928        nnoremap <buffer> <silent> <nowait> mb       :<c-u>call <SID>NetrwBookHistHandler(0,b:netrw_curdir)<cr>
4929        nnoremap <buffer> <silent> <nowait> mB       :<c-u>call <SID>NetrwBookHistHandler(6,b:netrw_curdir)<cr>
4930        nnoremap <buffer> <silent> <nowait> mc       :<c-u>call <SID>NetrwMarkFileCopy(1)<cr>
4931        nnoremap <buffer> <silent> <nowait> md       :<c-u>call <SID>NetrwMarkFileDiff(1)<cr>
4932        nnoremap <buffer> <silent> <nowait> me       :<c-u>call <SID>NetrwMarkFileEdit(1)<cr>
4933        nnoremap <buffer> <silent> <nowait> mf       :<c-u>call <SID>NetrwMarkFile(1,<SID>NetrwGetWord())<cr>
4934        nnoremap <buffer> <silent> <nowait> mF       :<c-u>call <SID>NetrwUnmarkList(bufnr("%"),b:netrw_curdir)<cr>
4935        nnoremap <buffer> <silent> <nowait> mg       :<c-u>call <SID>NetrwMarkFileGrep(1)<cr>
4936        nnoremap <buffer> <silent> <nowait> mh       :<c-u>call <SID>NetrwMarkHideSfx(1)<cr>
4937        nnoremap <buffer> <silent> <nowait> mm       :<c-u>call <SID>NetrwMarkFileMove(1)<cr>
4938        nnoremap <buffer> <silent> <nowait> mr       :<c-u>call <SID>NetrwMarkFileRegexp(1)<cr>
4939        nnoremap <buffer> <silent> <nowait> ms       :<c-u>call <SID>NetrwMarkFileSource(1)<cr>
4940        nnoremap <buffer> <silent> <nowait> mT       :<c-u>call <SID>NetrwMarkFileTag(1)<cr>
4941        nnoremap <buffer> <silent> <nowait> mt       :<c-u>call <SID>NetrwMarkFileTgt(1)<cr>
4942        nnoremap <buffer> <silent> <nowait> mu       :<c-u>call <SID>NetrwUnMarkFile(1)<cr>
4943        nnoremap <buffer> <silent> <nowait> mv       :<c-u>call <SID>NetrwMarkFileVimCmd(1)<cr>
4944        nnoremap <buffer> <silent> <nowait> mx       :<c-u>call <SID>NetrwMarkFileExe(1,0)<cr>
4945        nnoremap <buffer> <silent> <nowait> mX       :<c-u>call <SID>NetrwMarkFileExe(1,1)<cr>
4946        nnoremap <buffer> <silent> <nowait> mz       :<c-u>call <SID>NetrwMarkFileCompress(1)<cr>
4947        nnoremap <buffer> <silent> <nowait> O        :<c-u>call <SID>NetrwObtain(1)<cr>
4948        nnoremap <buffer> <silent> <nowait> o        :call <SID>NetrwSplit(3)<cr>
4949        nnoremap <buffer> <silent> <nowait> p        :<c-u>call <SID>NetrwPreview(<SID>NetrwBrowseChgDir(1,<SID>NetrwGetWord(),1,1))<cr>
4950        nnoremap <buffer> <silent> <nowait> P        :<c-u>call <SID>NetrwPrevWinOpen(1)<cr>
4951        nnoremap <buffer> <silent> <nowait> qb       :<c-u>call <SID>NetrwBookHistHandler(2,b:netrw_curdir)<cr>
4952        nnoremap <buffer> <silent> <nowait> qf       :<c-u>call <SID>NetrwFileInfo(1,<SID>NetrwGetWord())<cr>
4953        nnoremap <buffer> <silent> <nowait> qF       :<c-u>call <SID>NetrwMarkFileQFEL(1,getqflist())<cr>
4954        nnoremap <buffer> <silent> <nowait> qL       :<c-u>call <SID>NetrwMarkFileQFEL(1,getloclist(v:count))<cr>
4955        nnoremap <buffer> <silent> <nowait> s        :call <SID>NetrwSortStyle(1)<cr>
4956        nnoremap <buffer> <silent> <nowait> S        :<c-u>call <SID>NetSortSequence(1)<cr>
4957        nnoremap <buffer> <silent> <nowait> Tb       :<c-u>call <SID>NetrwSetTgt(1,'b',v:count1)<cr>
4958        nnoremap <buffer> <silent> <nowait> t        :call <SID>NetrwSplit(4)<cr>
4959        nnoremap <buffer> <silent> <nowait> Th       :<c-u>call <SID>NetrwSetTgt(1,'h',v:count)<cr>
4960        nnoremap <buffer> <silent> <nowait> u        :<c-u>call <SID>NetrwBookHistHandler(4,expand("%"))<cr>
4961        nnoremap <buffer> <silent> <nowait> U        :<c-u>call <SID>NetrwBookHistHandler(5,expand("%"))<cr>
4962        nnoremap <buffer> <silent> <nowait> v        :call <SID>NetrwSplit(5)<cr>
4963        nnoremap <buffer> <silent> <nowait> x        :<c-u>call netrw#BrowseX(<SID>NetrwBrowseChgDir(1,<SID>NetrwGetWord(),1,0))"<cr>
4964        nnoremap <buffer> <silent> <nowait> X        :<c-u>call <SID>NetrwLocalExecute(expand("<cword>"))"<cr>
4965
4966        nnoremap <buffer> <silent> <nowait> r        :<c-u>let g:netrw_sort_direction= (g:netrw_sort_direction =~# 'n')? 'r' : 'n'<bar>exe "norm! 0"<bar>call <SID>NetrwRefresh(1,<SID>NetrwBrowseChgDir(1,'./',0))<cr>
4967        if !hasmapto('<Plug>NetrwHideEdit')
4968            nmap <buffer> <unique> <c-h> <Plug>NetrwHideEdit
4969        endif
4970        nnoremap <buffer> <silent> <Plug>NetrwHideEdit               :call <SID>NetrwHideEdit(1)<cr>
4971        if !hasmapto('<Plug>NetrwRefresh')
4972            nmap <buffer> <unique> <c-l> <Plug>NetrwRefresh
4973        endif
4974        nnoremap <buffer> <silent> <Plug>NetrwRefresh                <c-l>:call <SID>NetrwRefresh(1,<SID>NetrwBrowseChgDir(1,(exists("w:netrw_liststyle") && exists("w:netrw_treetop") && w:netrw_liststyle == 3)? w:netrw_treetop : './',0))<cr>
4975        if s:didstarstar || !mapcheck("<s-down>","n")
4976            nnoremap <buffer> <silent> <s-down> :Nexplore<cr>
4977        endif
4978        if s:didstarstar || !mapcheck("<s-up>","n")
4979            nnoremap <buffer> <silent> <s-up>   :Pexplore<cr>
4980        endif
4981        if !hasmapto('<Plug>NetrwTreeSqueeze')
4982            nmap <buffer> <silent> <nowait> <s-cr>                      <Plug>NetrwTreeSqueeze
4983        endif
4984        nnoremap <buffer> <silent> <Plug>NetrwTreeSqueeze            :call <SID>TreeSqueezeDir(1)<cr>
4985        let mapsafecurdir = escape(b:netrw_curdir, s:netrw_map_escape)
4986        if g:netrw_mousemaps == 1
4987            nmap <buffer>                       <leftmouse>             <Plug>NetrwLeftmouse
4988            nmap <buffer>                       <c-leftmouse>           <Plug>NetrwCLeftmouse
4989            nmap <buffer>                       <middlemouse>           <Plug>NetrwMiddlemouse
4990            nmap <buffer>                       <s-leftmouse>           <Plug>NetrwSLeftmouse
4991            nmap <buffer>                       <s-leftdrag>            <Plug>NetrwSLeftdrag
4992            nmap <buffer>                       <2-leftmouse>           <Plug>Netrw2Leftmouse
4993            imap <buffer>                       <leftmouse>             <Plug>ILeftmouse
4994            imap <buffer>                       <middlemouse>           <Plug>IMiddlemouse
4995            nno  <buffer> <silent>              <Plug>NetrwLeftmouse    :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwLeftmouse(1)<cr>
4996            nno  <buffer> <silent>              <Plug>NetrwCLeftmouse   :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwCLeftmouse(1)<cr>
4997            nno  <buffer> <silent>              <Plug>NetrwMiddlemouse  :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwPrevWinOpen(1)<cr>
4998            nno  <buffer> <silent>              <Plug>NetrwSLeftmouse   :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwSLeftmouse(1)<cr>
4999            nno  <buffer> <silent>              <Plug>NetrwSLeftdrag    :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwSLeftdrag(1)<cr>
5000            nmap <buffer> <silent>              <Plug>Netrw2Leftmouse   -
5001            exe 'nnoremap <buffer> <silent> <rightmouse>  :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwLocalRm("'.mapsafecurdir.'")<cr>'
5002            exe 'vnoremap <buffer> <silent> <rightmouse>  :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwLocalRm("'.mapsafecurdir.'")<cr>'
5003        endif
5004        exe 'nnoremap <buffer> <silent> <nowait> <del>       :call <SID>NetrwLocalRm("'.mapsafecurdir.'")<cr>'
5005        exe 'nnoremap <buffer> <silent> <nowait> D           :call <SID>NetrwLocalRm("'.mapsafecurdir.'")<cr>'
5006        exe 'nnoremap <buffer> <silent> <nowait> R           :call <SID>NetrwLocalRename("'.mapsafecurdir.'")<cr>'
5007        exe 'nnoremap <buffer> <silent> <nowait> d           :call <SID>NetrwMakeDir("")<cr>'
5008        exe 'vnoremap <buffer> <silent> <nowait> <del>       :call <SID>NetrwLocalRm("'.mapsafecurdir.'")<cr>'
5009        exe 'vnoremap <buffer> <silent> <nowait> D           :call <SID>NetrwLocalRm("'.mapsafecurdir.'")<cr>'
5010        exe 'vnoremap <buffer> <silent> <nowait> R           :call <SID>NetrwLocalRename("'.mapsafecurdir.'")<cr>'
5011        nnoremap <buffer> <F1>                       :he netrw-quickhelp<cr>
5012
5013        " support user-specified maps
5014        call netrw#UserMaps(1)
5015
5016    else
5017        " remote normal-mode maps {{{3
5018        call s:RemotePathAnalysis(b:netrw_curdir)
5019        nnoremap <buffer> <silent> <Plug>NetrwHide_a                 :<c-u>call <SID>NetrwHide(0)<cr>
5020        nnoremap <buffer> <silent> <Plug>NetrwBrowseUpDir            :<c-u>call <SID>NetrwBrowseUpDir(0)<cr>
5021        nnoremap <buffer> <silent> <Plug>NetrwOpenFile               :<c-u>call <SID>NetrwOpenFile(0)<cr>
5022        nnoremap <buffer> <silent> <Plug>NetrwBadd_cb                :<c-u>call <SID>NetrwBadd(0,0)<cr>
5023        nnoremap <buffer> <silent> <Plug>NetrwBadd_cB                :<c-u>call <SID>NetrwBadd(0,1)<cr>
5024        nnoremap <buffer> <silent> <Plug>NetrwLcd                    :<c-u>call <SID>NetrwLcd(b:netrw_curdir)<cr>
5025        nnoremap <buffer> <silent> <Plug>NetrwSetChgwin              :<c-u>call <SID>NetrwSetChgwin()<cr>
5026        nnoremap <buffer> <silent> <Plug>NetrwRefresh                :<c-u>call <SID>NetrwRefresh(0,<SID>NetrwBrowseChgDir(0,'./',0))<cr>
5027        nnoremap <buffer> <silent> <Plug>NetrwLocalBrowseCheck       :<c-u>call <SID>NetrwBrowse(0,<SID>NetrwBrowseChgDir(0,<SID>NetrwGetWord(),1))<cr>
5028        nnoremap <buffer> <silent> <Plug>NetrwServerEdit             :<c-u>call <SID>NetrwServerEdit(2,<SID>NetrwGetWord())<cr>
5029        nnoremap <buffer> <silent> <Plug>NetrwBookHistHandler_gb     :<c-u>call <SID>NetrwBookHistHandler(1,b:netrw_curdir)<cr>
5030        " ---------------------------------------------------------------------
5031        nnoremap <buffer> <silent> <nowait> gd       :<c-u>call <SID>NetrwForceChgDir(0,<SID>NetrwGetWord())<cr>
5032        nnoremap <buffer> <silent> <nowait> gf       :<c-u>call <SID>NetrwForceFile(0,<SID>NetrwGetWord())<cr>
5033        nnoremap <buffer> <silent> <nowait> gh       :<c-u>call <SID>NetrwHidden(0)<cr>
5034        nnoremap <buffer> <silent> <nowait> gp       :<c-u>call <SID>NetrwChgPerm(0,b:netrw_curdir)<cr>
5035        nnoremap <buffer> <silent> <nowait> I        :<c-u>call <SID>NetrwBannerCtrl(1)<cr>
5036        nnoremap <buffer> <silent> <nowait> i        :<c-u>call <SID>NetrwListStyle(0)<cr>
5037        nnoremap <buffer> <silent> <nowait> ma       :<c-u>call <SID>NetrwMarkFileArgList(0,0)<cr>
5038        nnoremap <buffer> <silent> <nowait> mA       :<c-u>call <SID>NetrwMarkFileArgList(0,1)<cr>
5039        nnoremap <buffer> <silent> <nowait> mb       :<c-u>call <SID>NetrwBookHistHandler(0,b:netrw_curdir)<cr>
5040        nnoremap <buffer> <silent> <nowait> mB       :<c-u>call <SID>NetrwBookHistHandler(6,b:netrw_curdir)<cr>
5041        nnoremap <buffer> <silent> <nowait> mc       :<c-u>call <SID>NetrwMarkFileCopy(0)<cr>
5042        nnoremap <buffer> <silent> <nowait> md       :<c-u>call <SID>NetrwMarkFileDiff(0)<cr>
5043        nnoremap <buffer> <silent> <nowait> me       :<c-u>call <SID>NetrwMarkFileEdit(0)<cr>
5044        nnoremap <buffer> <silent> <nowait> mf       :<c-u>call <SID>NetrwMarkFile(0,<SID>NetrwGetWord())<cr>
5045        nnoremap <buffer> <silent> <nowait> mF       :<c-u>call <SID>NetrwUnmarkList(bufnr("%"),b:netrw_curdir)<cr>
5046        nnoremap <buffer> <silent> <nowait> mg       :<c-u>call <SID>NetrwMarkFileGrep(0)<cr>
5047        nnoremap <buffer> <silent> <nowait> mh       :<c-u>call <SID>NetrwMarkHideSfx(0)<cr>
5048        nnoremap <buffer> <silent> <nowait> mm       :<c-u>call <SID>NetrwMarkFileMove(0)<cr>
5049        nnoremap <buffer> <silent> <nowait> mr       :<c-u>call <SID>NetrwMarkFileRegexp(0)<cr>
5050        nnoremap <buffer> <silent> <nowait> ms       :<c-u>call <SID>NetrwMarkFileSource(0)<cr>
5051        nnoremap <buffer> <silent> <nowait> mT       :<c-u>call <SID>NetrwMarkFileTag(0)<cr>
5052        nnoremap <buffer> <silent> <nowait> mt       :<c-u>call <SID>NetrwMarkFileTgt(0)<cr>
5053        nnoremap <buffer> <silent> <nowait> mu       :<c-u>call <SID>NetrwUnMarkFile(0)<cr>
5054        nnoremap <buffer> <silent> <nowait> mv       :<c-u>call <SID>NetrwMarkFileVimCmd(0)<cr>
5055        nnoremap <buffer> <silent> <nowait> mx       :<c-u>call <SID>NetrwMarkFileExe(0,0)<cr>
5056        nnoremap <buffer> <silent> <nowait> mX       :<c-u>call <SID>NetrwMarkFileExe(0,1)<cr>
5057        nnoremap <buffer> <silent> <nowait> mz       :<c-u>call <SID>NetrwMarkFileCompress(0)<cr>
5058        nnoremap <buffer> <silent> <nowait> O        :<c-u>call <SID>NetrwObtain(0)<cr>
5059        nnoremap <buffer> <silent> <nowait> o        :call <SID>NetrwSplit(0)<cr>
5060        nnoremap <buffer> <silent> <nowait> p        :<c-u>call <SID>NetrwPreview(<SID>NetrwBrowseChgDir(1,<SID>NetrwGetWord(),1,1))<cr>
5061        nnoremap <buffer> <silent> <nowait> P        :<c-u>call <SID>NetrwPrevWinOpen(0)<cr>
5062        nnoremap <buffer> <silent> <nowait> qb       :<c-u>call <SID>NetrwBookHistHandler(2,b:netrw_curdir)<cr>
5063        nnoremap <buffer> <silent> <nowait> qf       :<c-u>call <SID>NetrwFileInfo(0,<SID>NetrwGetWord())<cr>
5064        nnoremap <buffer> <silent> <nowait> qF       :<c-u>call <SID>NetrwMarkFileQFEL(0,getqflist())<cr>
5065        nnoremap <buffer> <silent> <nowait> qL       :<c-u>call <SID>NetrwMarkFileQFEL(0,getloclist(v:count))<cr>
5066        nnoremap <buffer> <silent> <nowait> r        :<c-u>let g:netrw_sort_direction= (g:netrw_sort_direction =~# 'n')? 'r' : 'n'<bar>exe "norm! 0"<bar>call <SID>NetrwBrowse(0,<SID>NetrwBrowseChgDir(0,'./',0))<cr>
5067        nnoremap <buffer> <silent> <nowait> s        :call <SID>NetrwSortStyle(0)<cr>
5068        nnoremap <buffer> <silent> <nowait> S        :<c-u>call <SID>NetSortSequence(0)<cr>
5069        nnoremap <buffer> <silent> <nowait> Tb       :<c-u>call <SID>NetrwSetTgt(0,'b',v:count1)<cr>
5070        nnoremap <buffer> <silent> <nowait> t        :call <SID>NetrwSplit(1)<cr>
5071        nnoremap <buffer> <silent> <nowait> Th       :<c-u>call <SID>NetrwSetTgt(0,'h',v:count)<cr>
5072        nnoremap <buffer> <silent> <nowait> u        :<c-u>call <SID>NetrwBookHistHandler(4,b:netrw_curdir)<cr>
5073        nnoremap <buffer> <silent> <nowait> U        :<c-u>call <SID>NetrwBookHistHandler(5,b:netrw_curdir)<cr>
5074        nnoremap <buffer> <silent> <nowait> v        :call <SID>NetrwSplit(2)<cr>
5075        if !hasmapto('<Plug>NetrwHideEdit')
5076            nmap <buffer> <c-h> <Plug>NetrwHideEdit
5077        endif
5078        nnoremap <buffer> <silent> <Plug>NetrwHideEdit       :call <SID>NetrwHideEdit(0)<cr>
5079        if !hasmapto('<Plug>NetrwRefresh')
5080            nmap <buffer> <c-l> <Plug>NetrwRefresh
5081        endif
5082        if !hasmapto('<Plug>NetrwTreeSqueeze')
5083            nmap <buffer> <silent> <nowait> <s-cr>      <Plug>NetrwTreeSqueeze
5084        endif
5085        nnoremap <buffer> <silent> <Plug>NetrwTreeSqueeze    :call <SID>TreeSqueezeDir(0)<cr>
5086
5087        let mapsafepath     = escape(s:path, s:netrw_map_escape)
5088        let mapsafeusermach = escape(((s:user == "")? "" : s:user."@").s:machine, s:netrw_map_escape)
5089
5090        nnoremap <buffer> <silent> <Plug>NetrwRefresh        :call <SID>NetrwRefresh(0,<SID>NetrwBrowseChgDir(0,'./',0))<cr>
5091        if g:netrw_mousemaps == 1
5092            nmap <buffer> <leftmouse>           <Plug>NetrwLeftmouse
5093            nno  <buffer> <silent>              <Plug>NetrwLeftmouse    :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwLeftmouse(0)<cr>
5094            nmap <buffer> <c-leftmouse>         <Plug>NetrwCLeftmouse
5095            nno  <buffer> <silent>              <Plug>NetrwCLeftmouse   :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwCLeftmouse(0)<cr>
5096            nmap <buffer> <s-leftmouse>         <Plug>NetrwSLeftmouse
5097            nno  <buffer> <silent>              <Plug>NetrwSLeftmouse   :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwSLeftmouse(0)<cr>
5098            nmap <buffer> <s-leftdrag>          <Plug>NetrwSLeftdrag
5099            nno  <buffer> <silent>              <Plug>NetrwSLeftdrag    :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwSLeftdrag(0)<cr>
5100            nmap <middlemouse>                  <Plug>NetrwMiddlemouse
5101            nno  <buffer> <silent>              <middlemouse>           <Plug>NetrwMiddlemouse :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwPrevWinOpen(0)<cr>
5102            nmap <buffer> <2-leftmouse>         <Plug>Netrw2Leftmouse
5103            nmap <buffer> <silent>              <Plug>Netrw2Leftmouse   -
5104                imap <buffer> <leftmouse>           <Plug>ILeftmouse
5105            imap <buffer> <middlemouse>         <Plug>IMiddlemouse
5106            imap <buffer> <s-leftmouse>         <Plug>ISLeftmouse
5107            exe 'nnoremap <buffer> <silent> <rightmouse> :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwRemoteRm("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5108            exe 'vnoremap <buffer> <silent> <rightmouse> :exec "norm! \<lt>leftmouse>"<bar>call <SID>NetrwRemoteRm("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5109        endif
5110        exe 'nnoremap <buffer> <silent> <nowait> <del>       :call <SID>NetrwRemoteRm("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5111        exe 'nnoremap <buffer> <silent> <nowait> d           :call <SID>NetrwMakeDir("'.mapsafeusermach.'")<cr>'
5112        exe 'nnoremap <buffer> <silent> <nowait> D           :call <SID>NetrwRemoteRm("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5113        exe 'nnoremap <buffer> <silent> <nowait> R           :call <SID>NetrwRemoteRename("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5114        exe 'vnoremap <buffer> <silent> <nowait> <del>       :call <SID>NetrwRemoteRm("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5115        exe 'vnoremap <buffer> <silent> <nowait> D           :call <SID>NetrwRemoteRm("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5116        exe 'vnoremap <buffer> <silent> <nowait> R           :call <SID>NetrwRemoteRename("'.mapsafeusermach.'","'.mapsafepath.'")<cr>'
5117        nnoremap <buffer> <F1>                       :he netrw-quickhelp<cr>
5118
5119        " support user-specified maps
5120        call netrw#UserMaps(0)
5121    endif " }}}3
5122    let &cpo = _cpo
5123endfunction
5124
5125" s:NetrwCommands: set up commands                              {{{2
5126"  If -buffer, the command is only available from within netrw buffers
5127"  Otherwise, the command is available from any window, so long as netrw
5128"  has been used at least once in the session.
5129function s:NetrwCommands(islocal)
5130
5131    com! -nargs=* -complete=file -bang    NetrwMB call s:NetrwBookmark(<bang>0,<f-args>)
5132    com! -nargs=*                         NetrwC  call s:NetrwSetChgwin(<q-args>)
5133    com! Rexplore if exists("w:netrw_rexlocal")|call s:NetrwRexplore(w:netrw_rexlocal,exists("w:netrw_rexdir")? w:netrw_rexdir : ".")|else|call netrw#msg#Notify('WARNING', "win#".winnr()." not a former netrw window")|endif
5134    if a:islocal
5135        com! -buffer -nargs=+ -complete=file MF      call s:NetrwMarkFiles(1,<f-args>)
5136    else
5137        com! -buffer -nargs=+ -complete=file MF      call s:NetrwMarkFiles(0,<f-args>)
5138    endif
5139    com! -buffer -nargs=? -complete=file  MT      call s:NetrwMarkTarget(<q-args>)
5140
5141endfunction
5142
5143" s:NetrwMarkFiles: apply s:NetrwMarkFile() to named file(s) {{{2
5144"                   glob()ing only works with local files
5145function s:NetrwMarkFiles(islocal,...)
5146    let curdir = s:NetrwGetCurdir(a:islocal)
5147    let i      = 1
5148    while i <= a:0
5149        if a:islocal
5150            let mffiles= glob(a:{i}, 0, 1, 1)
5151        else
5152            let mffiles= [a:{i}]
5153        endif
5154        for mffile in mffiles
5155            call s:NetrwMarkFile(a:islocal,mffile)
5156        endfor
5157        let i= i + 1
5158    endwhile
5159endfunction
5160
5161" s:NetrwMarkTarget: implements :MT (mark target) {{{2
5162function s:NetrwMarkTarget(...)
5163    if a:0 == 0 || (a:0 == 1 && a:1 == "")
5164        let curdir = s:NetrwGetCurdir(1)
5165        let tgt    = b:netrw_curdir
5166    else
5167        let curdir = s:NetrwGetCurdir((a:1 =~ '^\a\{3,}://')? 0 : 1)
5168        let tgt    = a:1
5169    endif
5170    let s:netrwmftgt         = tgt
5171    let s:netrwmftgt_islocal = tgt !~ '^\a\{3,}://'
5172    let curislocal           = b:netrw_curdir !~ '^\a\{3,}://'
5173    let svpos                = winsaveview()
5174    call s:NetrwRefresh(curislocal,s:NetrwBrowseChgDir(curislocal,'./',0))
5175    call winrestview(svpos)
5176endfunction
5177
5178" s:NetrwMarkFile: (invoked by mf) This function is used to both {{{2
5179"                  mark and unmark files.  If a markfile list exists,
5180"                  then the rename and delete functions will use it instead
5181"                  of whatever may happen to be under the cursor at that
5182"                  moment.  When the mouse and gui are available,
5183"                  shift-leftmouse may also be used to mark files.
5184"
5185"  Creates two lists
5186"    s:netrwmarkfilelist    -- holds complete paths to all marked files
5187"    s:netrwmarkfilelist_#  -- holds list of marked files in current-buffer's directory (#==bufnr())
5188"
5189"  Creates a marked file match string
5190"    s:netrwmarkfilemtch_#   -- used with 2match to display marked files
5191"
5192"  Creates a buffer version of islocal
5193"    b:netrw_islocal
5194function s:NetrwMarkFile(islocal,fname)
5195
5196    " sanity check
5197    if empty(a:fname)
5198        return
5199    endif
5200    let curdir = s:NetrwGetCurdir(a:islocal)
5201
5202    let ykeep    = @@
5203    let curbufnr = bufnr("%")
5204    let leader   = '\%(^\|\s\)\zs'
5205    let word_boundary_trailer = '\>[@=|\/\*]\=\ze\%(  \|\t\|$\)'
5206    let fallback_trailer      = '[@=|\/\*]\=\ze\%(  \|\t\|$\)'
5207    let trailer = (a:fname =~ '\a$') ? word_boundary_trailer : fallback_trailer
5208
5209    if exists("s:netrwmarkfilelist_".curbufnr)
5210        " markfile list pre-exists
5211        let b:netrw_islocal = a:islocal
5212
5213        if index(s:netrwmarkfilelist_{curbufnr},a:fname) == -1
5214            " append filename to buffer's markfilelist
5215            call add(s:netrwmarkfilelist_{curbufnr},substitute(a:fname,'[|@]$','',''))
5216            let s:netrwmarkfilemtch_{curbufnr} = s:netrwmarkfilemtch_{curbufnr}.'\|'.leader.escape(a:fname,g:netrw_markfileesc).trailer
5217
5218        else
5219            " remove filename from buffer's markfilelist
5220            call filter(s:netrwmarkfilelist_{curbufnr}, {_, v -> v !=# a:fname})
5221            if s:netrwmarkfilelist_{curbufnr} == []
5222                " local markfilelist is empty; remove it entirely
5223                call s:NetrwUnmarkList(curbufnr,curdir)
5224            else
5225                " rebuild match list to display markings correctly
5226                let s:netrwmarkfilemtch_{curbufnr} = ""
5227                let first = 1
5228                for fname in s:netrwmarkfilelist_{curbufnr}
5229                    let curtrailer = (fname =~ '\a$') ? word_boundary_trailer : fallback_trailer
5230
5231                    let match_str = leader.escape(fname, g:netrw_markfileesc).curtrailer
5232                    if first
5233                        let s:netrwmarkfilemtch_{curbufnr} = match_str
5234                    else
5235                        let s:netrwmarkfilemtch_{curbufnr} = s:netrwmarkfilemtch_{curbufnr}.'\|'.match_str
5236                    endif
5237                    let first = 0
5238                endfor
5239            endif
5240        endif
5241
5242    else
5243        " initialize new markfilelist
5244        let s:netrwmarkfilelist_{curbufnr} = []
5245        call add(s:netrwmarkfilelist_{curbufnr},substitute(a:fname,'[|@]$','',''))
5246
5247        " build initial markfile matching pattern
5248        let s:netrwmarkfilemtch_{curbufnr} = leader.escape(a:fname,g:netrw_markfileesc).trailer
5249    endif
5250
5251    " handle global markfilelist
5252    if exists("s:netrwmarkfilelist")
5253        let dname = netrw#fs#ComposePath(b:netrw_curdir,a:fname)
5254        if index(s:netrwmarkfilelist,dname) == -1
5255            " append new filename to global markfilelist
5256            call add(s:netrwmarkfilelist,netrw#fs#ComposePath(b:netrw_curdir,a:fname))
5257        else
5258            " remove new filename from global markfilelist
5259            call filter(s:netrwmarkfilelist, {_, v -> v !=# dname})
5260            if s:netrwmarkfilelist == []
5261                unlet s:netrwmarkfilelist
5262            endif
5263        endif
5264    else
5265        " initialize new global-directory markfilelist
5266        let s:netrwmarkfilelist = []
5267        call add(s:netrwmarkfilelist,netrw#fs#ComposePath(b:netrw_curdir,a:fname))
5268    endif
5269
5270    " set up 2match'ing to netrwmarkfilemtch_# list
5271    if has("syntax") && exists("g:syntax_on") && g:syntax_on
5272        if exists("s:netrwmarkfilemtch_{curbufnr}") && s:netrwmarkfilemtch_{curbufnr} != ""
5273            if exists("g:did_drchip_netrwlist_syntax")
5274                exe "2match netrwMarkFile /".s:netrwmarkfilemtch_{curbufnr}."/"
5275            endif
5276        else
5277            2match none
5278        endif
5279    endif
5280    let @@= ykeep
5281endfunction
5282
5283" s:NetrwMarkFileArgList: ma: move the marked file list to the argument list (tomflist=0) {{{2
5284"                         mA: move the argument list to marked file list     (tomflist=1)
5285"                            Uses the global marked file list
5286function s:NetrwMarkFileArgList(islocal,tomflist)
5287    let svpos    = winsaveview()
5288    let curdir   = s:NetrwGetCurdir(a:islocal)
5289    let curbufnr = bufnr("%")
5290
5291    if a:tomflist
5292        " mA: move argument list to marked file list
5293        while argc()
5294            let fname= argv(0)
5295            exe "argdel ".fnameescape(fname)
5296            call s:NetrwMarkFile(a:islocal,fname)
5297        endwhile
5298
5299    else
5300        " ma: move marked file list to argument list
5301        if exists("s:netrwmarkfilelist")
5302
5303            " for every filename in the marked list
5304            for fname in s:netrwmarkfilelist
5305                exe "argadd ".fnameescape(fname)
5306            endfor      " for every file in the marked list
5307
5308            " unmark list and refresh
5309            call s:NetrwUnmarkList(curbufnr,curdir)
5310            NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
5311            NetrwKeepj call winrestview(svpos)
5312        endif
5313    endif
5314endfunction
5315
5316" s:NetrwMarkFileCompress: (invoked by mz) This function is used to {{{2
5317"                          compress/decompress files using the programs
5318"                          in g:netrw_compress and g:netrw_uncompress,
5319"                          using g:netrw_compress_suffix to know which to
5320"                          do.  By default:
5321"                            g:netrw_compress        = "gzip"
5322"                            g:netrw_decompress      = { ".gz" : "gunzip" , ".bz2" : "bunzip2" , ".zip" : "unzip" , ".tar" : "tar -xf", ".xz" : "unxz"}
5323function s:NetrwMarkFileCompress(islocal)
5324    let svpos    = winsaveview()
5325    let curdir   = s:NetrwGetCurdir(a:islocal)
5326    let curbufnr = bufnr("%")
5327
5328    " sanity check
5329    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5330        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5331        return
5332    endif
5333
5334    if exists("s:netrwmarkfilelist_{curbufnr}") && exists("g:netrw_compress") && exists("g:netrw_decompress")
5335
5336        " for every filename in the marked list
5337        for fname in s:netrwmarkfilelist_{curbufnr}
5338            let sfx= substitute(fname,'^.\{-}\(\.[[:alnum:]]\+\)$','\1','')
5339            if exists("g:netrw_decompress['".sfx."']")
5340                " fname has a suffix indicating that its compressed; apply associated decompression routine
5341                let exe= g:netrw_decompress[sfx]
5342                let exe= netrw#fs#WinPath(exe)
5343                if a:islocal
5344                    if g:netrw_keepdir
5345                        let fname= netrw#os#Escape(netrw#fs#ComposePath(curdir,fname))
5346                    else
5347                        let fname= netrw#os#Escape(fname)
5348                    endif
5349                    call system(exe." ".fname)
5350                    if v:shell_error
5351                        call netrw#msg#Notify('WARNING', printf('unable to apply<%s> to file<%s>', exe, fname))
5352                    endif
5353                else
5354                    let fname= netrw#os#Escape(b:netrw_curdir.fname,1)
5355                    NetrwKeepj call s:RemoteSystem(exe." ".fname)
5356                endif
5357
5358            endif
5359            unlet sfx
5360
5361            if exists("exe")
5362                unlet exe
5363            elseif a:islocal
5364                " fname not a compressed file, so compress it
5365                call system(netrw#fs#WinPath(g:netrw_compress)." ".netrw#os#Escape(netrw#fs#ComposePath(b:netrw_curdir,fname)))
5366                if v:shell_error
5367                    call netrw#msg#Notify('WARNING', printf('consider setting g:netrw_compress<%s> to something that works', g:netrw_compress))
5368                endif
5369            else
5370                " fname not a compressed file, so compress it
5371                NetrwKeepj call s:RemoteSystem(netrw#fs#WinPath(g:netrw_compress)." ".netrw#os#Escape(fname))
5372            endif
5373        endfor       " for every file in the marked list
5374
5375        call s:NetrwUnmarkList(curbufnr,curdir)
5376        NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
5377        NetrwKeepj call winrestview(svpos)
5378    endif
5379endfunction
5380
5381" s:NetrwMarkFileCopy: (invoked by mc) copy marked files to target {{{2
5382"                      If no marked files, then set up directory as the
5383"                      target.  Currently does not support copying entire
5384"                      directories.  Uses the local-buffer marked file list.
5385"                      Returns 1=success  (used by NetrwMarkFileMove())
5386"                              0=failure
5387function s:NetrwMarkFileCopy(islocal,...)
5388
5389    let curdir   = s:NetrwGetCurdir(a:islocal)
5390    let curbufnr = bufnr("%")
5391    if !exists("b:netrw_curdir")
5392        let b:netrw_curdir= curdir
5393    endif
5394
5395    " sanity check
5396    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5397        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5398        return 0
5399    endif
5400
5401    if !exists("s:netrwmftgt")
5402        call netrw#msg#Notify('ERROR', 'your marked file target is empty! (:help netrw-mt)')
5403        return 0
5404    endif
5405
5406    if a:islocal && s:netrwmftgt_islocal
5407        " Copy marked files, local directory to local directory
5408        if !executable(g:netrw_localcopycmd)
5409            call netrw#msg#Notify('ERROR', printf('g:netrw_localcopycmd<%s> not executable on your system, aborting', g:netrw_localcopycmd))
5410            return
5411        endif
5412
5413        " copy marked files while within the same directory (ie. allow renaming)
5414        if simplify(s:netrwmftgt."/") ==# simplify(b:netrw_curdir."/")
5415            " copy multiple marked files inside the same directory
5416            for oldname in s:netrwmarkfilelist_{curbufnr}
5417                call inputsave()
5418                let newname= input(printf("Copy %s to: ", oldname), oldname, 'file')
5419                call inputrestore()
5420
5421                if empty(newname)
5422                    return 0
5423                endif
5424
5425                let tgt = netrw#fs#ComposePath(s:netrwmftgt, newname)
5426                let oldname = netrw#fs#ComposePath(b:netrw_curdir, oldname)
5427                if tgt ==# oldname
5428                    continue
5429                endif
5430
5431                let ret = filecopy(oldname, tgt)
5432                if ret == v:false
5433                    call netrw#msg#Notify('ERROR', $'copy failed, unable to filecopy() <{oldname}> to <{tgt}>')
5434                    break
5435                endif
5436            endfor
5437            call s:NetrwUnmarkList(curbufnr,curdir)
5438            NetrwKeepj call s:NetrwRefreshDir(a:islocal, b:netrw_curdir)
5439            return ret
5440        else
5441            let args = []
5442            for arg in s:netrwmarkfilelist_{curbufnr}
5443                call add(args, netrw#fs#ComposePath(b:netrw_curdir, arg))
5444            endfor
5445            let tgt = s:netrwmftgt
5446        endif
5447
5448        let copycmd = g:netrw_localcopycmd
5449        let copycmdopt = g:netrw_localcopycmdopt
5450
5451        " on Windows, no builtin command supports copying multiple files at once
5452        " (powershell's Copy-Item cmdlet does but requires , as file separator)
5453        if len(s:netrwmarkfilelist_{curbufnr}) > 1 && has("win32") && !g:netrw_cygwin
5454            " copy multiple marked files
5455            for file in args
5456                let dest = netrw#fs#ComposePath(tgt, fnamemodify(file, ':t'))
5457                let ret = filecopy(file, dest)
5458                if ret == v:false
5459                    call netrw#msg#Notify('ERROR', $'copy failed, unable to filecopy() <{file}> to <{dest}>')
5460                    break
5461                endif
5462            endfor
5463            call s:NetrwUnmarkList(curbufnr,curdir)
5464            NetrwKeepj call s:NetrwRefreshDir(a:islocal, b:netrw_curdir)
5465            return ret
5466        endif
5467
5468        if len(args) == 1 && isdirectory(s:NetrwFile(args[0]))
5469            let copycmd = g:netrw_localcopydircmd
5470            let copycmdopt = g:netrw_localcopydircmdopt
5471            if has('win32') && g:netrw_localcopydircmd == "xcopy"
5472                " window's xcopy doesn't copy a directory to a target properly.  Instead, it copies a directory's
5473                " contents to a target.  One must append the source directory name to the target to get xcopy to
5474                " do the right thing.
5475                let tgt = netrw#fs#ComposePath(tgt, fnamemodify(simplify(netrw#fs#PathJoin(args[0],".")),":t"))
5476            endif
5477        endif
5478
5479        " prepare arguments for shell call
5480        let args = join(map(args,'netrw#os#Escape(v:val)'))
5481        let tgt = netrw#os#Escape(tgt)
5482
5483        " enforce noshellslash for system calls
5484        if exists('+shellslash') && &shellslash
5485            for var in ['copycmd', 'args', 'tgt']
5486                let {var} = substitute({var}, '/', '\', 'g')
5487            endfor
5488        endif
5489
5490        " shell call
5491        let shell_cmd = printf("%s %s %s %s", copycmd, copycmdopt, args, tgt)
5492        call system(shell_cmd)
5493        if v:shell_error != 0
5494            if exists("b:netrw_curdir") && b:netrw_curdir != getcwd() && g:netrw_keepdir
5495                call netrw#msg#Notify('ERROR', printf("copy failed; perhaps due to vim's current directory<%s> not matching netrw's (%s) (see :help netrw-cd)", getcwd(), b:netrw_curdir))
5496            else
5497                call netrw#msg#Notify('ERROR', printf("tried using g:netrw_localcopycmd<%s>; it doesn't work!", g:netrw_localcopycmd))
5498            endif
5499            return 0
5500        endif
5501
5502    elseif  a:islocal && !s:netrwmftgt_islocal
5503        " Copy marked files, local directory to remote directory
5504        NetrwKeepj call s:NetrwUpload(s:netrwmarkfilelist_{curbufnr},s:netrwmftgt)
5505
5506    elseif !a:islocal &&  s:netrwmftgt_islocal
5507        " Copy marked files, remote directory to local directory
5508        NetrwKeepj call netrw#Obtain(a:islocal,s:netrwmarkfilelist_{curbufnr},s:netrwmftgt)
5509
5510    elseif !a:islocal && !s:netrwmftgt_islocal
5511        " Copy marked files, remote directory to remote directory
5512        let curdir = getcwd()
5513        let tmpdir = s:GetTempfile("")
5514        if tmpdir !~ '/'
5515            let tmpdir= curdir."/".tmpdir
5516        endif
5517        call mkdir(tmpdir)
5518        if isdirectory(s:NetrwFile(tmpdir))
5519            if s:NetrwLcd(tmpdir)
5520                return
5521            endif
5522            NetrwKeepj call netrw#Obtain(a:islocal,s:netrwmarkfilelist_{curbufnr},tmpdir)
5523            let localfiles= map(deepcopy(s:netrwmarkfilelist_{curbufnr}),'substitute(v:val,"^.*/","","")')
5524            NetrwKeepj call s:NetrwUpload(localfiles,s:netrwmftgt)
5525            if getcwd() == tmpdir
5526                for fname in s:netrwmarkfilelist_{curbufnr}
5527                    call netrw#fs#Remove(fname)
5528                endfor
5529                if s:NetrwLcd(curdir)
5530                    return
5531                endif
5532                if delete(tmpdir,"d")
5533                    call netrw#msg#Notify('ERROR', printf('unable to delete directory <%s>!', tmpdir))
5534                endif
5535            else
5536                if s:NetrwLcd(curdir)
5537                    return
5538                endif
5539            endif
5540        endif
5541    endif
5542
5543    " -------
5544    " cleanup
5545    " -------
5546    " remove markings from local buffer
5547    call s:NetrwUnmarkList(curbufnr,curdir)                   " remove markings from local buffer
5548    " see s:LocalFastBrowser() for g:netrw_fastbrowse interpretation (refreshing done for both slow and medium)
5549    if g:netrw_fastbrowse <= 1
5550        NetrwKeepj call s:LocalBrowseRefresh()
5551    else
5552        " refresh local and targets for fast browsing
5553        " remove markings from local buffer
5554        NetrwKeepj call s:NetrwUnmarkList(curbufnr,curdir)
5555
5556        " refresh buffers
5557        if s:netrwmftgt_islocal
5558            NetrwKeepj call s:NetrwRefreshDir(s:netrwmftgt_islocal,s:netrwmftgt)
5559        endif
5560        if a:islocal && s:netrwmftgt != curdir
5561            NetrwKeepj call s:NetrwRefreshDir(a:islocal,curdir)
5562        endif
5563    endif
5564
5565    return 1
5566endfunction
5567
5568" s:NetrwMarkFileDiff: (invoked by md) This function is used to {{{2
5569"                      invoke vim's diff mode on the marked files.
5570"                      Either two or three files can be so handled.
5571"                      Uses the global marked file list.
5572function s:NetrwMarkFileDiff(islocal)
5573    let curbufnr= bufnr("%")
5574
5575    " sanity check
5576    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5577        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5578        return
5579    endif
5580    let curdir= s:NetrwGetCurdir(a:islocal)
5581
5582    if exists("s:netrwmarkfilelist_{".curbufnr."}")
5583        let cnt    = 0
5584        for fname in s:netrwmarkfilelist
5585            let cnt= cnt + 1
5586            if cnt == 1
5587                exe "NetrwKeepj e ".fnameescape(fname)
5588                diffthis
5589            elseif cnt == 2 || cnt == 3
5590                below vsplit
5591                exe "NetrwKeepj e ".fnameescape(fname)
5592                diffthis
5593            else
5594                break
5595            endif
5596        endfor
5597        call s:NetrwUnmarkList(curbufnr,curdir)
5598    endif
5599
5600endfunction
5601
5602" s:NetrwMarkFileEdit: (invoked by me) put marked files on arg list and start editing them {{{2
5603"                       Uses global markfilelist
5604function s:NetrwMarkFileEdit(islocal)
5605
5606    let curdir   = s:NetrwGetCurdir(a:islocal)
5607    let curbufnr = bufnr("%")
5608
5609    " sanity check
5610    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5611        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5612        return
5613    endif
5614
5615    if exists("s:netrwmarkfilelist_{curbufnr}")
5616        call s:SetRexDir(a:islocal,curdir)
5617        let flist= join(map(deepcopy(s:netrwmarkfilelist), "fnameescape(v:val)"))
5618        " unmark markedfile list
5619        "   call s:NetrwUnmarkList(curbufnr,curdir)
5620        call s:NetrwUnmarkAll()
5621        exe "sil args ".flist
5622    endif
5623    echo "(use :bn, :bp to navigate files; :Rex to return)"
5624
5625endfunction
5626
5627" s:NetrwMarkFileQFEL: convert a quickfix-error or location list into a marked file list {{{2
5628function s:NetrwMarkFileQFEL(islocal,qfel)
5629    call s:NetrwUnmarkAll()
5630    let curbufnr= bufnr("%")
5631
5632    if !empty(a:qfel)
5633        for entry in a:qfel
5634            let bufnmbr= entry["bufnr"]
5635            if !exists("s:netrwmarkfilelist_{curbufnr}")
5636                call s:NetrwMarkFile(a:islocal,bufname(bufnmbr))
5637            elseif index(s:netrwmarkfilelist_{curbufnr},bufname(bufnmbr)) == -1
5638                " s:NetrwMarkFile will remove duplicate entries from the marked file list.
5639                " So, this test lets two or more hits on the same pattern to be ignored.
5640                call s:NetrwMarkFile(a:islocal,bufname(bufnmbr))
5641            else
5642            endif
5643        endfor
5644        echo "(use me to edit marked files)"
5645    else
5646        call netrw#msg#Notify('WARNING', "can't convert quickfix error list; its empty!")
5647    endif
5648
5649endfunction
5650
5651" s:NetrwMarkFileExe: (invoked by mx and mX) execute arbitrary system command on marked files {{{2
5652"                     mx enbloc=0: Uses the local marked-file list, applies command to each file individually
5653"                     mX enbloc=1: Uses the global marked-file list, applies command to entire list
5654function s:NetrwMarkFileExe(islocal,enbloc)
5655    let svpos    = winsaveview()
5656    let curdir   = s:NetrwGetCurdir(a:islocal)
5657    let curbufnr = bufnr("%")
5658
5659    if a:enbloc == 0
5660        " individually apply command to files, one at a time
5661        " sanity check
5662        if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5663            call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5664            return
5665        endif
5666
5667        if exists("s:netrwmarkfilelist_{curbufnr}")
5668            " get the command
5669            call inputsave()
5670            let cmd= input("Enter command: ","","file")
5671            call inputrestore()
5672            if cmd == ""
5673                return
5674            endif
5675
5676            " apply command to marked files, individually.  Substitute: filename -> %
5677            " If no %, then append a space and the filename to the command
5678            for fname in s:netrwmarkfilelist_{curbufnr}
5679                if a:islocal
5680                    if g:netrw_keepdir
5681                        let fname= netrw#os#Escape(netrw#fs#WinPath(netrw#fs#ComposePath(curdir,fname)))
5682                    else
5683                        let fname= netrw#os#Escape(netrw#fs#WinPath(fname))
5684                    endif
5685                else
5686                    let fname= netrw#os#Escape(netrw#fs#WinPath(b:netrw_curdir.fname))
5687                endif
5688                if cmd =~ '%'
5689                    let xcmd= substitute(cmd,'%',fname,'g')
5690                else
5691                    let xcmd= cmd.' '.fname
5692                endif
5693                if a:islocal
5694                    let ret= system(xcmd)
5695                else
5696                    let ret= s:RemoteSystem(xcmd)
5697                endif
5698                if v:shell_error < 0
5699                    call netrw#msg#Notify('ERROR', printf('command<%s> failed, aborting', xcmd))
5700                    break
5701                else
5702                    if ret !=# ''
5703                        echo "\n"
5704                        " skip trailing new line
5705                        echo ret[0:-2]
5706                    else
5707                        echo ret
5708                    endif
5709                endif
5710            endfor
5711
5712            " unmark marked file list
5713            call s:NetrwUnmarkList(curbufnr,curdir)
5714
5715            " refresh the listing
5716            NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
5717            NetrwKeepj call winrestview(svpos)
5718        else
5719            call netrw#msg#Notify('ERROR', 'no files marked!')
5720        endif
5721
5722    else " apply command to global list of files, en bloc
5723
5724        call inputsave()
5725        let cmd= input("Enter command: ","","file")
5726        call inputrestore()
5727        if cmd == ""
5728            return
5729        endif
5730        if cmd =~ '%'
5731            let cmd= substitute(cmd,'%',join(map(s:netrwmarkfilelist,'netrw#os#Escape(v:val)'),' '),'g')
5732        else
5733            let cmd= cmd.' '.join(map(s:netrwmarkfilelist,'netrw#os#Escape(v:val)'),' ')
5734        endif
5735        if a:islocal
5736            call system(cmd)
5737            if v:shell_error < 0
5738                call netrw#msg#Notify('ERROR', printf('command<%s> failed, aborting',xcmd))
5739            endif
5740        else
5741            let ret= s:RemoteSystem(cmd)
5742        endif
5743        call s:NetrwUnmarkAll()
5744
5745        " refresh the listing
5746        NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
5747        NetrwKeepj call winrestview(svpos)
5748
5749    endif
5750endfunction
5751
5752" s:NetrwMarkHideSfx: (invoked by mh) (un)hide files having same suffix
5753"                  as the marked file(s) (toggles suffix presence)
5754"                  Uses the local marked file list.
5755function s:NetrwMarkHideSfx(islocal)
5756    let svpos    = winsaveview()
5757    let curbufnr = bufnr("%")
5758
5759    " s:netrwmarkfilelist_{curbufnr}: the List of marked files
5760    if exists("s:netrwmarkfilelist_{curbufnr}")
5761
5762        for fname in s:netrwmarkfilelist_{curbufnr}
5763            " construct suffix pattern
5764            if fname =~ '\.'
5765                let sfxpat= "^.*".substitute(fname,'^.*\(\.[^. ]\+\)$','\1','')
5766            else
5767                let sfxpat= '^\%(\%(\.\)\@!.\)*$'
5768            endif
5769            " determine if its in the hiding list or not
5770            let inhidelist= 0
5771            if g:netrw_list_hide != ""
5772                let itemnum = 0
5773                let hidelist= split(g:netrw_list_hide,',')
5774                for hidepat in hidelist
5775                    if sfxpat == hidepat
5776                        let inhidelist= 1
5777                        break
5778                    endif
5779                    let itemnum= itemnum + 1
5780                endfor
5781            endif
5782            if inhidelist
5783                " remove sfxpat from list
5784                call remove(hidelist,itemnum)
5785                let g:netrw_list_hide= join(hidelist,",")
5786            elseif g:netrw_list_hide != ""
5787                " append sfxpat to non-empty list
5788                let g:netrw_list_hide= g:netrw_list_hide.",".sfxpat
5789            else
5790                " set hiding list to sfxpat
5791                let g:netrw_list_hide= sfxpat
5792            endif
5793        endfor
5794
5795        " refresh the listing
5796        NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
5797        NetrwKeepj call winrestview(svpos)
5798    else
5799        call netrw#msg#Notify('ERROR', 'no files marked!')
5800    endif
5801endfunction
5802
5803" s:NetrwMarkFileVimCmd: (invoked by mv) execute arbitrary vim command on marked files, one at a time {{{2
5804"                     Uses the local marked-file list.
5805function s:NetrwMarkFileVimCmd(islocal)
5806    let svpos    = winsaveview()
5807    let curdir   = s:NetrwGetCurdir(a:islocal)
5808    let curbufnr = bufnr("%")
5809
5810    " sanity check
5811    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5812        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5813        return
5814    endif
5815
5816    if exists("s:netrwmarkfilelist_{curbufnr}")
5817        " get the command
5818        call inputsave()
5819        let cmd= input("Enter vim command: ","","file")
5820        call inputrestore()
5821        if cmd == ""
5822            return
5823        endif
5824
5825        " apply command to marked files.  Substitute: filename -> %
5826        " If no %, then append a space and the filename to the command
5827        for fname in s:netrwmarkfilelist_{curbufnr}
5828            if a:islocal
5829                1split
5830                exe "sil! NetrwKeepj keepalt e ".fnameescape(fname)
5831                exe cmd
5832                exe "sil! keepalt wq!"
5833            else
5834                echo "sorry, \"mv\" not supported yet for remote files"
5835            endif
5836        endfor
5837
5838        " unmark marked file list
5839        call s:NetrwUnmarkList(curbufnr,curdir)
5840
5841        " refresh the listing
5842        NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
5843        NetrwKeepj call winrestview(svpos)
5844    else
5845        call netrw#msg#Notify('ERROR', 'no files marked!')
5846    endif
5847endfunction
5848
5849" s:NetrwMarkFileGrep: (invoked by mg) This function applies vimgrep to marked files {{{2
5850"                     Uses the global markfilelist
5851function s:NetrwMarkFileGrep(islocal)
5852    let svpos    = winsaveview()
5853    let curbufnr = bufnr("%")
5854    let curdir   = s:NetrwGetCurdir(a:islocal)
5855
5856    if exists("s:netrwmarkfilelist")
5857        let netrwmarkfilelist= join(map(deepcopy(s:netrwmarkfilelist), "fnameescape(v:val)"))
5858        call s:NetrwUnmarkAll()
5859    else
5860        let netrwmarkfilelist= "*"
5861    endif
5862
5863    " ask user for pattern
5864    call inputsave()
5865    let pat= input("Enter pattern: ","")
5866    call inputrestore()
5867    let patbang = ""
5868    if pat =~ '^!'
5869        let patbang = "!"
5870        let pat     = strpart(pat,2)
5871    endif
5872    if pat =~ '^\i'
5873        let pat    = escape(pat,'/')
5874        let pat    = '/'.pat.'/'
5875    else
5876        let nonisi = pat[0]
5877    endif
5878
5879    " use vimgrep for both local and remote
5880    try
5881        exe "NetrwKeepj noautocmd vimgrep".patbang." ".pat." ".netrwmarkfilelist
5882    catch /^Vim\%((\a\+)\)\=:E480/
5883        call netrw#msg#Notify('WARNING', printf('no match with pattern<%s>', pat))
5884        return
5885    endtry
5886    echo "(use :cn, :cp to navigate, :Rex to return)"
5887
5888    2match none
5889    NetrwKeepj call winrestview(svpos)
5890
5891    if exists("nonisi")
5892        " original, user-supplied pattern did not begin with a character from isident
5893        if pat =~# nonisi.'j$\|'.nonisi.'gj$\|'.nonisi.'jg$'
5894            call s:NetrwMarkFileQFEL(a:islocal,getqflist())
5895        endif
5896    endif
5897
5898endfunction
5899
5900" s:NetrwMarkFileMove: (invoked by mm) execute arbitrary command on marked files, one at a time {{{2
5901"                      uses the global marked file list
5902"                      s:netrwmfloc= 0: target directory is remote
5903"                                  = 1: target directory is local
5904function s:NetrwMarkFileMove(islocal)
5905    let curdir   = s:NetrwGetCurdir(a:islocal)
5906    let curbufnr = bufnr("%")
5907
5908    " sanity check
5909    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
5910        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
5911        return
5912    endif
5913
5914    if !exists("s:netrwmftgt")
5915        call netrw#msg#Notify('ERROR', 'your marked file target is empty! (:help netrw-mt)')
5916        return 0
5917    endif
5918
5919    if      a:islocal &&  s:netrwmftgt_islocal
5920        " move: local -> local
5921        if !executable(g:netrw_localmovecmd)
5922            call netrw#msg#Notify('ERROR', printf('g:netrw_localmovecmd<%s> not executable on your system, aborting', g:netrw_localmovecmd))
5923            return
5924        endif
5925
5926        let tgt = netrw#os#Escape(s:netrwmftgt)
5927        if has("win32") && !g:netrw_cygwin && g:netrw_localmovecmd =~ '\s' && g:netrw_localmovecmdopt == ""
5928            let movecmd     = substitute(g:netrw_localmovecmd,'\s.*$','','')
5929            let movecmdargs = substitute(g:netrw_localmovecmd,'^.\{-}\(\s.*\)$','\1','')
5930        else
5931            let movecmd = g:netrw_localmovecmd
5932            let movecmdargs = g:netrw_localmovecmdopt
5933        endif
5934
5935        " build args list
5936        let args = []
5937        for fname in s:netrwmarkfilelist_{curbufnr}
5938            if g:netrw_keepdir
5939                " Jul 19, 2022: fixing file move when g:netrw_keepdir is 1
5940                let fname= netrw#fs#ComposePath(b:netrw_curdir, fname)
5941            endif
5942            call add(args, netrw#os#Escape(fname))
5943        endfor
5944
5945        " enforce noshellslash for system calls
5946        if exists('+shellslash') && &shellslash
5947            let tgt = substitute(tgt, '/', '\', 'g')
5948            call map(args, "substitute(v:val, '/', '\\', 'g')")
5949        endif
5950
5951        for fname in args
5952            let shell_cmd = printf("%s %s %s %s", movecmd, movecmdargs, fname, tgt)
5953            let ret= system(shell_cmd)
5954            if v:shell_error != 0
5955                if exists("b:netrw_curdir") && b:netrw_curdir != getcwd() && !g:netrw_keepdir
5956                    call netrw#msg#Notify('ERROR', printf("move failed; perhaps due to vim's current directory<%s> not matching netrw's (%s) (see :help netrw-cd)", getcwd(), b:netrw_curdir))
5957                else
5958                    call netrw#msg#Notify('ERROR', printf("tried using g:netrw_localmovecmd<%s>; it doesn't work!", g:netrw_localmovecmd))
5959                endif
5960                break
5961            endif
5962        endfor
5963
5964    elseif  a:islocal && !s:netrwmftgt_islocal
5965        " move: local -> remote
5966        let mflist= s:netrwmarkfilelist_{curbufnr}
5967        NetrwKeepj call s:NetrwMarkFileCopy(a:islocal)
5968        for fname in mflist
5969            let barefname = substitute(fname,'^\(.*/\)\(.\{-}\)$','\2','')
5970            let ok        = s:NetrwLocalRmFile(b:netrw_curdir,barefname,1)
5971        endfor
5972        unlet mflist
5973
5974    elseif !a:islocal &&  s:netrwmftgt_islocal
5975        " move: remote -> local
5976        let mflist= s:netrwmarkfilelist_{curbufnr}
5977        NetrwKeepj call s:NetrwMarkFileCopy(a:islocal)
5978        for fname in mflist
5979            let barefname = substitute(fname,'^\(.*/\)\(.\{-}\)$','\2','')
5980            let ok        = s:NetrwRemoteRmFile(b:netrw_curdir,barefname,1)
5981        endfor
5982        unlet mflist
5983
5984    elseif !a:islocal && !s:netrwmftgt_islocal
5985        " move: remote -> remote
5986        let mflist= s:netrwmarkfilelist_{curbufnr}
5987        NetrwKeepj call s:NetrwMarkFileCopy(a:islocal)
5988        for fname in mflist
5989            let barefname = substitute(fname,'^\(.*/\)\(.\{-}\)$','\2','')
5990            let ok        = s:NetrwRemoteRmFile(b:netrw_curdir,barefname,1)
5991        endfor
5992        unlet mflist
5993    endif
5994
5995    " -------
5996    " cleanup
5997    " -------
5998
5999    " remove markings from local buffer
6000    call s:NetrwUnmarkList(curbufnr,curdir)                   " remove markings from local buffer
6001
6002    " refresh buffers
6003    if !s:netrwmftgt_islocal
6004        NetrwKeepj call s:NetrwRefreshDir(s:netrwmftgt_islocal,s:netrwmftgt)
6005    endif
6006    if a:islocal
6007        NetrwKeepj call s:NetrwRefreshDir(a:islocal,b:netrw_curdir)
6008    endif
6009    if g:netrw_fastbrowse <= 1
6010        NetrwKeepj call s:LocalBrowseRefresh()
6011    endif
6012
6013endfunction
6014
6015" s:NetrwMarkFileRegexp: (invoked by mr) This function is used to mark {{{2
6016"                        files when given a regexp (for which a prompt is
6017"                        issued) (matches to name of files).
6018function s:NetrwMarkFileRegexp(islocal)
6019
6020    " get the regular expression
6021    call inputsave()
6022    let regexp= input("Enter regexp: ","","file")
6023    call inputrestore()
6024
6025    if a:islocal
6026        let curdir= s:NetrwGetCurdir(a:islocal)
6027        " get the matching list of files using local glob()
6028        let dirname = escape(b:netrw_curdir,g:netrw_glob_escape)
6029        let filelist= glob(netrw#fs#ComposePath(dirname,regexp),0,1,1)
6030
6031        " mark the list of files
6032        for fname in filelist
6033            if fname =~ '^'.fnameescape(curdir)
6034                NetrwKeepj call s:NetrwMarkFile(a:islocal,substitute(fname,'^'.fnameescape(curdir).'/','',''))
6035            else
6036                NetrwKeepj call s:NetrwMarkFile(a:islocal,substitute(fname,'^.*/','',''))
6037            endif
6038        endfor
6039
6040    else
6041
6042        " convert displayed listing into a filelist
6043        let eikeep = &ei
6044        let areg   = @a
6045        sil NetrwKeepj %y a
6046        setl ei=all ma
6047        1split
6048        NetrwKeepj call s:NetrwEnew()
6049        NetrwKeepj call s:NetrwOptionsSafe(a:islocal)
6050        sil NetrwKeepj norm! "ap
6051        NetrwKeepj 2
6052        let bannercnt= search('^" =====','W')
6053        exe "sil NetrwKeepj 1,".bannercnt."d"
6054        setl bt=nofile
6055        if     g:netrw_liststyle == s:LONGLIST
6056            sil NetrwKeepj %s/\s\{2,}\S.*$//e
6057            call histdel("/",-1)
6058        elseif g:netrw_liststyle == s:WIDELIST
6059            sil NetrwKeepj %s/\s\{2,}/\r/ge
6060            call histdel("/",-1)
6061        elseif g:netrw_liststyle == s:TREELIST
6062            exe 'sil NetrwKeepj %s/^'.s:treedepthstring.' //e'
6063            sil! NetrwKeepj g/^ .*$/d
6064            call histdel("/",-1)
6065            call histdel("/",-1)
6066        endif
6067        " convert regexp into the more usual glob-style format
6068        let regexp= substitute(regexp,'\*','.*','g')
6069        exe "sil! NetrwKeepj v/".escape(regexp,'/')."/d"
6070        call histdel("/",-1)
6071        let filelist= getline(1,line("$"))
6072        q!
6073        for filename in filelist
6074            NetrwKeepj call s:NetrwMarkFile(a:islocal,substitute(filename,'^.*/','',''))
6075        endfor
6076        unlet filelist
6077        let @a  = areg
6078        let &ei = eikeep
6079    endif
6080    echo "  (use me to edit marked files)"
6081
6082endfunction
6083
6084" s:NetrwMarkFileSource: (invoked by ms) This function sources marked files {{{2
6085"                        Uses the local marked file list.
6086function s:NetrwMarkFileSource(islocal)
6087    let curbufnr= bufnr("%")
6088
6089    " sanity check
6090    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
6091        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
6092        return
6093    endif
6094    let curdir= s:NetrwGetCurdir(a:islocal)
6095
6096    if exists("s:netrwmarkfilelist_{curbufnr}")
6097        let netrwmarkfilelist = s:netrwmarkfilelist_{bufnr("%")}
6098        call s:NetrwUnmarkList(curbufnr,curdir)
6099        for fname in netrwmarkfilelist
6100            if a:islocal
6101                if g:netrw_keepdir
6102                    let fname= netrw#fs#ComposePath(curdir,fname)
6103                endif
6104            else
6105                let fname= curdir.fname
6106            endif
6107            " the autocmds will handle sourcing both local and remote files
6108            exe "so ".fnameescape(fname)
6109        endfor
6110        2match none
6111    endif
6112endfunction
6113
6114" s:NetrwMarkFileTag: (invoked by mT) This function applies g:netrw_ctags to marked files {{{2
6115"                     Uses the global markfilelist
6116function s:NetrwMarkFileTag(islocal)
6117    let svpos    = winsaveview()
6118    let curdir   = s:NetrwGetCurdir(a:islocal)
6119    let curbufnr = bufnr("%")
6120
6121    " sanity check
6122    if !exists("s:netrwmarkfilelist_{curbufnr}") || empty(s:netrwmarkfilelist_{curbufnr})
6123        call netrw#msg#Notify('ERROR', 'there are no marked files in this window (:help netrw-mf)')
6124        return
6125    endif
6126
6127    if exists("s:netrwmarkfilelist")
6128        let netrwmarkfilelist= join(map(deepcopy(s:netrwmarkfilelist), "netrw#os#Escape(v:val,".!a:islocal.")"))
6129        call s:NetrwUnmarkAll()
6130
6131        if a:islocal
6132
6133            call system(g:netrw_ctags." ".netrwmarkfilelist)
6134            if v:shell_error
6135                call netrw#msg#Notify('ERROR', printf('g:netrw_ctags<%s> is not executable!', g:netrw_ctags))
6136            endif
6137
6138        else
6139            let cmd   = s:RemoteSystem(g:netrw_ctags." ".netrwmarkfilelist)
6140            call netrw#Obtain(a:islocal,"tags")
6141            let curdir= b:netrw_curdir
6142            1split
6143            NetrwKeepj e tags
6144            let path= substitute(curdir,'^\(.*\)/[^/]*$','\1/','')
6145            exe 'NetrwKeepj %s/\t\(\S\+\)\t/\t'.escape(path,"/\n\r\\").'\1\t/e'
6146            call histdel("/",-1)
6147            wq!
6148        endif
6149        2match none
6150        call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6151        call winrestview(svpos)
6152    endif
6153endfunction
6154
6155" s:NetrwMarkFileTgt:  (invoked by mt) This function sets up a marked file target {{{2
6156"   Sets up two variables,
6157"     s:netrwmftgt         : holds the target directory
6158"     s:netrwmftgt_islocal : 0=target directory is remote
6159"                            1=target directory is local
6160function s:NetrwMarkFileTgt(islocal)
6161    let svpos  = winsaveview()
6162    let curdir = s:NetrwGetCurdir(a:islocal)
6163    let hadtgt = exists("s:netrwmftgt")
6164    if !exists("w:netrw_bannercnt")
6165        let w:netrw_bannercnt= b:netrw_bannercnt
6166    endif
6167
6168    " set up target
6169    if line(".") < w:netrw_bannercnt
6170        " if cursor in banner region, use b:netrw_curdir for the target unless its already the target
6171        if exists("s:netrwmftgt") && exists("s:netrwmftgt_islocal") && s:netrwmftgt == b:netrw_curdir
6172            unlet s:netrwmftgt s:netrwmftgt_islocal
6173            if g:netrw_fastbrowse <= 1
6174                call s:LocalBrowseRefresh()
6175            endif
6176            call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6177            call winrestview(svpos)
6178            return
6179        else
6180            let s:netrwmftgt= b:netrw_curdir
6181        endif
6182
6183    else
6184        " get word under cursor.
6185        "  * If directory, use it for the target.
6186        "  * If file, use b:netrw_curdir for the target
6187        let curword= s:NetrwGetWord()
6188        let tgtdir = netrw#fs#ComposePath(curdir,curword)
6189        if a:islocal && isdirectory(s:NetrwFile(tgtdir))
6190            let s:netrwmftgt = tgtdir
6191        elseif !a:islocal && tgtdir =~ '/$'
6192            let s:netrwmftgt = tgtdir
6193        else
6194            let s:netrwmftgt = curdir
6195        endif
6196    endif
6197    if a:islocal
6198        " simplify the target (eg. /abc/def/../ghi -> /abc/ghi)
6199        let s:netrwmftgt= simplify(s:netrwmftgt)
6200    endif
6201    if g:netrw_cygwin
6202        let s:netrwmftgt= substitute(system("cygpath ".netrw#os#Escape(s:netrwmftgt)),'\n$','','')
6203        let s:netrwmftgt= substitute(s:netrwmftgt,'\n$','','')
6204    endif
6205    let s:netrwmftgt_islocal= a:islocal
6206
6207    " need to do refresh so that the banner will be updated
6208    "  s:LocalBrowseRefresh handles all local-browsing buffers when not fast browsing
6209    if g:netrw_fastbrowse <= 1
6210        call s:LocalBrowseRefresh()
6211    endif
6212    "  call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6213    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
6214        call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,w:netrw_treetop,0))
6215    else
6216        call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6217    endif
6218    call winrestview(svpos)
6219    if !hadtgt
6220        sil! NetrwKeepj norm! j
6221    endif
6222endfunction
6223
6224" s:NetrwGetCurdir: gets current directory and sets up b:netrw_curdir if necessary {{{2
6225function s:NetrwGetCurdir(islocal)
6226
6227    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
6228        let b:netrw_curdir = s:NetrwTreePath(w:netrw_treetop)
6229    elseif !exists("b:netrw_curdir")
6230        let b:netrw_curdir= getcwd()
6231    endif
6232
6233    if b:netrw_curdir !~ '\<\a\{3,}://'
6234        let curdir= b:netrw_curdir
6235        if g:netrw_keepdir == 0
6236            call s:NetrwLcd(curdir)
6237        endif
6238    endif
6239
6240    return b:netrw_curdir
6241endfunction
6242
6243" s:NetrwOpenFile: query user for a filename and open it {{{2
6244function s:NetrwOpenFile(islocal)
6245    call inputsave()
6246    let fname = input("Enter filename: ")
6247    call inputrestore()
6248
6249    if empty(fname)
6250        return
6251    endif
6252
6253    " save position for benefit of Rexplore
6254    let s:rexposn_{bufnr("%")}= winsaveview()
6255
6256    execute "NetrwKeepj e " . fnameescape(!isabsolutepath(fname)
6257                \ ? netrw#fs#ComposePath(b:netrw_curdir, fname)
6258                \ : fname)
6259endfunction
6260
6261" netrw#Shrink: shrinks/expands a netrw or Lexplorer window {{{2
6262"               For the mapping to this function be made via
6263"               netrwPlugin, you'll need to have had
6264"               g:netrw_usetab set to non-zero.
6265function netrw#Shrink()
6266    let curwin  = winnr()
6267    let wiwkeep = &wiw
6268    set wiw=1
6269
6270    if &ft == "netrw"
6271        if winwidth(0) > g:netrw_wiw
6272            let t:netrw_winwidth= winwidth(0)
6273            exe "vert resize ".g:netrw_wiw
6274            wincmd l
6275            if winnr() == curwin
6276                wincmd h
6277            endif
6278        else
6279            exe "vert resize ".t:netrw_winwidth
6280        endif
6281
6282    elseif exists("t:netrw_lexbufnr")
6283        exe bufwinnr(t:netrw_lexbufnr)."wincmd w"
6284        if     winwidth(bufwinnr(t:netrw_lexbufnr)) >  g:netrw_wiw
6285            let t:netrw_winwidth= winwidth(0)
6286            exe "vert resize ".g:netrw_wiw
6287            wincmd l
6288            if winnr() == curwin
6289                wincmd h
6290            endif
6291        elseif winwidth(bufwinnr(t:netrw_lexbufnr)) >= 0
6292            exe "vert resize ".t:netrw_winwidth
6293        else
6294            call netrw#Lexplore(0,0)
6295        endif
6296
6297    else
6298        call netrw#Lexplore(0,0)
6299    endif
6300    let wiw= wiwkeep
6301
6302endfunction
6303
6304" s:NetSortSequence: allows user to edit the sorting sequence {{{2
6305function s:NetSortSequence(islocal)
6306    let ykeep= @@
6307    let svpos= winsaveview()
6308    call inputsave()
6309    let newsortseq= input("Edit Sorting Sequence: ",g:netrw_sort_sequence)
6310    call inputrestore()
6311
6312    " refresh the listing
6313    let g:netrw_sort_sequence= newsortseq
6314    NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6315    NetrwKeepj call winrestview(svpos)
6316    let @@= ykeep
6317endfunction
6318
6319" s:NetrwUnmarkList: delete local marked file list and remove their contents from the global marked-file list {{{2
6320"   User access provided by the <mF> mapping. (see :help netrw-mF)
6321"   Used by many MarkFile functions.
6322function s:NetrwUnmarkList(curbufnr,curdir)
6323
6324    "  remove all files in local marked-file list from global list
6325    if exists("s:netrwmarkfilelist")
6326        for mfile in s:netrwmarkfilelist_{a:curbufnr}
6327            let dfile = netrw#fs#ComposePath(a:curdir,mfile)       " prepend directory to mfile
6328            let idx   = index(s:netrwmarkfilelist,dfile)    " get index in list of dfile
6329            call remove(s:netrwmarkfilelist,idx)            " remove from global list
6330        endfor
6331        if s:netrwmarkfilelist == []
6332            unlet s:netrwmarkfilelist
6333        endif
6334
6335        " getting rid of the local marked-file lists is easy
6336        unlet s:netrwmarkfilelist_{a:curbufnr}
6337    endif
6338    if exists("s:netrwmarkfilemtch_{a:curbufnr}")
6339        unlet s:netrwmarkfilemtch_{a:curbufnr}
6340    endif
6341    2match none
6342endfunction
6343
6344" s:NetrwUnmarkAll: remove the global marked file list and all local ones {{{2
6345function s:NetrwUnmarkAll()
6346    if exists("s:netrwmarkfilelist")
6347        unlet s:netrwmarkfilelist
6348    endif
6349    sil call s:NetrwUnmarkAll2()
6350    2match none
6351endfunction
6352
6353" s:NetrwUnmarkAll2: unmark all files from all buffers {{{2
6354function s:NetrwUnmarkAll2()
6355    redir => netrwmarkfilelist_let
6356    let
6357    redir END
6358    let netrwmarkfilelist_list= split(netrwmarkfilelist_let,'\n')          " convert let string into a let list
6359    call filter(netrwmarkfilelist_list,"v:val =~ '^s:netrwmarkfilelist_'") " retain only those vars that start as s:netrwmarkfilelist_
6360    call map(netrwmarkfilelist_list,"substitute(v:val,'\\s.*$','','')")    " remove what the entries are equal to
6361    for flist in netrwmarkfilelist_list
6362        let curbufnr= substitute(flist,'s:netrwmarkfilelist_','','')
6363        unlet s:netrwmarkfilelist_{curbufnr}
6364        unlet s:netrwmarkfilemtch_{curbufnr}
6365    endfor
6366endfunction
6367
6368" s:NetrwUnMarkFile: called via mu map; unmarks *all* marked files, both global and buffer-local {{{2
6369"
6370" Marked files are in two types of lists:
6371"    s:netrwmarkfilelist    -- holds complete paths to all marked files
6372"    s:netrwmarkfilelist_#  -- holds list of marked files in current-buffer's directory (#==bufnr())
6373"
6374" Marked files suitable for use with 2match are in:
6375"    s:netrwmarkfilemtch_#   -- used with 2match to display marked files
6376function s:NetrwUnMarkFile(islocal)
6377    let svpos    = winsaveview()
6378    let curbufnr = bufnr("%")
6379
6380    " unmark marked file list
6381    " (although I expect s:NetrwUpload() to do it, I'm just making sure)
6382    if exists("s:netrwmarkfilelist")
6383        unlet s:netrwmarkfilelist
6384    endif
6385
6386    let ibuf= 1
6387    while ibuf <= bufnr("$")
6388        if exists("s:netrwmarkfilelist_".ibuf)
6389            unlet s:netrwmarkfilelist_{ibuf}
6390            unlet s:netrwmarkfilemtch_{ibuf}
6391        endif
6392        let ibuf = ibuf + 1
6393    endwhile
6394    2match none
6395
6396    "  call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6397    call winrestview(svpos)
6398endfunction
6399
6400" s:NetrwMenu: generates the menu for gvim and netrw {{{2
6401function s:NetrwMenu(domenu)
6402
6403    if !exists("g:NetrwMenuPriority")
6404        let g:NetrwMenuPriority= 80
6405    endif
6406
6407    if has("menu") && has("gui_running") && &go =~# 'm' && g:netrw_menu
6408
6409        if !exists("s:netrw_menu_enabled") && a:domenu
6410            let s:netrw_menu_enabled= 1
6411            exe 'sil! menu '.g:NetrwMenuPriority.'.1      '.g:NetrwTopLvlMenu.'Help<tab><F1>    <F1>'
6412            exe 'sil! menu '.g:NetrwMenuPriority.'.5      '.g:NetrwTopLvlMenu.'-Sep1-   :'
6413            exe 'sil! menu '.g:NetrwMenuPriority.'.6      '.g:NetrwTopLvlMenu.'Go\ Up\ Directory<tab>-  -'
6414            exe 'sil! menu '.g:NetrwMenuPriority.'.7      '.g:NetrwTopLvlMenu.'Apply\ Special\ Viewer<tab>x     x'
6415            if g:netrw_dirhistmax > 0
6416                exe 'sil! menu '.g:NetrwMenuPriority.'.8.1   '.g:NetrwTopLvlMenu.'Bookmarks\ and\ History.Bookmark\ Current\ Directory<tab>mb      mb'
6417                exe 'sil! menu '.g:NetrwMenuPriority.'.8.4   '.g:NetrwTopLvlMenu.'Bookmarks\ and\ History.Goto\ Prev\ Dir\ (History)<tab>u u'
6418                exe 'sil! menu '.g:NetrwMenuPriority.'.8.5   '.g:NetrwTopLvlMenu.'Bookmarks\ and\ History.Goto\ Next\ Dir\ (History)<tab>U U'
6419                exe 'sil! menu '.g:NetrwMenuPriority.'.8.6   '.g:NetrwTopLvlMenu.'Bookmarks\ and\ History.List<tab>qb      qb'
6420            else
6421                exe 'sil! menu '.g:NetrwMenuPriority.'.8     '.g:NetrwTopLvlMenu.'Bookmarks\ and\ History  :echo "(disabled)"'."\<cr>"
6422            endif
6423            exe 'sil! menu '.g:NetrwMenuPriority.'.9.1    '.g:NetrwTopLvlMenu.'Browsing\ Control.Horizontal\ Split<tab>o        o'
6424            exe 'sil! menu '.g:NetrwMenuPriority.'.9.2    '.g:NetrwTopLvlMenu.'Browsing\ Control.Vertical\ Split<tab>v  v'
6425            exe 'sil! menu '.g:NetrwMenuPriority.'.9.3    '.g:NetrwTopLvlMenu.'Browsing\ Control.New\ Tab<tab>t t'
6426            exe 'sil! menu '.g:NetrwMenuPriority.'.9.4    '.g:NetrwTopLvlMenu.'Browsing\ Control.Preview<tab>p  p'
6427            exe 'sil! menu '.g:NetrwMenuPriority.'.9.5    '.g:NetrwTopLvlMenu.'Browsing\ Control.Edit\ File\ Hiding\ List<tab><ctrl-h>'."       \<c-h>'"
6428            exe 'sil! menu '.g:NetrwMenuPriority.'.9.6    '.g:NetrwTopLvlMenu.'Browsing\ Control.Edit\ Sorting\ Sequence<tab>S  S'
6429            exe 'sil! menu '.g:NetrwMenuPriority.'.9.7    '.g:NetrwTopLvlMenu.'Browsing\ Control.Quick\ Hide/Unhide\ Dot\ Files<tab>'."gh       gh"
6430            exe 'sil! menu '.g:NetrwMenuPriority.'.9.8    '.g:NetrwTopLvlMenu.'Browsing\ Control.Refresh\ Listing<tab>'."<ctrl-l>       \<c-l>"
6431            exe 'sil! menu '.g:NetrwMenuPriority.'.9.9    '.g:NetrwTopLvlMenu.'Browsing\ Control.Settings/Options<tab>:NetrwSettings    '.":NetrwSettings\<cr>"
6432            exe 'sil! menu '.g:NetrwMenuPriority.'.10     '.g:NetrwTopLvlMenu.'Delete\ File/Directory<tab>D     D'
6433            exe 'sil! menu '.g:NetrwMenuPriority.'.11.1   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.Create\ New\ File<tab>%   %'
6434            exe 'sil! menu '.g:NetrwMenuPriority.'.11.1   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.In\ Current\ Window<tab><cr>      '."\<cr>"
6435            exe 'sil! menu '.g:NetrwMenuPriority.'.11.2   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.Preview\ File/Directory<tab>p     p'
6436            exe 'sil! menu '.g:NetrwMenuPriority.'.11.3   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.In\ Previous\ Window<tab>P        P'
6437            exe 'sil! menu '.g:NetrwMenuPriority.'.11.4   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.In\ New\ Window<tab>o     o'
6438            exe 'sil! menu '.g:NetrwMenuPriority.'.11.5   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.In\ New\ Tab<tab>t        t'
6439            exe 'sil! menu '.g:NetrwMenuPriority.'.11.5   '.g:NetrwTopLvlMenu.'Edit\ File/Dir.In\ New\ Vertical\ Window<tab>v   v'
6440            exe 'sil! menu '.g:NetrwMenuPriority.'.12.1   '.g:NetrwTopLvlMenu.'Explore.Directory\ Name  :Explore '
6441            exe 'sil! menu '.g:NetrwMenuPriority.'.12.2   '.g:NetrwTopLvlMenu.'Explore.Filenames\ Matching\ Pattern\ (curdir\ only)<tab>:Explore\ */    :Explore */'
6442            exe 'sil! menu '.g:NetrwMenuPriority.'.12.2   '.g:NetrwTopLvlMenu.'Explore.Filenames\ Matching\ Pattern\ (+subdirs)<tab>:Explore\ **/       :Explore **/'
6443            exe 'sil! menu '.g:NetrwMenuPriority.'.12.3   '.g:NetrwTopLvlMenu.'Explore.Files\ Containing\ String\ Pattern\ (curdir\ only)<tab>:Explore\ *//     :Explore *//'
6444            exe 'sil! menu '.g:NetrwMenuPriority.'.12.4   '.g:NetrwTopLvlMenu.'Explore.Files\ Containing\ String\ Pattern\ (+subdirs)<tab>:Explore\ **//        :Explore **//'
6445            exe 'sil! menu '.g:NetrwMenuPriority.'.12.4   '.g:NetrwTopLvlMenu.'Explore.Next\ Match<tab>:Nexplore        :Nexplore<cr>'
6446            exe 'sil! menu '.g:NetrwMenuPriority.'.12.4   '.g:NetrwTopLvlMenu.'Explore.Prev\ Match<tab>:Pexplore        :Pexplore<cr>'
6447            exe 'sil! menu '.g:NetrwMenuPriority.'.13     '.g:NetrwTopLvlMenu.'Make\ Subdirectory<tab>d d'
6448            exe 'sil! menu '.g:NetrwMenuPriority.'.14.1   '.g:NetrwTopLvlMenu.'Marked\ Files.Mark\ File<tab>mf  mf'
6449            exe 'sil! menu '.g:NetrwMenuPriority.'.14.2   '.g:NetrwTopLvlMenu.'Marked\ Files.Mark\ Files\ by\ Regexp<tab>mr     mr'
6450            exe 'sil! menu '.g:NetrwMenuPriority.'.14.3   '.g:NetrwTopLvlMenu.'Marked\ Files.Hide-Show-List\ Control<tab>a      a'
6451            exe 'sil! menu '.g:NetrwMenuPriority.'.14.4   '.g:NetrwTopLvlMenu.'Marked\ Files.Copy\ To\ Target<tab>mc    mc'
6452            exe 'sil! menu '.g:NetrwMenuPriority.'.14.5   '.g:NetrwTopLvlMenu.'Marked\ Files.Delete<tab>D       D'
6453            exe 'sil! menu '.g:NetrwMenuPriority.'.14.6   '.g:NetrwTopLvlMenu.'Marked\ Files.Diff<tab>md        md'
6454            exe 'sil! menu '.g:NetrwMenuPriority.'.14.7   '.g:NetrwTopLvlMenu.'Marked\ Files.Edit<tab>me        me'
6455            exe 'sil! menu '.g:NetrwMenuPriority.'.14.8   '.g:NetrwTopLvlMenu.'Marked\ Files.Exe\ Cmd<tab>mx    mx'
6456            exe 'sil! menu '.g:NetrwMenuPriority.'.14.9   '.g:NetrwTopLvlMenu.'Marked\ Files.Move\ To\ Target<tab>mm    mm'
6457            exe 'sil! menu '.g:NetrwMenuPriority.'.14.10  '.g:NetrwTopLvlMenu.'Marked\ Files.Obtain<tab>O       O'
6458            exe 'sil! menu '.g:NetrwMenuPriority.'.14.11  '.g:NetrwTopLvlMenu.'Marked\ Files.Print<tab>mp       mp'
6459            exe 'sil! menu '.g:NetrwMenuPriority.'.14.12  '.g:NetrwTopLvlMenu.'Marked\ Files.Replace<tab>R      R'
6460            exe 'sil! menu '.g:NetrwMenuPriority.'.14.13  '.g:NetrwTopLvlMenu.'Marked\ Files.Set\ Target<tab>mt mt'
6461            exe 'sil! menu '.g:NetrwMenuPriority.'.14.14  '.g:NetrwTopLvlMenu.'Marked\ Files.Tag<tab>mT mT'
6462            exe 'sil! menu '.g:NetrwMenuPriority.'.14.15  '.g:NetrwTopLvlMenu.'Marked\ Files.Zip/Unzip/Compress/Uncompress<tab>mz       mz'
6463            exe 'sil! menu '.g:NetrwMenuPriority.'.15     '.g:NetrwTopLvlMenu.'Obtain\ File<tab>O       O'
6464            exe 'sil! menu '.g:NetrwMenuPriority.'.16.1.1 '.g:NetrwTopLvlMenu.'Style.Listing.thin<tab>i :let w:netrw_liststyle=0<cr><c-L>'
6465            exe 'sil! menu '.g:NetrwMenuPriority.'.16.1.1 '.g:NetrwTopLvlMenu.'Style.Listing.long<tab>i :let w:netrw_liststyle=1<cr><c-L>'
6466            exe 'sil! menu '.g:NetrwMenuPriority.'.16.1.1 '.g:NetrwTopLvlMenu.'Style.Listing.wide<tab>i :let w:netrw_liststyle=2<cr><c-L>'
6467            exe 'sil! menu '.g:NetrwMenuPriority.'.16.1.1 '.g:NetrwTopLvlMenu.'Style.Listing.tree<tab>i :let w:netrw_liststyle=3<cr><c-L>'
6468            exe 'sil! menu '.g:NetrwMenuPriority.'.16.2.1 '.g:NetrwTopLvlMenu.'Style.Normal-Hide-Show.Show\ All<tab>a   :let g:netrw_hide=0<cr><c-L>'
6469            exe 'sil! menu '.g:NetrwMenuPriority.'.16.2.3 '.g:NetrwTopLvlMenu.'Style.Normal-Hide-Show.Normal<tab>a      :let g:netrw_hide=1<cr><c-L>'
6470            exe 'sil! menu '.g:NetrwMenuPriority.'.16.2.2 '.g:NetrwTopLvlMenu.'Style.Normal-Hide-Show.Hidden\ Only<tab>a        :let g:netrw_hide=2<cr><c-L>'
6471            exe 'sil! menu '.g:NetrwMenuPriority.'.16.3   '.g:NetrwTopLvlMenu.'Style.Reverse\ Sorting\ Order<tab>'."r   r"
6472            exe 'sil! menu '.g:NetrwMenuPriority.'.16.4.1 '.g:NetrwTopLvlMenu.'Style.Sorting\ Method.Name<tab>s       :let g:netrw_sort_by="name"<cr><c-L>'
6473            exe 'sil! menu '.g:NetrwMenuPriority.'.16.4.2 '.g:NetrwTopLvlMenu.'Style.Sorting\ Method.Time<tab>s       :let g:netrw_sort_by="time"<cr><c-L>'
6474            exe 'sil! menu '.g:NetrwMenuPriority.'.16.4.3 '.g:NetrwTopLvlMenu.'Style.Sorting\ Method.Size<tab>s       :let g:netrw_sort_by="size"<cr><c-L>'
6475            exe 'sil! menu '.g:NetrwMenuPriority.'.16.4.3 '.g:NetrwTopLvlMenu.'Style.Sorting\ Method.Exten<tab>s      :let g:netrw_sort_by="exten"<cr><c-L>'
6476            exe 'sil! menu '.g:NetrwMenuPriority.'.17     '.g:NetrwTopLvlMenu.'Rename\ File/Directory<tab>R     R'
6477            exe 'sil! menu '.g:NetrwMenuPriority.'.18     '.g:NetrwTopLvlMenu.'Set\ Current\ Directory<tab>c    c'
6478            let s:netrw_menucnt= 28
6479            call s:NetrwBookmarkMenu() " provide some history!  uses priorities 2,3, reserves 4, 8.2.x
6480            call s:NetrwTgtMenu()      " let bookmarks and history be easy targets
6481
6482        elseif !a:domenu
6483            let s:netrwcnt = 0
6484            let curwin     = winnr()
6485            windo if getline(2) =~# "Netrw" | let s:netrwcnt= s:netrwcnt + 1 | endif
6486            exe curwin."wincmd w"
6487
6488            if s:netrwcnt <= 1
6489                exe 'sil! unmenu '.g:NetrwTopLvlMenu
6490                sil! unlet s:netrw_menu_enabled
6491            endif
6492        endif
6493    return
6494  endif
6495
6496endfunction
6497
6498" s:NetrwObtain: obtain file under cursor or from markfile list {{{2
6499"                Used by the O maps (as <SID>NetrwObtain())
6500function s:NetrwObtain(islocal)
6501
6502    let ykeep= @@
6503    if exists("s:netrwmarkfilelist_{bufnr('%')}")
6504        let islocal= s:netrwmarkfilelist_{bufnr('%')}[1] !~ '^\a\{3,}://'
6505        call netrw#Obtain(islocal,s:netrwmarkfilelist_{bufnr('%')})
6506        call s:NetrwUnmarkList(bufnr('%'),b:netrw_curdir)
6507    else
6508        call netrw#Obtain(a:islocal,s:NetrwGetWord())
6509    endif
6510    let @@= ykeep
6511
6512endfunction
6513
6514" s:NetrwPrevWinOpen: open file/directory in previous window.  {{{2
6515"   If there's only one window, then the window will first be split.
6516"   Returns:
6517"     choice = 0 : didn't have to choose
6518"     choice = 1 : saved modified file in window first
6519"     choice = 2 : didn't save modified file, opened window
6520"     choice = 3 : cancel open
6521function s:NetrwPrevWinOpen(islocal)
6522    let ykeep= @@
6523    " grab a copy of the b:netrw_curdir to pass it along to newly split windows
6524    let curdir = b:netrw_curdir
6525
6526    " get last window number and the word currently under the cursor
6527    let origwin   = winnr()
6528    let lastwinnr = winnr("$")
6529    let curword      = s:NetrwGetWord()
6530    let choice       = 0
6531    let s:prevwinopen= 1  " lets s:NetrwTreeDir() know that NetrwPrevWinOpen called it (s:NetrwTreeDir() will unlet s:prevwinopen)
6532    let s:treedir = s:NetrwTreeDir(a:islocal)
6533    let curdir    = s:treedir
6534
6535    let didsplit = 0
6536    if lastwinnr == 1
6537        " if only one window, open a new one first
6538        " g:netrw_preview=0: preview window shown in a horizontally split window
6539        " g:netrw_preview=1: preview window shown in a vertically   split window
6540        if g:netrw_preview
6541            " vertically split preview window
6542            let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize
6543            exe (g:netrw_alto? "top " : "bot ")."vert ".winsz."wincmd s"
6544        else
6545            " horizontally split preview window
6546            let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winheight(0))/100 : -g:netrw_winsize
6547            exe (g:netrw_alto? "bel " : "abo ").winsz."wincmd s"
6548        endif
6549        let didsplit = 1
6550
6551    else
6552        NetrwKeepj call s:SaveBufVars()
6553        let eikeep= &ei
6554        setl ei=all
6555        wincmd p
6556
6557        if exists("s:lexplore_win") && s:lexplore_win == winnr()
6558            " whoops -- user trying to open file in the Lexplore window.
6559            " Use Lexplore's opening-file window instead.
6560            "    exe g:netrw_chgwin."wincmd w"
6561            wincmd p
6562            call s:NetrwBrowse(0,s:NetrwBrowseChgDir(0,s:NetrwGetWord(),1))
6563        endif
6564
6565        " prevwinnr: the window number of the "prev" window
6566        " prevbufnr: the buffer number of the buffer in the "prev" window
6567        " bnrcnt   : the qty of windows open on the "prev" buffer
6568        let prevwinnr   = winnr()
6569        let prevbufnr   = bufnr("%")
6570        let prevbufname = bufname("%")
6571        let prevmod     = &mod
6572        let bnrcnt      = 0
6573        NetrwKeepj call s:RestoreBufVars()
6574
6575        " if the previous window's buffer has been changed (ie. its modified flag is set),
6576        " and it doesn't appear in any other extant window, then ask the
6577        " user if s/he wants to abandon modifications therein.
6578        if prevmod
6579            windo if winbufnr(0) == prevbufnr | let bnrcnt=bnrcnt+1 | endif
6580            exe prevwinnr."wincmd w"
6581
6582            if bnrcnt == 1 && &hidden == 0
6583                " only one copy of the modified buffer in a window, and
6584                " hidden not set, so overwriting will lose the modified file.  Ask first...
6585                let choice = confirm("Save modified buffer<".prevbufname."> first?","&Yes\n&No\n&Cancel")
6586                let &ei= eikeep
6587
6588                if choice == 1
6589                    " Yes -- write file & then browse
6590                    let v:errmsg= ""
6591                    sil w
6592                    if v:errmsg != ""
6593                        call netrw#msg#Notify('ERROR', printf('unable to write <%s>!', (exists("prevbufname") ? prevbufname : 'n/a')))
6594                        exe origwin."wincmd w"
6595                        let &ei = eikeep
6596                        let @@  = ykeep
6597                        return choice
6598                    endif
6599
6600                elseif choice == 2
6601                    " No -- don't worry about changed file, just browse anyway
6602                    echomsg "**note** changes to ".prevbufname." abandoned"
6603
6604                else
6605                    " Cancel -- don't do this
6606                    exe origwin."wincmd w"
6607                    let &ei= eikeep
6608                    let @@ = ykeep
6609                    return choice
6610                endif
6611            endif
6612        endif
6613        let &ei= eikeep
6614    endif
6615
6616    " restore b:netrw_curdir (window split/enew may have lost it)
6617    let b:netrw_curdir= curdir
6618    if a:islocal < 2
6619        if a:islocal
6620            call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(a:islocal,curword,0))
6621        else
6622            call s:NetrwBrowse(a:islocal,s:NetrwBrowseChgDir(a:islocal,curword,0))
6623        endif
6624    endif
6625    let @@= ykeep
6626    return choice
6627endfunction
6628
6629" s:NetrwUpload: load fname to tgt (used by NetrwMarkFileCopy()) {{{2
6630"                Always assumed to be local -> remote
6631"                call s:NetrwUpload(filename, target)
6632"                call s:NetrwUpload(filename, target, fromdirectory)
6633function s:NetrwUpload(fname,tgt,...)
6634
6635    if a:tgt =~ '^\a\{3,}://'
6636        let tgtdir= substitute(a:tgt,'^\a\{3,}://[^/]\+/\(.\{-}\)$','\1','')
6637    else
6638        let tgtdir= substitute(a:tgt,'^\(.*\)/[^/]*$','\1','')
6639    endif
6640
6641    if a:0 > 0
6642        let fromdir= a:1
6643    else
6644        let fromdir= getcwd()
6645    endif
6646
6647    if type(a:fname) == 1
6648        " handle uploading a single file using NetWrite
6649        1split
6650        exe "NetrwKeepj e ".fnameescape(s:NetrwFile(a:fname))
6651        if a:tgt =~ '/$'
6652            let wfname= substitute(a:fname,'^.*/','','')
6653            exe "w! ".fnameescape(a:tgt.wfname)
6654        else
6655            exe "w ".fnameescape(a:tgt)
6656        endif
6657        q!
6658
6659    elseif type(a:fname) == 3
6660        " handle uploading a list of files via scp
6661        let curdir= getcwd()
6662        if a:tgt =~ '^scp:'
6663            if s:NetrwLcd(fromdir)
6664                return
6665            endif
6666            let filelist= deepcopy(s:netrwmarkfilelist_{bufnr('%')})
6667            let args    = join(map(filelist,"netrw#os#Escape(v:val, 1)"))
6668            if exists("g:netrw_port") && g:netrw_port != ""
6669                let useport= " ".g:netrw_scpport." ".g:netrw_port
6670            else
6671                let useport= ""
6672            endif
6673            let machine = substitute(a:tgt,'^scp://\([^/:]\+\).*$','\1','')
6674            let tgt     = substitute(a:tgt,'^scp://[^/]\+/\(.*\)$','\1','')
6675            call netrw#os#Execute(s:netrw_silentxfer."!".g:netrw_scp_cmd.netrw#os#Escape(useport,1)." ".args." ".netrw#os#Escape(machine.":".tgt,1))
6676            if s:NetrwLcd(curdir)
6677                return
6678            endif
6679
6680        elseif a:tgt =~ '^ftp:'
6681            call s:NetrwMethod(a:tgt)
6682            if !s:NetrwValidateHostname(g:netrw_machine)
6683                call netrw#msg#Notify('ERROR', printf('Rejecting invalid hostname: <%s>', g:netrw_machine))
6684                return
6685            endif
6686
6687            if b:netrw_method == 2
6688                " handle uploading a list of files via ftp+.netrc
6689                let netrw_fname = b:netrw_fname
6690                sil NetrwKeepj new
6691
6692                NetrwKeepj put =g:netrw_ftpmode
6693
6694                if exists("g:netrw_ftpextracmd")
6695                    NetrwKeepj put =g:netrw_ftpextracmd
6696                endif
6697
6698                NetrwKeepj call setline(line("$")+1,'lcd "'.fromdir.'"')
6699
6700                if tgtdir == ""
6701                    let tgtdir= '/'
6702                endif
6703                NetrwKeepj call setline(line("$")+1,'cd "'.tgtdir.'"')
6704
6705                for fname in a:fname
6706                    NetrwKeepj call setline(line("$")+1,'put "'.s:NetrwFile(fname).'"')
6707                endfor
6708
6709                if exists("g:netrw_port") && g:netrw_port != ""
6710                    call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1)." ".netrw#os#Escape(g:netrw_port,1))
6711                else
6712                    call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1))
6713                endif
6714                " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
6715                sil NetrwKeepj g/Local directory now/d
6716                call histdel("/",-1)
6717                if getline(1) !~ "^$" && getline(1) !~ '^Trying '
6718                    call netrw#msg#Notify('ERROR', getline(1))
6719                else
6720                    bw!|q
6721                endif
6722
6723            elseif b:netrw_method == 3
6724                " upload with ftp + machine, id, passwd, and fname (ie. no .netrc)
6725                let netrw_fname= b:netrw_fname
6726                NetrwKeepj call s:SaveBufVars()|sil NetrwKeepj new|NetrwKeepj call s:RestoreBufVars()
6727                let tmpbufnr= bufnr("%")
6728                setl ff=unix
6729
6730                if exists("g:netrw_port") && g:netrw_port != ""
6731                    NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
6732                else
6733                    NetrwKeepj put ='open '.g:netrw_machine
6734                endif
6735
6736                if exists("g:netrw_uid") && g:netrw_uid != ""
6737                    if exists("g:netrw_ftp") && g:netrw_ftp == 1
6738                        NetrwKeepj put =g:netrw_uid
6739                        if exists("s:netrw_passwd")
6740                            NetrwKeepj call setline(line("$")+1,'"'.s:netrw_passwd.'"')
6741                        endif
6742                    elseif exists("s:netrw_passwd")
6743                        NetrwKeepj put ='user \"'.g:netrw_uid.'\" \"'.s:netrw_passwd.'\"'
6744                    endif
6745                endif
6746
6747                NetrwKeepj call setline(line("$")+1,'lcd "'.fromdir.'"')
6748
6749                if exists("b:netrw_fname") && b:netrw_fname != ""
6750                    NetrwKeepj call setline(line("$")+1,'cd "'.b:netrw_fname.'"')
6751                endif
6752
6753                if exists("g:netrw_ftpextracmd")
6754                    NetrwKeepj put =g:netrw_ftpextracmd
6755                endif
6756
6757                for fname in a:fname
6758                    NetrwKeepj call setline(line("$")+1,'put "'.fname.'"')
6759                endfor
6760
6761                " perform ftp:
6762                " -i       : turns off interactive prompting from ftp
6763                " -n  unix : DON'T use <.netrc>, even though it exists
6764                " -n  win32: quit being obnoxious about password
6765                NetrwKeepj norm! 1G"_dd
6766                call netrw#os#Execute(s:netrw_silentxfer."%!".s:netrw_ftp_cmd." ".g:netrw_ftp_options)
6767                " If the result of the ftp operation isn't blank, show an error message (tnx to Doug Claar)
6768                sil NetrwKeepj g/Local directory now/d
6769                call histdel("/",-1)
6770                if getline(1) !~ "^$" && getline(1) !~ '^Trying '
6771                    let debugkeep= &debug
6772                    setl debug=msg
6773                    call netrw#msg#Notify('ERROR', getline(1))
6774                    let &debug = debugkeep
6775                    let mod    = 1
6776                else
6777                    bw!|q
6778                endif
6779            elseif !exists("b:netrw_method") || b:netrw_method < 0
6780                return
6781            endif
6782        else
6783            call netrw#msg#Notify('ERROR', printf("can't obtain files with protocol from<%s>", a:tgt))
6784        endif
6785    endif
6786
6787endfunction
6788
6789" s:NetrwPreview: supports netrw's "p" map {{{2
6790function s:NetrwPreview(path) range
6791    let ykeep= @@
6792    NetrwKeepj call s:NetrwOptionsSave("s:")
6793    if a:path !~ '^\*\{1,2}/' && a:path !~ '^\a\{3,}://'
6794        NetrwKeepj call s:NetrwOptionsSafe(1)
6795    else
6796        NetrwKeepj call s:NetrwOptionsSafe(0)
6797    endif
6798    if has("quickfix")
6799        if !isdirectory(s:NetrwFile(a:path))
6800            if g:netrw_preview
6801                " vertical split
6802                let pvhkeep = &pvh
6803                let winsz   = (g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize
6804                let &pvh    = winwidth(0) - winsz
6805            else
6806                " horizontal split
6807                let pvhkeep = &pvh
6808                let winsz   = (g:netrw_winsize > 0)? (g:netrw_winsize*winheight(0))/100 : -g:netrw_winsize
6809                let &pvh    = winheight(0) - winsz
6810            endif
6811            " g:netrw_preview   g:netrw_alto
6812            "    1 : vert        1: top       -- preview window is vertically   split off and on the left
6813            "    1 : vert        0: bot       -- preview window is vertically   split off and on the right
6814            "    0 :             1: top       -- preview window is horizontally split off and on the top
6815            "    0 :             0: bot       -- preview window is horizontally split off and on the bottom
6816            "
6817            " Note that the file being previewed is already known to not be a directory, hence we can avoid doing a LocalBrowseCheck() check via
6818            " the BufEnter event set up in netrwPlugin.vim
6819            let eikeep = &ei
6820            set ei=BufEnter
6821            exe (g:netrw_alto? "top " : "bot ").(g:netrw_preview? "vert " : "")."pedit ".fnameescape(a:path)
6822            let &ei= eikeep
6823            if exists("pvhkeep")
6824                let &pvh= pvhkeep
6825            endif
6826        else
6827            call netrw#msg#Notify('WARNING', printf('sorry, cannot preview a directory such as <%s>', a:path))
6828        endif
6829    else
6830        call netrw#msg#Notify('WARNING', 'sorry, to preview your vim needs the quickfix feature compiled in')
6831    endif
6832    NetrwKeepj call s:NetrwOptionsRestore("s:")
6833    let @@= ykeep
6834endfunction
6835
6836" s:NetrwRefresh: {{{2
6837function s:NetrwRefresh(islocal,dirname)
6838    " at the current time (Mar 19, 2007) all calls to NetrwRefresh() call NetrwBrowseChgDir() first.
6839    setl ma noro
6840    let ykeep      = @@
6841    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
6842        if !exists("w:netrw_treetop")
6843            if exists("b:netrw_curdir")
6844                let w:netrw_treetop= b:netrw_curdir
6845            else
6846                let w:netrw_treetop= getcwd()
6847            endif
6848        endif
6849        NetrwKeepj call s:NetrwRefreshTreeDict(w:netrw_treetop)
6850    endif
6851
6852    " save the cursor position before refresh.
6853    let screenposn = winsaveview()
6854
6855    sil! NetrwKeepj %d _
6856    if a:islocal
6857        NetrwKeepj call netrw#LocalBrowseCheck(a:dirname)
6858    else
6859        NetrwKeepj call s:NetrwBrowse(a:islocal,a:dirname)
6860    endif
6861
6862    " restore position
6863    NetrwKeepj call winrestview(screenposn)
6864
6865    " restore file marks
6866    if has("syntax") && exists("g:syntax_on") && g:syntax_on
6867        if exists("s:netrwmarkfilemtch_{bufnr('%')}") && s:netrwmarkfilemtch_{bufnr("%")} != ""
6868            exe "2match netrwMarkFile /".s:netrwmarkfilemtch_{bufnr("%")}."/"
6869        else
6870            2match none
6871        endif
6872    endif
6873
6874    "  restore
6875    let @@= ykeep
6876endfunction
6877
6878" s:NetrwRefreshDir: refreshes a directory by name {{{2
6879"                    Called by NetrwMarkFileCopy()
6880"                    Interfaces to s:NetrwRefresh() and s:LocalBrowseRefresh()
6881function s:NetrwRefreshDir(islocal,dirname)
6882    if g:netrw_fastbrowse == 0
6883        " slowest mode (keep buffers refreshed, local or remote)
6884        let tgtwin= bufwinnr(a:dirname)
6885
6886        if tgtwin > 0
6887            " tgtwin is being displayed, so refresh it
6888            let curwin= winnr()
6889            exe tgtwin."wincmd w"
6890            NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
6891            exe curwin."wincmd w"
6892
6893        elseif bufnr(a:dirname) > 0
6894            let bn= bufnr(a:dirname)
6895            exe "sil keepj bd ".bn
6896        endif
6897
6898    elseif g:netrw_fastbrowse <= 1
6899        NetrwKeepj call s:LocalBrowseRefresh()
6900    endif
6901endfunction
6902
6903" s:NetrwSetChgwin: set g:netrw_chgwin; a <cr> will use the specified
6904" window number to do its editing in.
6905" Supports   [count]C  where the count, if present, is used to specify
6906" a window to use for editing via the <cr> mapping.
6907function s:NetrwSetChgwin(...)
6908    if a:0 > 0
6909        if a:1 == ""    " :NetrwC win#
6910            let g:netrw_chgwin= winnr()
6911        else              " :NetrwC
6912            let g:netrw_chgwin= a:1
6913        endif
6914    elseif v:count > 0 " [count]C
6915        let g:netrw_chgwin= v:count
6916    else               " C
6917        let g:netrw_chgwin= winnr()
6918    endif
6919    echo "editing window now set to window#".g:netrw_chgwin
6920endfunction
6921
6922" s:NetrwSetSort: sets up the sort based on the g:netrw_sort_sequence {{{2
6923"          What this function does is to compute a priority for the patterns
6924"          in the g:netrw_sort_sequence.  It applies a substitute to any
6925"          "files" that satisfy each pattern, putting the priority / in
6926"          front.  An "*" pattern handles the default priority.
6927function s:NetrwSetSort()
6928    let ykeep= @@
6929    if w:netrw_liststyle == s:LONGLIST
6930        let seqlist  = substitute(g:netrw_sort_sequence,'\$','\\%(\t\\|\$\\)','ge')
6931    else
6932        let seqlist  = g:netrw_sort_sequence
6933    endif
6934    " sanity check -- insure that * appears somewhere
6935    if seqlist == ""
6936        let seqlist= '*'
6937    elseif seqlist !~ '\*'
6938        let seqlist= seqlist.',*'
6939    endif
6940    let priority = 1
6941    while seqlist != ""
6942        if seqlist =~ ','
6943            let seq     = substitute(seqlist,',.*$','','e')
6944            let seqlist = substitute(seqlist,'^.\{-},\(.*\)$','\1','e')
6945        else
6946            let seq     = seqlist
6947            let seqlist = ""
6948        endif
6949        if priority < 10
6950            let spriority= "00".priority.g:netrw_sepchr
6951        elseif priority < 100
6952            let spriority= "0".priority.g:netrw_sepchr
6953        else
6954            let spriority= priority.g:netrw_sepchr
6955        endif
6956
6957        " sanity check
6958        if w:netrw_bannercnt > line("$")
6959            " apparently no files were left after a Hiding pattern was used
6960            return
6961        endif
6962        if seq == '*'
6963            let starpriority= spriority
6964        else
6965            exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$g/'.seq.'/s/^/'.spriority.'/'
6966            call histdel("/",-1)
6967            " sometimes multiple sorting patterns will match the same file or directory.
6968            " The following substitute is intended to remove the excess matches.
6969            exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$g/^\d\{3}'.g:netrw_sepchr.'\d\{3}\//s/^\d\{3}'.g:netrw_sepchr.'\(\d\{3}\/\).\@=/\1/e'
6970            NetrwKeepj call histdel("/",-1)
6971        endif
6972        let priority = priority + 1
6973    endwhile
6974    if exists("starpriority")
6975        exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$v/^\d\{3}'.g:netrw_sepchr.'/s/^/'.starpriority.'/e'
6976        NetrwKeepj call histdel("/",-1)
6977    endif
6978
6979    " Following line associated with priority -- items that satisfy a priority
6980    " pattern get prefixed by ###/ which permits easy sorting by priority.
6981    " Sometimes files can satisfy multiple priority patterns -- only the latest
6982    " priority pattern needs to be retained.  So, at this point, these excess
6983    " priority prefixes need to be removed, but not directories that happen to
6984    " be just digits themselves.
6985    exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$s/^\(\d\{3}'.g:netrw_sepchr.'\)\%(\d\{3}'.g:netrw_sepchr.'\)\+\ze./\1/e'
6986    NetrwKeepj call histdel("/",-1)
6987    let @@= ykeep
6988
6989endfunction
6990
6991" s:NetrwSetTgt: sets the target to the specified choice index {{{2
6992"    Implements [count]Tb  (bookhist<b>)
6993"               [count]Th  (bookhist<h>)
6994"               See :help netrw-qb for how to make the choice.
6995function s:NetrwSetTgt(islocal,bookhist,choice)
6996
6997    if     a:bookhist == 'b'
6998        " supports choosing a bookmark as a target using a qb-generated list
6999        let choice= a:choice - 1
7000        if exists("g:netrw_bookmarklist[".choice."]")
7001            call netrw#MakeTgt(g:netrw_bookmarklist[choice])
7002        else
7003            echomsg "Sorry, bookmark#".a:choice." doesn't exist!"
7004        endif
7005
7006    elseif a:bookhist == 'h'
7007        " supports choosing a history stack entry as a target using a qb-generated list
7008        let choice= (a:choice % g:netrw_dirhistmax) + 1
7009        if exists("g:netrw_dirhist_".choice)
7010            let histentry = g:netrw_dirhist_{choice}
7011            call netrw#MakeTgt(histentry)
7012        else
7013            echomsg "Sorry, history#".a:choice." not available!"
7014        endif
7015    endif
7016
7017    " refresh the display
7018    if !exists("b:netrw_curdir")
7019        let b:netrw_curdir= getcwd()
7020    endif
7021    call s:NetrwRefresh(a:islocal,b:netrw_curdir)
7022
7023endfunction
7024
7025" s:NetrwSortStyle: change sorting style (name - time - size - exten) and refresh display {{{2
7026function s:NetrwSortStyle(islocal)
7027    NetrwKeepj call s:NetrwSaveWordPosn()
7028    let svpos= winsaveview()
7029
7030    let g:netrw_sort_by= (g:netrw_sort_by =~# '^n')? 'time' : (g:netrw_sort_by =~# '^t')? 'size' : (g:netrw_sort_by =~# '^siz')? 'exten' : 'name'
7031    NetrwKeepj norm! 0
7032    NetrwKeepj call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
7033    NetrwKeepj call winrestview(svpos)
7034endfunction
7035
7036" s:NetrwSplit: mode {{{2
7037"           =0 : net   and o
7038"           =1 : net   and t
7039"           =2 : net   and v
7040"           =3 : local and o
7041"           =4 : local and t
7042"           =5 : local and v
7043function s:NetrwSplit(mode)
7044
7045    let ykeep= @@
7046    call s:SaveWinVars()
7047
7048    if a:mode == 0
7049        " remote and o
7050        let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winheight(0))/100 : -g:netrw_winsize
7051        if winsz == 0|let winsz= ""|endif
7052        exe (g:netrw_alto? "bel " : "abo ").winsz."wincmd s"
7053        let s:didsplit= 1
7054        NetrwKeepj call s:RestoreWinVars()
7055        NetrwKeepj call s:NetrwBrowse(0,s:NetrwBrowseChgDir(0,s:NetrwGetWord(),1))
7056        unlet s:didsplit
7057
7058    elseif a:mode == 1
7059        " remote and t
7060        let newdir  = s:NetrwBrowseChgDir(0,s:NetrwGetWord(),1)
7061        tabnew
7062        let s:didsplit= 1
7063        NetrwKeepj call s:RestoreWinVars()
7064        NetrwKeepj call s:NetrwBrowse(0,newdir)
7065        unlet s:didsplit
7066
7067    elseif a:mode == 2
7068        " remote and v
7069        let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize
7070        if winsz == 0|let winsz= ""|endif
7071        exe (g:netrw_altv? "rightb " : "lefta ").winsz."wincmd v"
7072        let s:didsplit= 1
7073        NetrwKeepj call s:RestoreWinVars()
7074        NetrwKeepj call s:NetrwBrowse(0,s:NetrwBrowseChgDir(0,s:NetrwGetWord(),1))
7075        unlet s:didsplit
7076
7077    elseif a:mode == 3
7078        " local and o
7079        let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winheight(0))/100 : -g:netrw_winsize
7080        if winsz == 0|let winsz= ""|endif
7081        exe (g:netrw_alto? "bel " : "abo ").winsz."wincmd s"
7082        let s:didsplit= 1
7083        NetrwKeepj call s:RestoreWinVars()
7084        NetrwKeepj call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,s:NetrwGetWord(),1))
7085        unlet s:didsplit
7086        if &ea
7087            exe "keepalt wincmd ="
7088        endif
7089
7090    elseif a:mode == 4
7091        " local and t
7092        let cursorword  = s:NetrwGetWord()
7093        let eikeep      = &ei
7094        let netrw_winnr = winnr()
7095        let netrw_line  = line(".")
7096        let netrw_col   = virtcol(".")
7097        NetrwKeepj norm! H0
7098        let netrw_hline = line(".")
7099        setl ei=all
7100        exe "NetrwKeepj norm! ".netrw_hline."G0z\<CR>"
7101        exe "NetrwKeepj norm! ".netrw_line."G0".netrw_col."\<bar>"
7102        let &ei          = eikeep
7103        let netrw_curdir = s:NetrwTreeDir(0)
7104        tabnew
7105        let b:netrw_curdir = netrw_curdir
7106        let s:didsplit     = 1
7107        NetrwKeepj call s:RestoreWinVars()
7108        NetrwKeepj call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,cursorword,0))
7109        if &ft == "netrw"
7110            setl ei=all
7111            exe "NetrwKeepj norm! ".netrw_hline."G0z\<CR>"
7112            exe "NetrwKeepj norm! ".netrw_line."G0".netrw_col."\<bar>"
7113            let &ei= eikeep
7114        endif
7115        unlet s:didsplit
7116
7117    elseif a:mode == 5
7118        " local and v
7119        let winsz= (g:netrw_winsize > 0)? (g:netrw_winsize*winwidth(0))/100 : -g:netrw_winsize
7120        if winsz == 0|let winsz= ""|endif
7121        exe (g:netrw_altv? "rightb " : "lefta ").winsz."wincmd v"
7122        let s:didsplit= 1
7123        NetrwKeepj call s:RestoreWinVars()
7124        NetrwKeepj call netrw#LocalBrowseCheck(s:NetrwBrowseChgDir(1,s:NetrwGetWord(),1))
7125        unlet s:didsplit
7126        if &ea
7127            exe "keepalt wincmd ="
7128        endif
7129
7130    else
7131        call netrw#msg#Notify('ERROR', '(NetrwSplit) unsupported mode='.a:mode)
7132    endif
7133
7134    let @@= ykeep
7135endfunction
7136
7137" s:NetrwTgtMenu: {{{2
7138function s:NetrwTgtMenu()
7139    if !exists("s:netrw_menucnt")
7140        return
7141    endif
7142
7143    " the following test assures that gvim is running, has menus available, and has menus enabled.
7144    if has("gui") && has("menu") && has("gui_running") && &go =~# 'm' && g:netrw_menu
7145        if exists("g:NetrwTopLvlMenu")
7146            exe 'sil! unmenu '.g:NetrwTopLvlMenu.'Targets'
7147        endif
7148        if !exists("s:netrw_initbookhist")
7149            call s:NetrwBookHistRead()
7150        endif
7151
7152        " try to cull duplicate entries
7153        let tgtdict={}
7154
7155        " target bookmarked places
7156        if exists("g:netrw_bookmarklist") && g:netrw_bookmarklist != [] && g:netrw_dirhistmax > 0
7157            let cnt= 1
7158            for bmd in g:netrw_bookmarklist
7159                if has_key(tgtdict,bmd)
7160                    let cnt= cnt + 1
7161                    continue
7162                endif
7163                let tgtdict[bmd]= cnt
7164                let ebmd= escape(bmd,g:netrw_menu_escape)
7165                " show bookmarks for goto menu
7166                exe 'sil! menu <silent> '.g:NetrwMenuPriority.".19.1.".cnt." ".g:NetrwTopLvlMenu.'Targets.'.ebmd." :call netrw#MakeTgt(".escape(string(bmd),'|').")\<cr>"
7167                let cnt= cnt + 1
7168            endfor
7169        endif
7170
7171        " target directory browsing history
7172        if exists("g:netrw_dirhistmax") && g:netrw_dirhistmax > 0
7173            let histcnt = 1
7174            while histcnt <= g:netrw_dirhistmax
7175                let priority = g:netrw_dirhistcnt + histcnt
7176                if exists("g:netrw_dirhist_{histcnt}")
7177                    let histentry  = g:netrw_dirhist_{histcnt}
7178                    if has_key(tgtdict,histentry)
7179                        let histcnt = histcnt + 1
7180                        continue
7181                    endif
7182                    let tgtdict[histentry] = histcnt
7183                    let ehistentry         = escape(histentry,g:netrw_menu_escape)
7184                    exe 'sil! menu <silent> '.g:NetrwMenuPriority.".19.2.".priority." ".g:NetrwTopLvlMenu.'Targets.'.ehistentry."     :call netrw#MakeTgt(".escape(string(histentry),'|').")\<cr>"
7185                endif
7186                let histcnt = histcnt + 1
7187            endwhile
7188        endif
7189    endif
7190endfunction
7191
7192" s:NetrwTreeDir: determine tree directory given current cursor position {{{2
7193" (full path directory with trailing slash returned)
7194function s:NetrwTreeDir(islocal)
7195
7196    if exists("s:treedir") && exists("s:prevwinopen")
7197        " s:NetrwPrevWinOpen opens a "previous" window -- and thus needs to and does call s:NetrwTreeDir early
7198        let treedir= s:treedir
7199        unlet s:treedir
7200        unlet s:prevwinopen
7201        return treedir
7202    endif
7203    if exists("s:prevwinopen")
7204        unlet s:prevwinopen
7205    endif
7206
7207    if !exists("b:netrw_curdir") || b:netrw_curdir == ""
7208        let b:netrw_curdir= getcwd()
7209    endif
7210    let treedir = b:netrw_curdir
7211    let s:treecurpos= winsaveview()
7212
7213    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
7214
7215        " extract tree directory if on a line specifying a subdirectory (ie. ends with "/")
7216        let curline= substitute(getline('.'),"\t -->.*$",'','')
7217        if curline =~ '/$'
7218            let treedir= substitute(getline('.'),'^\%('.s:treedepthstring.'\)*\([^'.s:treedepthstring.'].\{-}\)$','\1','e')
7219        elseif curline =~ '@$'
7220            let potentialdir= resolve(s:NetrwTreePath(w:netrw_treetop))
7221        else
7222            let treedir= ""
7223        endif
7224
7225        " detect user attempting to close treeroot
7226        if curline !~ '^'.s:treedepthstring && getline('.') != '..'
7227            " now force a refresh
7228            sil! NetrwKeepj %d _
7229            return b:netrw_curdir
7230        endif
7231
7232        " COMBAK: a symbolic link may point anywhere -- so it will be used to start a new treetop
7233        "   if a:islocal && curline =~ '@$' && isdirectory(s:NetrwFile(potentialdir))
7234        "    let newdir          = w:netrw_treetop.'/'.potentialdir
7235        if a:islocal && curline =~ '@$'
7236            if isdirectory(s:NetrwFile(potentialdir))
7237                let treedir = potentialdir
7238                let w:netrw_treetop = treedir
7239            endif
7240        else
7241            let potentialdir= s:NetrwFile(substitute(curline,'^'.s:treedepthstring.'\+ \(.*\)@$','\1',''))
7242            let treedir = s:NetrwTreePath(w:netrw_treetop)
7243        endif
7244    endif
7245
7246    " sanity maintenance: keep those //s away...
7247    let treedir= substitute(treedir,'//$','/','')
7248    return treedir
7249endfunction
7250
7251" s:NetrwTreeDisplay: recursive tree display {{{2
7252function s:NetrwTreeDisplay(dir,depth)
7253    " ensure that there are no folds
7254    setl nofen
7255
7256    " install ../ and shortdir
7257    if a:depth == ""
7258        call setline(line("$")+1,'../')
7259    endif
7260    if a:dir =~ '^\a\{3,}://'
7261        if a:dir == w:netrw_treetop
7262            let shortdir= a:dir
7263        else
7264            let shortdir= substitute(a:dir,'^.*/\([^/]\+\)/$','\1/','e')
7265        endif
7266        call setline(line("$")+1,a:depth.shortdir)
7267    else
7268        let shortdir= substitute(a:dir,'^.*/','','e')
7269        call setline(line("$")+1,a:depth.shortdir.'/')
7270    endif
7271    " append a / to dir if its missing one
7272    let dir= a:dir
7273
7274    " display subtrees (if any)
7275    let depth= s:treedepthstring.a:depth
7276
7277    " implement g:netrw_hide for tree listings (uses g:netrw_list_hide)
7278    if     g:netrw_hide == 1
7279        " hide given patterns
7280        let listhide= split(g:netrw_list_hide,',')
7281        for pat in listhide
7282            call filter(w:netrw_treedict[dir], {_, v -> v !~# pat})
7283        endfor
7284
7285    elseif g:netrw_hide == 2
7286        " show given patterns (only)
7287        let listhide= split(g:netrw_list_hide,',')
7288        let entries=[]
7289        for entry in w:netrw_treedict[dir]
7290            for pat in listhide
7291                if entry =~ pat
7292                    call add(entries,entry)
7293                    break
7294                endif
7295            endfor
7296        endfor
7297        let w:netrw_treedict[dir]= entries
7298    endif
7299    if depth != ""
7300        " always remove "." and ".." entries when there's depth
7301        call filter(w:netrw_treedict[dir],'v:val !~ "\\.\\.$"')
7302        call filter(w:netrw_treedict[dir],'v:val !~ "\\.\\./$"')
7303        call filter(w:netrw_treedict[dir],'v:val !~ "\\.$"')
7304        call filter(w:netrw_treedict[dir],'v:val !~ "\\./$"')
7305    endif
7306
7307    for entry in w:netrw_treedict[dir]
7308        if dir =~ '/$'
7309            let direntry= substitute(dir.entry,'[@/]$','','e')
7310        else
7311            let direntry= substitute(dir.'/'.entry,'[@/]$','','e')
7312        endif
7313        if entry =~ '/$' && has_key(w:netrw_treedict,direntry)
7314            NetrwKeepj call s:NetrwTreeDisplay(direntry,depth)
7315        elseif entry =~ '/$' && has_key(w:netrw_treedict,direntry.'/')
7316            NetrwKeepj call s:NetrwTreeDisplay(direntry.'/',depth)
7317        elseif entry =~ '@$' && has_key(w:netrw_treedict,direntry.'@')
7318            NetrwKeepj call s:NetrwTreeDisplay(direntry.'@',depth)
7319        else
7320            sil! NetrwKeepj call setline(line("$")+1,depth.entry)
7321        endif
7322    endfor
7323endfunction
7324
7325" s:NetrwRefreshTreeDict: updates the contents information for a tree (w:netrw_treedict) {{{2
7326function s:NetrwRefreshTreeDict(dir)
7327    if !exists("w:netrw_treedict")
7328        return
7329    endif
7330
7331    for entry in w:netrw_treedict[a:dir]
7332        let direntry= substitute(a:dir.'/'.entry,'[@/]$','','e')
7333
7334        if entry =~ '/$' && has_key(w:netrw_treedict,direntry)
7335            NetrwKeepj call s:NetrwRefreshTreeDict(direntry)
7336            let filelist = s:NetrwLocalListingList(direntry,0)
7337            let w:netrw_treedict[direntry] = sort(filelist)
7338
7339        elseif entry =~ '/$' && has_key(w:netrw_treedict,direntry.'/')
7340            NetrwKeepj call s:NetrwRefreshTreeDict(direntry.'/')
7341            let filelist = s:NetrwLocalListingList(direntry.'/',0)
7342            let w:netrw_treedict[direntry] = sort(filelist)
7343
7344        elseif entry =~ '@$' && has_key(w:netrw_treedict,direntry.'@')
7345            NetrwKeepj call s:NetrwRefreshTreeDict(direntry.'/')
7346            let liststar   = netrw#fs#Glob(direntry.'/','*',1)
7347            let listdotstar= netrw#fs#Glob(direntry.'/','.*',1)
7348
7349        else
7350        endif
7351    endfor
7352endfunction
7353
7354" s:NetrwTreeListing: displays tree listing from treetop on down, using NetrwTreeDisplay() {{{2
7355"                     Called by s:PerformListing()
7356function s:NetrwTreeListing(dirname)
7357    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
7358
7359        " update the treetop
7360        if !exists("w:netrw_treetop")
7361            let w:netrw_treetop= a:dirname
7362            let s:netrw_treetop= w:netrw_treetop
7363        " use \V in case the directory contains specials chars like '$' or '~'
7364        elseif (w:netrw_treetop =~ ('^'.'\V'.a:dirname)
7365                    \ && strdisplaywidth(a:dirname) < strdisplaywidth(w:netrw_treetop))
7366                    \ || a:dirname !~ ('^'.'\V'.w:netrw_treetop)
7367            let w:netrw_treetop= a:dirname
7368            let s:netrw_treetop= w:netrw_treetop
7369        endif
7370        if exists("w:netrw_treetop")
7371            let s:netrw_treetop= w:netrw_treetop
7372        else
7373            let w:netrw_treetop= getcwd()
7374            let s:netrw_treetop= w:netrw_treetop
7375        endif
7376
7377        if !exists("w:netrw_treedict")
7378            " insure that we have a treedict, albeit empty
7379            let w:netrw_treedict= {}
7380        endif
7381
7382        " update the dictionary for the current directory
7383        exe "sil! NetrwKeepj keepp ".w:netrw_bannercnt.',$g@^\.\.\=/$@d _'
7384        let w:netrw_treedict[a:dirname]= getline(w:netrw_bannercnt,line("$"))
7385        exe "sil! NetrwKeepj ".w:netrw_bannercnt.",$d _"
7386
7387        " if past banner, record word
7388        if exists("w:netrw_bannercnt") && line(".") > w:netrw_bannercnt
7389            let fname= expand("<cword>")
7390        else
7391            let fname= ""
7392        endif
7393
7394        " display from treetop on down
7395        NetrwKeepj call s:NetrwTreeDisplay(w:netrw_treetop,"")
7396
7397        " remove any blank line remaining as line#1 (happens in treelisting mode with banner suppressed)
7398        while getline(1) =~ '^\s*$' && byte2line(1) > 0
7399            1d
7400        endwhile
7401
7402        exe "setl ".g:netrw_bufsettings
7403
7404        return
7405    endif
7406endfunction
7407
7408" s:NetrwTreePath: returns path to current file/directory in tree listing {{{2
7409"                  Normally, treetop is w:netrw_treetop, but a
7410"                  user of the function ( netrw#SetTreetop() )
7411"                  wipes that out prior to calling this function
7412function s:NetrwTreePath(treetop)
7413    if line(".") < w:netrw_bannercnt + 2
7414        let treedir= a:treetop
7415        if treedir !~ '/$'
7416            let treedir= treedir.'/'
7417        endif
7418        return treedir
7419    endif
7420
7421    let svpos = winsaveview()
7422    let depth = substitute(getline('.'),'^\(\%('.s:treedepthstring.'\)*\)[^'.s:treedepthstring.'].\{-}$','\1','e')
7423    let depth = substitute(depth,'^'.s:treedepthstring,'','')
7424    let curline= getline('.')
7425    if curline =~ '/$'
7426        let treedir= substitute(curline,'^\%('.s:treedepthstring.'\)*\([^'.s:treedepthstring.'].\{-}\)$','\1','e')
7427    elseif curline =~ '@\s\+-->'
7428        let treedir= substitute(curline,'^\%('.s:treedepthstring.'\)*\([^'.s:treedepthstring.'].\{-}\)$','\1','e')
7429        let treedir= substitute(treedir,'@\s\+-->.*$','','e')
7430    else
7431        let treedir= ""
7432    endif
7433    " construct treedir by searching backwards at correct depth
7434    while depth != "" && search('^'.depth.'[^'.s:treedepthstring.'].\{-}/$','bW')
7435        let dirname= substitute(getline('.'),'^\('.s:treedepthstring.'\)*','','e')
7436        let treedir= dirname.treedir
7437        let depth  = substitute(depth,'^'.s:treedepthstring,'','')
7438    endwhile
7439    if a:treetop =~ '/$'
7440        let treedir= a:treetop.treedir
7441    else
7442        let treedir= a:treetop.'/'.treedir
7443    endif
7444    let treedir= substitute(treedir,'//$','/','')
7445    call winrestview(svpos)
7446    return treedir
7447endfunction
7448
7449" s:NetrwWideListing: {{{2
7450function s:NetrwWideListing()
7451
7452    if w:netrw_liststyle == s:WIDELIST
7453        " look for longest filename (cpf=characters per filename)
7454        " cpf: characters per filename
7455        " fpl: filenames per line
7456        " fpc: filenames per column
7457        setl ma noro
7458        let dict={}
7459        " save the unnamed register and register 0-9 and a
7460        let dict.a=[getreg('a'), getregtype('a')]
7461        for i in range(0, 9)
7462            let dict[i] = [getreg(i), getregtype(i)]
7463        endfor
7464        let dict.unnamed = [getreg(''), getregtype('')]
7465        let b:netrw_cpf= 0
7466        if line("$") >= w:netrw_bannercnt
7467            " determine the maximum filename size; use that to set cpf
7468            exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$g/^./if virtcol("$") > b:netrw_cpf|let b:netrw_cpf= virtcol("$")|endif'
7469            NetrwKeepj call histdel("/",-1)
7470        else
7471            " restore stored registers
7472            call s:RestoreRegister(dict)
7473            return
7474        endif
7475        " allow for two spaces to separate columns
7476        let b:netrw_cpf= b:netrw_cpf + 2
7477
7478        " determine qty files per line (fpl)
7479        let w:netrw_fpl= winwidth(0)/b:netrw_cpf
7480        if w:netrw_fpl <= 0
7481            let w:netrw_fpl= 1
7482        endif
7483
7484        " make wide display
7485        "   fpc: files per column of wide listing
7486        exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$s/^.*$/\=escape(printf("%-'.b:netrw_cpf.'S",submatch(0)),"\\")/'
7487        NetrwKeepj call histdel("/",-1)
7488        let fpc         = (line("$") - w:netrw_bannercnt + w:netrw_fpl)/w:netrw_fpl
7489        let newcolstart = w:netrw_bannercnt + fpc
7490        let newcolend   = newcolstart + fpc - 1
7491        if !has('nvim') && has("clipboard") && g:netrw_clipboard
7492            sil! let keepregstar = @*
7493            sil! let keepregplus = @+
7494        endif
7495        while line("$") >= newcolstart
7496            if newcolend > line("$") | let newcolend= line("$") | endif
7497            let newcolqty= newcolend - newcolstart
7498            exe newcolstart
7499            " COMBAK: both of the visual-mode using lines below are problematic vis-a-vis @*
7500            if newcolqty == 0
7501                exe "sil! NetrwKeepj norm! 0\<c-v>$h\"ax".w:netrw_bannercnt."G$\"ap"
7502            else
7503                exe "sil! NetrwKeepj norm! 0\<c-v>".newcolqty.'j$h"ax'.w:netrw_bannercnt.'G$"ap'
7504            endif
7505            exe "sil! NetrwKeepj ".newcolstart.','.newcolend.'d _'
7506            exe 'sil! NetrwKeepj '.w:netrw_bannercnt
7507        endwhile
7508        if !has('nvim') && has("clipboard")
7509            if @* != keepregstar | sil! let @* = keepregstar | endif
7510            if @+ != keepregplus | sil! let @+ = keepregplus | endif
7511        endif
7512        exe "sil! NetrwKeepj ".w:netrw_bannercnt.',$s/\s\+$//e'
7513        NetrwKeepj call histdel("/",-1)
7514        exe 'nno <buffer> <silent> w :call search(''^.\\|\s\s\zs\S'',''W'')'."\<cr>"
7515        exe 'nno <buffer> <silent> b :call search(''^.\\|\s\s\zs\S'',''bW'')'."\<cr>"
7516        exe "setl ".g:netrw_bufsettings
7517        call s:RestoreRegister(dict)
7518        return
7519    else
7520        if hasmapto("w","n")
7521            sil! nunmap <buffer> w
7522        endif
7523        if hasmapto("b","n")
7524            sil! nunmap <buffer> b
7525        endif
7526    endif
7527endfunction
7528
7529" s:PerformListing: {{{2
7530function s:PerformListing(islocal)
7531    sil! NetrwKeepj %d _
7532    "  call DechoBuf(bufnr("%"))
7533
7534    " set up syntax highlighting {{{3
7535    sil! setl ft=netrw
7536
7537    NetrwKeepj call s:NetrwOptionsSafe(a:islocal)
7538    setl noro ma
7539
7540
7541    if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("w:netrw_treedict")
7542        " force a refresh for tree listings
7543        sil! NetrwKeepj %d _
7544    endif
7545
7546    " save current directory on directory history list
7547    NetrwKeepj call s:NetrwBookHistHandler(3,b:netrw_curdir)
7548
7549    " Set up the banner {{{3
7550    if g:netrw_banner
7551        NetrwKeepj call setline(1,'" ============================================================================')
7552        if exists("g:netrw_pchk")
7553            " this undocumented option allows pchk to run with different versions of netrw without causing spurious
7554            " failure detections.
7555            NetrwKeepj call setline(2,'" Netrw Directory Listing')
7556        else
7557            NetrwKeepj call setline(2,'" Netrw Directory Listing                                        (netrw '.g:loaded_netrw.')')
7558        endif
7559        if exists("g:netrw_pchk")
7560            let curdir= substitute(b:netrw_curdir,expand("$HOME"),'~','')
7561        else
7562            let curdir= b:netrw_curdir
7563        endif
7564        if exists("g:netrw_bannerbackslash") && g:netrw_bannerbackslash
7565            NetrwKeepj call setline(3,'"   '.substitute(curdir,'/','\\','g'))
7566        else
7567            NetrwKeepj call setline(3,'"   '.curdir)
7568        endif
7569        let w:netrw_bannercnt= 3
7570        NetrwKeepj exe "sil! NetrwKeepj ".w:netrw_bannercnt
7571    else
7572        NetrwKeepj 1
7573        let w:netrw_bannercnt= 1
7574    endif
7575
7576    " construct sortby string: [name|time|size|exten] [reversed]
7577    let sortby= g:netrw_sort_by
7578    if g:netrw_sort_direction =~# "^r"
7579        let sortby= sortby." reversed"
7580    endif
7581
7582    " Sorted by... {{{3
7583    if g:netrw_banner
7584        if g:netrw_sort_by =~# "^n"
7585            " sorted by name (also includes the sorting sequence in the banner)
7586            NetrwKeepj put ='\"   Sorted by      '.sortby
7587            NetrwKeepj put ='\"   Sort sequence: '.g:netrw_sort_sequence
7588            let w:netrw_bannercnt= w:netrw_bannercnt + 2
7589        else
7590            " sorted by time, size, exten
7591            NetrwKeepj put ='\"   Sorted by '.sortby
7592            let w:netrw_bannercnt= w:netrw_bannercnt + 1
7593        endif
7594        exe "sil! NetrwKeepj ".w:netrw_bannercnt
7595    endif
7596
7597    " show copy/move target, if any {{{3
7598    if g:netrw_banner
7599        if exists("s:netrwmftgt") && exists("s:netrwmftgt_islocal")
7600            NetrwKeepj put =''
7601            if s:netrwmftgt_islocal
7602                sil! NetrwKeepj call setline(line("."),'"   Copy/Move Tgt: '.s:netrwmftgt.' (local)')
7603            else
7604                sil! NetrwKeepj call setline(line("."),'"   Copy/Move Tgt: '.s:netrwmftgt.' (remote)')
7605            endif
7606            let w:netrw_bannercnt= w:netrw_bannercnt + 1
7607        else
7608        endif
7609        exe "sil! NetrwKeepj ".w:netrw_bannercnt
7610    endif
7611
7612    " Hiding...  -or-  Showing... {{{3
7613    if g:netrw_banner
7614        if g:netrw_list_hide != "" && g:netrw_hide
7615            if g:netrw_hide == 1
7616                NetrwKeepj put ='\"   Hiding:        '.g:netrw_list_hide
7617            else
7618                NetrwKeepj put ='\"   Showing:       '.g:netrw_list_hide
7619            endif
7620            let w:netrw_bannercnt= w:netrw_bannercnt + 1
7621        endif
7622        exe "NetrwKeepj ".w:netrw_bannercnt
7623
7624        let quickhelp   = g:netrw_quickhelp%len(s:QuickHelp)
7625        NetrwKeepj put ='\"   Quick Help: <F1>:help  '.s:QuickHelp[quickhelp]
7626        NetrwKeepj put ='\" =============================================================================='
7627        let w:netrw_bannercnt= w:netrw_bannercnt + 2
7628    endif
7629
7630    " bannercnt should index the line just after the banner
7631    if g:netrw_banner
7632        let w:netrw_bannercnt= w:netrw_bannercnt + 1
7633        exe "sil! NetrwKeepj ".w:netrw_bannercnt
7634    endif
7635
7636    " get list of files
7637    if a:islocal
7638        let filelist = s:NetrwLocalListingList(b:netrw_curdir, 1)
7639        call append(w:netrw_bannercnt - 1, filelist)
7640        silent! NetrwKeepj g/^$/d
7641        silent! NetrwKeepj %s/\r$//e
7642        execute printf("setl ts=%d", g:netrw_maxfilenamelen + 1)
7643    else " remote
7644        NetrwKeepj let badresult= s:NetrwRemoteListing()
7645        if badresult
7646            return
7647        endif
7648    endif
7649
7650    " manipulate the directory listing (hide, sort) {{{3
7651    if !exists("w:netrw_bannercnt")
7652        let w:netrw_bannercnt= 0
7653    endif
7654
7655    if !g:netrw_banner || line("$") >= w:netrw_bannercnt
7656        if g:netrw_hide && g:netrw_list_hide != ""
7657            NetrwKeepj call s:NetrwListHide()
7658        endif
7659        if !g:netrw_banner || line("$") >= w:netrw_bannercnt
7660
7661            if g:netrw_sort_by =~# "^n"
7662                " sort by name
7663                NetrwKeepj call s:NetrwSetSort()
7664
7665                if !g:netrw_banner || w:netrw_bannercnt < line("$")
7666                    if g:netrw_sort_direction =~# 'n'
7667                        " name: sort by name of file
7668                        exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$sort'.' '.g:netrw_sort_options
7669                    else
7670                        " reverse direction sorting
7671                        exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$sort!'.' '.g:netrw_sort_options
7672                    endif
7673                endif
7674
7675                " remove priority pattern prefix
7676                exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s/^\d\{3}'.g:netrw_sepchr.'//e'
7677                NetrwKeepj call histdel("/",-1)
7678
7679            elseif g:netrw_sort_by =~# "^ext"
7680                " exten: sort by extension
7681                "   The histdel(...,-1) calls remove the last search from the search history
7682                exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$g+/+s/^/001'.g:netrw_sepchr.'/'
7683                NetrwKeepj call histdel("/",-1)
7684                exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$v+[./]+s/^/002'.g:netrw_sepchr.'/'
7685                NetrwKeepj call histdel("/",-1)
7686                exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$v+['.g:netrw_sepchr.'/]+s/^\(.*\.\)\(.\{-\}\)$/\2'.g:netrw_sepchr.'&/e'
7687                NetrwKeepj call histdel("/",-1)
7688                if !g:netrw_banner || w:netrw_bannercnt < line("$")
7689                    if g:netrw_sort_direction =~# 'n'
7690                        " normal direction sorting
7691                        exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$sort'.' '.g:netrw_sort_options
7692                    else
7693                        " reverse direction sorting
7694                        exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$sort!'.' '.g:netrw_sort_options
7695                    endif
7696                endif
7697                exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s/^.\{-}'.g:netrw_sepchr.'//e'
7698                NetrwKeepj call histdel("/",-1)
7699
7700            elseif a:islocal
7701                if !g:netrw_banner || w:netrw_bannercnt < line("$")
7702                    if g:netrw_sort_direction =~# 'n'
7703                        exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$sort'.' '.g:netrw_sort_options
7704                    else
7705                        exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$sort!'.' '.g:netrw_sort_options
7706                    endif
7707                    exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s/^\d\{-}\///e'
7708                    NetrwKeepj call histdel("/",-1)
7709                endif
7710            endif
7711
7712        elseif g:netrw_sort_direction =~# 'r'
7713            if !g:netrw_banner || w:netrw_bannercnt < line('$')
7714                exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$g/^/m '.w:netrw_bannercnt
7715                call histdel("/",-1)
7716            endif
7717        endif
7718    endif
7719
7720    " convert to wide/tree listing {{{3
7721    NetrwKeepj call s:NetrwWideListing()
7722    NetrwKeepj call s:NetrwTreeListing(b:netrw_curdir)
7723
7724    " resolve symbolic links if local and (thin or tree)
7725    if a:islocal && (w:netrw_liststyle == s:THINLIST || (exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST))
7726        sil! keepp g/@$/call s:ShowLink()
7727    endif
7728
7729    if exists("w:netrw_bannercnt") && (line("$") >= w:netrw_bannercnt || !g:netrw_banner)
7730        " place cursor on the top-left corner of the file listing
7731        exe 'sil! '.w:netrw_bannercnt
7732        sil! NetrwKeepj norm! 0
7733    else
7734    endif
7735
7736    " record previous current directory
7737    let w:netrw_prvdir= b:netrw_curdir
7738
7739    " save certain window-oriented variables into buffer-oriented variables {{{3
7740    NetrwKeepj call s:SetBufWinVars()
7741    NetrwKeepj call s:NetrwOptionsRestore("w:")
7742
7743    " set display to netrw display settings
7744    exe "setl ".g:netrw_bufsettings
7745    if g:netrw_liststyle == s:LONGLIST
7746        exe "setl ts=".(g:netrw_maxfilenamelen+1)
7747    endif
7748    "  call DechoBuf(bufnr("%"))
7749
7750    if exists("s:treecurpos")
7751        NetrwKeepj call winrestview(s:treecurpos)
7752        unlet s:treecurpos
7753    endif
7754
7755endfunction
7756
7757" s:SetupNetrwStatusLine: {{{2
7758function s:SetupNetrwStatusLine(statline)
7759
7760    if !exists("s:netrw_setup_statline")
7761        let s:netrw_setup_statline= 1
7762
7763        if !exists("s:netrw_users_stl")
7764            let s:netrw_users_stl= &stl
7765        endif
7766        if !exists("s:netrw_users_ls")
7767            let s:netrw_users_ls= &laststatus
7768        endif
7769
7770        " set up User9 highlighting as needed
7771        let dict={}
7772        let dict.a=[getreg('a'), getregtype('a')]
7773        redir @a
7774        try
7775            hi User9
7776        catch /^Vim\%((\a\{3,})\)\=:E411/
7777            if &bg == "dark"
7778                hi User9 ctermfg=yellow ctermbg=blue guifg=yellow guibg=blue
7779            else
7780                hi User9 ctermbg=yellow ctermfg=blue guibg=yellow guifg=blue
7781            endif
7782        endtry
7783        redir END
7784        call s:RestoreRegister(dict)
7785    endif
7786
7787    " set up status line (may use User9 highlighting)
7788    " insure that windows have a statusline
7789    " make sure statusline is displayed
7790    let &l:stl=a:statline
7791    setl laststatus=2
7792    redraw
7793
7794endfunction
7795
7796"  Remote Directory Browsing Support:  {{{1
7797
7798" s:NetrwRemoteFtpCmd: unfortunately, not all ftp servers honor options for ls {{{2
7799"  This function assumes that a long listing will be received.  Size, time,
7800"  and reverse sorts will be requested of the server but not otherwise
7801"  enforced here.
7802function s:NetrwRemoteFtpCmd(path,listcmd)
7803    " sanity check: {{{3
7804    if !exists("w:netrw_method")
7805        if exists("b:netrw_method")
7806            let w:netrw_method= b:netrw_method
7807        else
7808            call netrw#msg#Notify('ERROR', '(s:NetrwRemoteFtpCmd) internal netrw error')
7809            return
7810        endif
7811    endif
7812
7813    " WinXX ftp uses unix style input, so set ff to unix  " {{{3
7814    let ffkeep= &ff
7815    setl ma ff=unix noro
7816
7817    " clear off any older non-banner lines        " {{{3
7818    " note that w:netrw_bannercnt indexes the line after the banner
7819    exe "sil! NetrwKeepj ".w:netrw_bannercnt.",$d _"
7820
7821    ".........................................
7822    if w:netrw_method == 2 || w:netrw_method == 5 " {{{3
7823        " ftp + <.netrc>:  Method #2
7824        if a:path != ""
7825            NetrwKeepj put ='cd \"'.a:path.'\"'
7826        endif
7827        if exists("g:netrw_ftpextracmd")
7828            NetrwKeepj put =g:netrw_ftpextracmd
7829        endif
7830        NetrwKeepj call setline(line("$")+1,a:listcmd)
7831        if exists("g:netrw_port") && g:netrw_port != ""
7832            exe s:netrw_silentxfer." NetrwKeepj ".w:netrw_bannercnt.",$!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1)." ".netrw#os#Escape(g:netrw_port,1)
7833        else
7834            exe s:netrw_silentxfer." NetrwKeepj ".w:netrw_bannercnt.",$!".s:netrw_ftp_cmd." -i ".netrw#os#Escape(g:netrw_machine,1)
7835        endif
7836
7837        ".........................................
7838    elseif w:netrw_method == 3    " {{{3
7839        " ftp + machine,id,passwd,filename:  Method #3
7840        setl ff=unix
7841        if exists("g:netrw_port") && g:netrw_port != ""
7842            NetrwKeepj put ='open '.g:netrw_machine.' '.g:netrw_port
7843        else
7844            NetrwKeepj put ='open '.g:netrw_machine
7845        endif
7846
7847        " handle userid and password
7848        let host= substitute(g:netrw_machine,'\..*$','','')
7849        if exists("s:netrw_hup") && exists("s:netrw_hup[host]")
7850            call netrw#NetUserPass("ftp:".host)
7851        endif
7852        if exists("g:netrw_uid") && g:netrw_uid != ""
7853            if exists("g:netrw_ftp") && g:netrw_ftp == 1
7854                NetrwKeepj put =g:netrw_uid
7855                if exists("s:netrw_passwd") && s:netrw_passwd != ""
7856                    NetrwKeepj put ='\"'.s:netrw_passwd.'\"'
7857                endif
7858            elseif exists("s:netrw_passwd")
7859                NetrwKeepj put ='user \"'.g:netrw_uid.'\" \"'.s:netrw_passwd.'\"'
7860            endif
7861        endif
7862
7863        if a:path != ""
7864            NetrwKeepj put ='cd \"'.a:path.'\"'
7865        endif
7866        if exists("g:netrw_ftpextracmd")
7867            NetrwKeepj put =g:netrw_ftpextracmd
7868        endif
7869        NetrwKeepj call setline(line("$")+1,a:listcmd)
7870
7871        " perform ftp:
7872        " -i       : turns off interactive prompting from ftp
7873        " -n  unix : DON'T use <.netrc>, even though it exists
7874        " -n  win32: quit being obnoxious about password
7875        if exists("w:netrw_bannercnt")
7876            call netrw#os#Execute(s:netrw_silentxfer.w:netrw_bannercnt.",$!".s:netrw_ftp_cmd." ".g:netrw_ftp_options)
7877        endif
7878
7879        ".........................................
7880    elseif w:netrw_method == 9    " {{{3
7881        " sftp username@machine: Method #9
7882        " s:netrw_sftp_cmd
7883        setl ff=unix
7884
7885        " restore settings
7886        let &l:ff= ffkeep
7887        return
7888
7889        ".........................................
7890    else  " {{{3
7891        call netrw#msg#Notify('WARNING', printf('unable to comply with your request<%s>', bufname("%")))
7892    endif
7893
7894    " cleanup for Windows " {{{3
7895    if has("win32")
7896        sil! NetrwKeepj %s/\r$//e
7897        NetrwKeepj call histdel("/",-1)
7898    endif
7899    if a:listcmd == "dir"
7900        " infer directory/link based on the file permission string
7901        sil! NetrwKeepj g/d\%([-r][-w][-x]\)\{3}/NetrwKeepj s@$@/@e
7902        sil! NetrwKeepj g/l\%([-r][-w][-x]\)\{3}/NetrwKeepj s/$/@/e
7903        NetrwKeepj call histdel("/",-1)
7904        NetrwKeepj call histdel("/",-1)
7905        if w:netrw_liststyle == s:THINLIST || w:netrw_liststyle == s:WIDELIST || (exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST)
7906            exe "sil! NetrwKeepj ".w:netrw_bannercnt.',$s/^\%(\S\+\s\+\)\{8}//e'
7907            NetrwKeepj call histdel("/",-1)
7908        endif
7909    endif
7910
7911    " ftp's listing doesn't seem to include ./ or ../ " {{{3
7912    if !search('^\.\/$\|\s\.\/$','wn')
7913        exe 'NetrwKeepj '.w:netrw_bannercnt
7914        NetrwKeepj put ='./'
7915    endif
7916    if !search('^\.\.\/$\|\s\.\.\/$','wn')
7917        exe 'NetrwKeepj '.w:netrw_bannercnt
7918        NetrwKeepj put ='../'
7919    endif
7920
7921    " restore settings " {{{3
7922    let &l:ff= ffkeep
7923endfunction
7924
7925" s:NetrwRemoteListing: {{{2
7926function s:NetrwRemoteListing()
7927
7928    if !exists("w:netrw_bannercnt") && exists("s:bannercnt")
7929        let w:netrw_bannercnt= s:bannercnt
7930    endif
7931    if !exists("w:netrw_bannercnt") && exists("b:bannercnt")
7932        let w:netrw_bannercnt= b:bannercnt
7933    endif
7934
7935    call s:RemotePathAnalysis(b:netrw_curdir)
7936
7937    " sanity check:
7938    if exists("b:netrw_method") && b:netrw_method =~ '[235]'
7939        if !executable("ftp")
7940            call netrw#msg#Notify('ERROR', "this system doesn't support remote directory listing via ftp")
7941            call s:NetrwOptionsRestore("w:")
7942            return -1
7943        endif
7944
7945    elseif !exists("g:netrw_list_cmd") || g:netrw_list_cmd == ''
7946        if g:netrw_list_cmd == ""
7947            call netrw#msg#Notify('ERROR', printf('your g:netrw_list_cmd is empty; perhaps %s is not executable on your system', g:netrw_ssh_cmd))
7948        else
7949            call netrw#msg#Notify('ERROR', "this system doesn't support remote directory listing via ".g:netrw_list_cmd)
7950        endif
7951
7952        NetrwKeepj call s:NetrwOptionsRestore("w:")
7953        return -1
7954    endif  " (remote handling sanity check)
7955
7956    if exists("b:netrw_method")
7957        let w:netrw_method= b:netrw_method
7958    endif
7959
7960    if s:method == "ftp"
7961        " use ftp to get remote file listing {{{3
7962        let s:method  = "ftp"
7963        let listcmd = g:netrw_ftp_list_cmd
7964        if g:netrw_sort_by =~# '^t'
7965            let listcmd= g:netrw_ftp_timelist_cmd
7966        elseif g:netrw_sort_by =~# '^s'
7967            let listcmd= g:netrw_ftp_sizelist_cmd
7968        endif
7969        call s:NetrwRemoteFtpCmd(s:path,listcmd)
7970
7971        " report on missing file or directory messages
7972        if search('[Nn]o such file or directory\|Failed to change directory')
7973            let mesg= getline(".")
7974            if exists("w:netrw_bannercnt")
7975                setl ma
7976                exe w:netrw_bannercnt.",$d _"
7977                setl noma
7978            endif
7979            NetrwKeepj call s:NetrwOptionsRestore("w:")
7980            call netrw#msg#Notify('WARNING', mesg)
7981            return -1
7982        endif
7983
7984        if w:netrw_liststyle == s:THINLIST || w:netrw_liststyle == s:WIDELIST || (exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST)
7985            " shorten the listing
7986            exe "sil! keepalt NetrwKeepj ".w:netrw_bannercnt
7987
7988            " cleanup
7989            if g:netrw_ftp_browse_reject != ""
7990                exe "sil! keepalt NetrwKeepj g/".g:netrw_ftp_browse_reject."/NetrwKeepj d"
7991                NetrwKeepj call histdel("/",-1)
7992            endif
7993            sil! NetrwKeepj %s/\r$//e
7994            NetrwKeepj call histdel("/",-1)
7995
7996            " if there's no ../ listed, then put ../ in
7997            let line1= line(".")
7998            exe "sil! NetrwKeepj ".w:netrw_bannercnt
7999            let line2= search('\.\.\/\%(\s\|$\)','cnW')
8000            if line2 == 0
8001                sil! NetrwKeepj put='../'
8002            endif
8003            exe "sil! NetrwKeepj ".line1
8004            sil! NetrwKeepj norm! 0
8005
8006            if search('^\d\{2}-\d\{2}-\d\{2}\s','n') " M$ ftp site cleanup
8007                exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s/^\d\{2}-\d\{2}-\d\{2}\s\+\d\+:\d\+[AaPp][Mm]\s\+\%(<DIR>\|\d\+\)\s\+//'
8008                NetrwKeepj call histdel("/",-1)
8009            else " normal ftp cleanup
8010                exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s/^\(\%(\S\+\s\+\)\{7}\S\+\)\s\+\(\S.*\)$/\2/e'
8011                exe "sil! NetrwKeepj ".w:netrw_bannercnt.',$g/ -> /s# -> .*/$#/#e'
8012                exe "sil! NetrwKeepj ".w:netrw_bannercnt.',$g/ -> /s# -> .*$#/#e'
8013                NetrwKeepj call histdel("/",-1)
8014                NetrwKeepj call histdel("/",-1)
8015                NetrwKeepj call histdel("/",-1)
8016            endif
8017        endif
8018
8019    else
8020        " use ssh to get remote file listing {{{3
8021        let listcmd= s:MakeSshCmd(g:netrw_list_cmd)
8022        if g:netrw_scp_cmd =~ '^pscp'
8023            exe "NetrwKeepj r! ".listcmd.netrw#os#Escape(s:path, 1)
8024            " remove rubbish and adjust listing format of 'pscp' to 'ssh ls -FLa' like
8025            sil! NetrwKeepj g/^Listing directory/NetrwKeepj d
8026            sil! NetrwKeepj g/^d[-rwx][-rwx][-rwx]/NetrwKeepj s+$+/+e
8027            sil! NetrwKeepj g/^l[-rwx][-rwx][-rwx]/NetrwKeepj s+$+@+e
8028            NetrwKeepj call histdel("/",-1)
8029            NetrwKeepj call histdel("/",-1)
8030            NetrwKeepj call histdel("/",-1)
8031            if g:netrw_liststyle != s:LONGLIST
8032                sil! NetrwKeepj g/^[dlsp-][-rwx][-rwx][-rwx]/NetrwKeepj s/^.*\s\(\S\+\)$/\1/e
8033                NetrwKeepj call histdel("/",-1)
8034            endif
8035        else
8036            if s:path == ""
8037                exe "NetrwKeepj keepalt r! ".listcmd
8038            else
8039                exe "NetrwKeepj keepalt r! ".listcmd.' '.netrw#os#Escape(fnameescape(s:path),1)
8040            endif
8041        endif
8042
8043        " cleanup
8044        if g:netrw_ssh_browse_reject != ""
8045            exe "sil! g/".g:netrw_ssh_browse_reject."/NetrwKeepj d"
8046            NetrwKeepj call histdel("/",-1)
8047        endif
8048    endif
8049
8050    if w:netrw_liststyle == s:LONGLIST
8051        " do a long listing; these substitutions need to be done prior to sorting {{{3
8052
8053        if s:method == "ftp"
8054            " cleanup
8055            exe "sil! NetrwKeepj ".w:netrw_bannercnt
8056            while getline('.') =~# g:netrw_ftp_browse_reject
8057                sil! NetrwKeepj d
8058            endwhile
8059            " if there's no ../ listed, then put ../ in
8060            let line1= line(".")
8061            sil! NetrwKeepj 1
8062            sil! NetrwKeepj call search('^\.\.\/\%(\s\|$\)','W')
8063            let line2= line(".")
8064            if line2 == 0
8065                if b:netrw_curdir != '/'
8066                    exe 'sil! NetrwKeepj '.w:netrw_bannercnt."put='../'"
8067                endif
8068            endif
8069            exe "sil! NetrwKeepj ".line1
8070            sil! NetrwKeepj norm! 0
8071        endif
8072
8073        if search('^\d\{2}-\d\{2}-\d\{2}\s','n') " M$ ftp site cleanup
8074            exe 'sil! NetrwKeepj '.w:netrw_bannercnt.',$s/^\(\d\{2}-\d\{2}-\d\{2}\s\+\d\+:\d\+[AaPp][Mm]\s\+\%(<DIR>\|\d\+\)\s\+\)\(\w.*\)$/\2\t\1/'
8075        elseif exists("w:netrw_bannercnt") && w:netrw_bannercnt <= line("$")
8076            exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$s/ -> .*$//e'
8077            exe 'sil NetrwKeepj '.w:netrw_bannercnt.',$s/^\(\%(\S\+\s\+\)\{7}\S\+\)\s\+\(\S.*\)$/\2 \t\1/e'
8078            exe 'sil NetrwKeepj '.w:netrw_bannercnt
8079            NetrwKeepj call histdel("/",-1)
8080            NetrwKeepj call histdel("/",-1)
8081            NetrwKeepj call histdel("/",-1)
8082        endif
8083    endif
8084
8085
8086    return 0
8087endfunction
8088
8089" s:NetrwRemoteRm: remove/delete a remote file or directory {{{2
8090function s:NetrwRemoteRm(usrhost,path) range
8091    let svpos= winsaveview()
8092
8093    let all= 0
8094    if exists("s:netrwmarkfilelist_{bufnr('%')}")
8095        " remove all marked files
8096        for fname in s:netrwmarkfilelist_{bufnr("%")}
8097            let ok= s:NetrwRemoteRmFile(a:path,fname,all)
8098            if ok =~# 'q\%[uit]'
8099                break
8100            elseif ok =~# 'a\%[ll]'
8101                let all= 1
8102            endif
8103        endfor
8104        call s:NetrwUnmarkList(bufnr("%"),b:netrw_curdir)
8105
8106    else
8107        " remove files specified by range
8108
8109        " preparation for removing multiple files/directories
8110        let keepsol = &l:sol
8111        setl nosol
8112        let ctr    = a:firstline
8113
8114        " remove multiple files and directories
8115        while ctr <= a:lastline
8116            exe "NetrwKeepj ".ctr
8117            let ok= s:NetrwRemoteRmFile(a:path,s:NetrwGetWord(),all)
8118            if ok =~# 'q\%[uit]'
8119                break
8120            elseif ok =~# 'a\%[ll]'
8121                let all= 1
8122            endif
8123            let ctr= ctr + 1
8124        endwhile
8125        let &l:sol = keepsol
8126    endif
8127
8128    " refresh the (remote) directory listing
8129    NetrwKeepj call s:NetrwRefresh(0,s:NetrwBrowseChgDir(0,'./',0))
8130    NetrwKeepj call winrestview(svpos)
8131endfunction
8132
8133" s:NetrwRemoteRmFile: {{{2
8134function s:NetrwRemoteRmFile(path,rmfile,all)
8135
8136    let all= a:all
8137    let ok = ""
8138
8139    if a:rmfile !~ '^"' && (a:rmfile =~ '@$' || a:rmfile !~ '[\/]$')
8140        " attempt to remove file
8141        if !all
8142            echohl Statement
8143            call inputsave()
8144            let ok= input("Confirm deletion of file<".a:rmfile."> ","[{y(es)},n(o),a(ll),q(uit)] ")
8145            call inputrestore()
8146            echohl NONE
8147            if ok == ""
8148                let ok="no"
8149            endif
8150            let ok= substitute(ok,'\[{y(es)},n(o),a(ll),q(uit)]\s*','','e')
8151            if ok =~# 'a\%[ll]'
8152                let all= 1
8153            endif
8154        endif
8155
8156        if all || ok =~# 'y\%[es]' || ok == ""
8157            if exists("w:netrw_method") && (w:netrw_method == 2 || w:netrw_method == 3)
8158                let path= a:path
8159                if path =~ '^\a\{3,}://'
8160                    let path= substitute(path,'^\a\{3,}://[^/]\+/','','')
8161                endif
8162                sil! NetrwKeepj .,$d _
8163                call s:NetrwRemoteFtpCmd(path,"delete ".'"'.a:rmfile.'"')
8164            else
8165                let netrw_rm_cmd= s:MakeSshCmd(g:netrw_rm_cmd)
8166                if !exists("b:netrw_curdir")
8167                    call netrw#msg#Notify('ERROR', "for some reason b:netrw_curdir doesn't exist!")
8168                    let ok="q"
8169                else
8170                    let remotedir= substitute(b:netrw_curdir,'^.\{-}//[^/]\+/\(.*\)$','\1','')
8171                    if remotedir != ""
8172                        let netrw_rm_cmd= netrw_rm_cmd." ".netrw#os#Escape(fnameescape(remotedir.a:rmfile))
8173                    else
8174                        let netrw_rm_cmd= netrw_rm_cmd." ".netrw#os#Escape(fnameescape(a:rmfile))
8175                    endif
8176                    let ret= system(netrw_rm_cmd)
8177                    if v:shell_error != 0
8178                        if exists("b:netrw_curdir") && b:netrw_curdir != getcwd() && !g:netrw_keepdir
8179                            call netrw#msg#Notify('ERROR', printf("remove failed; perhaps due to vim's current directory<%s> not matching netrw's (%s) (see :help netrw-cd)", getcwd(), b:netrw_curdir))
8180                        else
8181                            call netrw#msg#Notify('WARNING', printf('cmd<%s> failed', netrw_rm_cmd))
8182                        endif
8183                    elseif ret != 0
8184                        call netrw#msg#Notify('WARNING', printf('cmd<%s> failed', netrw_rm_cmd))
8185                    endif
8186                endif
8187            endif
8188        elseif ok =~# 'q\%[uit]'
8189        endif
8190
8191    else
8192        " attempt to remove directory
8193        if !all
8194            call inputsave()
8195            let ok= input("Confirm deletion of directory<".a:rmfile."> ","[{y(es)},n(o),a(ll),q(uit)] ")
8196            call inputrestore()
8197            if ok == ""
8198                let ok="no"
8199            endif
8200            let ok= substitute(ok,'\[{y(es)},n(o),a(ll),q(uit)]\s*','','e')
8201            if ok =~# 'a\%[ll]'
8202                let all= 1
8203            endif
8204        endif
8205
8206        if all || ok =~# 'y\%[es]' || ok == ""
8207            if exists("w:netrw_method") && (w:netrw_method == 2 || w:netrw_method == 3)
8208                NetrwKeepj call s:NetrwRemoteFtpCmd(a:path,"rmdir ".a:rmfile)
8209            else
8210                let rmfile          = substitute(a:path.a:rmfile,'/$','','')
8211                let netrw_rmdir_cmd = s:MakeSshCmd(netrw#fs#WinPath(g:netrw_rmdir_cmd)).' '.netrw#os#Escape(netrw#fs#WinPath(rmfile))
8212                let ret= system(netrw_rmdir_cmd)
8213
8214                if v:shell_error != 0
8215                    let netrw_rmf_cmd= s:MakeSshCmd(netrw#fs#WinPath(g:netrw_rmf_cmd)).' '.netrw#os#Escape(netrw#fs#WinPath(substitute(rmfile,'[\/]$','','e')))
8216                    let ret= system(netrw_rmf_cmd)
8217
8218                    if v:shell_error != 0
8219                        call netrw#msg#Notify('ERROR', printf('unable to remove directory<%s> -- is it empty?', rmfile))
8220                    endif
8221                endif
8222            endif
8223
8224        elseif ok =~# 'q\%[uit]'
8225        endif
8226    endif
8227
8228    return ok
8229endfunction
8230
8231" s:NetrwRemoteRename: rename a remote file or directory {{{2
8232function s:NetrwRemoteRename(usrhost,path) range
8233
8234    " preparation for removing multiple files/directories
8235    let svpos      = winsaveview()
8236    let ctr        = a:firstline
8237    let rename_cmd = s:MakeSshCmd(g:netrw_rename_cmd)
8238
8239    " rename files given by the markfilelist
8240    if exists("s:netrwmarkfilelist_{bufnr('%')}")
8241        for oldname in s:netrwmarkfilelist_{bufnr("%")}
8242            if exists("subfrom")
8243                let newname= substitute(oldname,subfrom,subto,'')
8244            else
8245                call inputsave()
8246                let newname= input("Moving ".oldname." to : ",oldname)
8247                call inputrestore()
8248                if newname =~ '^s/'
8249                    let subfrom = substitute(newname,'^s/\([^/]*\)/.*/$','\1','')
8250                    let subto   = substitute(newname,'^s/[^/]*/\(.*\)/$','\1','')
8251                    let newname = substitute(oldname,subfrom,subto,'')
8252                endif
8253            endif
8254
8255            if exists("w:netrw_method") && (w:netrw_method == 2 || w:netrw_method == 3)
8256                NetrwKeepj call s:NetrwRemoteFtpCmd(a:path,"rename ".oldname." ".newname)
8257            else
8258                let oldname= netrw#os#Escape(a:path.oldname)
8259                let newname= netrw#os#Escape(a:path.newname)
8260                let ret    = system(netrw#fs#WinPath(rename_cmd).' '.oldname.' '.newname)
8261            endif
8262
8263        endfor
8264        call s:NetrwUnMarkFile(1)
8265
8266    else
8267
8268        " attempt to rename files/directories
8269        let keepsol= &l:sol
8270        setl nosol
8271        while ctr <= a:lastline
8272            exe "NetrwKeepj ".ctr
8273
8274            let oldname= s:NetrwGetWord()
8275
8276            call inputsave()
8277            let newname= input("Moving ".oldname." to : ",oldname)
8278            call inputrestore()
8279
8280            if exists("w:netrw_method") && (w:netrw_method == 2 || w:netrw_method == 3)
8281                call s:NetrwRemoteFtpCmd(a:path,"rename ".oldname." ".newname)
8282            else
8283                let oldname= netrw#os#Escape(a:path.oldname)
8284                let newname= netrw#os#Escape(a:path.newname)
8285                let ret    = system(netrw#fs#WinPath(rename_cmd).' '.oldname.' '.newname)
8286            endif
8287
8288            let ctr= ctr + 1
8289        endwhile
8290        let &l:sol= keepsol
8291    endif
8292
8293    " refresh the directory
8294    NetrwKeepj call s:NetrwRefresh(0,s:NetrwBrowseChgDir(0,'./',0))
8295    NetrwKeepj call winrestview(svpos)
8296endfunction
8297
8298"  Local Directory Browsing Support:    {{{1
8299
8300" netrw#FileUrlEdit: handles editing file://* files {{{2
8301"   Should accept:   file://localhost/etc/fstab
8302"                    file:///etc/fstab
8303"                    file:///c:/WINDOWS/clock.avi
8304"                    file:///c|/WINDOWS/clock.avi
8305"                    file://localhost/c:/WINDOWS/clock.avi
8306"                    file://localhost/c|/WINDOWS/clock.avi
8307"                    file://c:/foo.txt
8308"                    file:///c:/foo.txt
8309" and %XX (where X is [0-9a-fA-F] is converted into a character with the given hexadecimal value
8310function netrw#FileUrlEdit(fname)
8311    let fname = a:fname
8312    if fname =~ '^file://localhost/'
8313        let fname= substitute(fname,'^file://localhost/','file:///','')
8314    endif
8315    if has("win32")
8316        if fname  =~ '^file:///\=\a[|:]/'
8317            let fname = substitute(fname,'^file:///\=\(\a\)[|:]/','file://\1:/','')
8318        endif
8319    endif
8320    let fname2396 = netrw#RFC2396(fname)
8321    let fname2396e= fnameescape(fname2396)
8322    let plainfname= substitute(fname2396,'file://\(.*\)','\1',"")
8323    if has("win32")
8324        if plainfname =~ '^/\+\a:'
8325            let plainfname= substitute(plainfname,'^/\+\(\a:\)','\1','')
8326        endif
8327    endif
8328
8329    exe "sil doau BufReadPre ".fname2396e
8330    exe 'NetrwKeepj keepalt edit '. fnameescape(plainfname)
8331    exe 'sil! NetrwKeepj keepalt bdelete '.fnameescape(a:fname)
8332
8333    exe "sil doau BufReadPost ".fname2396e
8334endfunction
8335
8336" netrw#LocalBrowseCheck: {{{2
8337function netrw#LocalBrowseCheck(dirname)
8338    " This function is called by netrwPlugin.vim's s:LocalBrowseCheck(), s:NetrwRexplore(),
8339    " and by <cr> when atop a listed file/directory (via a buffer-local map)
8340    "
8341    " unfortunate interaction -- split window debugging can't be used here, must use
8342    "                            D-echoRemOn or D-echoTabOn as the BufEnter event triggers
8343    "                            another call to LocalBrowseCheck() when attempts to write
8344    "                            to the DBG buffer are made.
8345    "
8346    " The &ft == "netrw" test was installed because the BufEnter event
8347    " would hit when re-entering netrw windows, creating unexpected
8348    " refreshes (and would do so in the middle of NetrwSaveOptions(), too)
8349    " getting E930: Cannot use :redir inside execute
8350
8351    let ykeep= @@
8352    if isdirectory(s:NetrwFile(a:dirname))
8353
8354        if &ft != "netrw" || (exists("b:netrw_curdir") && b:netrw_curdir != a:dirname) || g:netrw_fastbrowse <= 1
8355            sil! NetrwKeepj keepalt call s:NetrwBrowse(1,a:dirname)
8356
8357        elseif &ft == "netrw" && line("$") == 1
8358            sil! NetrwKeepj keepalt call s:NetrwBrowse(1,a:dirname)
8359
8360        elseif exists("s:treeforceredraw")
8361            unlet s:treeforceredraw
8362            sil! NetrwKeepj keepalt call s:NetrwBrowse(1,a:dirname)
8363        endif
8364        return
8365    endif
8366
8367    " The following code wipes out currently unused netrw buffers
8368    "       IF g:netrw_fastbrowse is zero (ie. slow browsing selected)
8369    "   AND IF the listing style is not a tree listing
8370    if exists("g:netrw_fastbrowse") && g:netrw_fastbrowse == 0 && g:netrw_liststyle != s:TREELIST
8371        let ibuf    = 1
8372        let buflast = bufnr("$")
8373        while ibuf <= buflast
8374            if bufwinnr(ibuf) == -1 && !empty(bufname(ibuf)) && isdirectory(s:NetrwFile(bufname(ibuf)))
8375                exe "sil! keepj keepalt ".ibuf."bw!"
8376            endif
8377            let ibuf= ibuf + 1
8378        endwhile
8379    endif
8380    let @@= ykeep
8381    " not a directory, ignore it
8382endfunction
8383
8384" s:LocalBrowseRefresh: this function is called after a user has {{{2
8385" performed any shell command.  The idea is to cause all local-browsing
8386" buffers to be refreshed after a user has executed some shell command,
8387" on the chance that s/he removed/created a file/directory with it.
8388function s:LocalBrowseRefresh()
8389    " determine which buffers currently reside in a tab
8390    if !exists("s:netrw_browselist")
8391        return
8392    endif
8393    if !exists("w:netrw_bannercnt")
8394        return
8395    endif
8396    if exists("s:netrw_events") && s:netrw_events == 1
8397        " s:LocalFastBrowser gets called (indirectly) from a
8398        let s:netrw_events= 2
8399        return
8400    endif
8401    let itab       = 1
8402    let buftablist = []
8403    let ykeep      = @@
8404    while itab <= tabpagenr("$")
8405        let buftablist = buftablist + tabpagebuflist()
8406        let itab       = itab + 1
8407        sil! tabn
8408    endwhile
8409    "  GO through all buffers on netrw_browselist (ie. just local-netrw buffers):
8410    "   | refresh any netrw window
8411    "   | wipe out any non-displaying netrw buffer
8412    let curwinid = win_getid(winnr())
8413    let ibl    = 0
8414    for ibuf in s:netrw_browselist
8415        if bufwinnr(ibuf) == -1 && index(buftablist,ibuf) == -1
8416            " wipe out any non-displaying netrw buffer
8417            " (ibuf not shown in a current window AND
8418            "  ibuf not in any tab)
8419            exe "sil! keepj bd ".fnameescape(ibuf)
8420            call remove(s:netrw_browselist,ibl)
8421            continue
8422        elseif index(tabpagebuflist(),ibuf) != -1
8423            " refresh any netrw buffer
8424            exe bufwinnr(ibuf)."wincmd w"
8425            if getline(".") =~# 'Quick Help'
8426                " decrement g:netrw_quickhelp to prevent refresh from changing g:netrw_quickhelp
8427                " (counteracts s:NetrwBrowseChgDir()'s incrementing)
8428                let g:netrw_quickhelp= g:netrw_quickhelp - 1
8429            endif
8430            if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
8431                NetrwKeepj call s:NetrwRefreshTreeDict(w:netrw_treetop)
8432            endif
8433            NetrwKeepj call s:NetrwRefresh(1,s:NetrwBrowseChgDir(1,'./',0))
8434        endif
8435        let ibl= ibl + 1
8436    endfor
8437    call win_gotoid(curwinid)
8438    let @@= ykeep
8439endfunction
8440
8441" s:LocalFastBrowser: handles setting up/taking down fast browsing for the local browser {{{2
8442"
8443"     g:netrw_    Directory Is
8444"     fastbrowse  Local  Remote
8445"  slow   0         D      D      D=Deleting a buffer implies it will not be re-used (slow)
8446"  med    1         D      H      H=Hiding a buffer implies it may be re-used        (fast)
8447"  fast   2         H      H
8448"
8449"  Deleting a buffer means that it will be re-loaded when examined, hence "slow".
8450"  Hiding   a buffer means that it will be re-used   when examined, hence "fast".
8451"                       (re-using a buffer may not be as accurate)
8452"
8453"  s:netrw_events : doesn't exist, s:LocalFastBrowser() will install autocmds with medium-speed or fast browsing
8454"                   =1: autocmds installed, but ignore next FocusGained event to avoid initial double-refresh of listing.
8455"                       BufEnter may be first event, then a FocusGained event.  Ignore the first FocusGained event.
8456"                       If :Explore used: it sets s:netrw_events to 2, so no FocusGained events are ignored.
8457"                   =2: autocmds installed (doesn't ignore any FocusGained events)
8458function s:LocalFastBrowser()
8459
8460    " initialize browselist, a list of buffer numbers that the local browser has used
8461    if !exists("s:netrw_browselist")
8462        let s:netrw_browselist= []
8463    endif
8464
8465    " append current buffer to fastbrowse list
8466    if empty(s:netrw_browselist) || bufnr("%") > s:netrw_browselist[-1]
8467        call add(s:netrw_browselist,bufnr("%"))
8468    endif
8469
8470    " enable autocmd events to handle refreshing/removing local browser buffers
8471    "    If local browse buffer is currently showing: refresh it
8472    "    If local browse buffer is currently hidden : wipe it
8473    "    g:netrw_fastbrowse=0 : slow   speed, never re-use directory listing
8474    "                      =1 : medium speed, re-use directory listing for remote only
8475    "                      =2 : fast   speed, always re-use directory listing when possible
8476    if g:netrw_fastbrowse <= 1 && !exists("#ShellCmdPost") && !exists("s:netrw_events")
8477        let s:netrw_events= 1
8478        augroup AuNetrwEvent
8479            au!
8480            if has("win32")
8481                au ShellCmdPost                    *       call s:LocalBrowseRefresh()
8482            else
8483                au ShellCmdPost,FocusGained        *       call s:LocalBrowseRefresh()
8484            endif
8485        augroup END
8486
8487    " user must have changed fastbrowse to its fast setting, so remove
8488    " the associated autocmd events
8489    elseif g:netrw_fastbrowse > 1 && exists("#ShellCmdPost") && exists("s:netrw_events")
8490        unlet s:netrw_events
8491        augroup AuNetrwEvent
8492            au!
8493        augroup END
8494        augroup! AuNetrwEvent
8495    endif
8496endfunction
8497
8498function s:NetrwLocalListingList(dirname,setmaxfilenamelen)
8499    " get the list of files contained in the current directory
8500    let dirname    = a:dirname
8501    let dirnamelen = strlen(dirname)
8502    let filelist   = map(['.', '..'] + readdir(dirname), 'netrw#fs#PathJoin(dirname, v:val)')
8503
8504    if g:netrw_cygwin == 0 && has("win32")
8505    elseif index(filelist,'..') == -1 && dirname !~ '/'
8506        " include ../ in the glob() entry if its missing
8507        let filelist= filelist+[netrw#fs#ComposePath(dirname,"../")]
8508    endif
8509
8510    if a:setmaxfilenamelen && get(g:, 'netrw_dynamic_maxfilenamelen', 0)
8511        let filelistcopy           = map(deepcopy(filelist),'fnamemodify(v:val, ":t")')
8512        let g:netrw_maxfilenamelen = max(map(filelistcopy,'len(v:val)')) + 1
8513    endif
8514
8515    let resultfilelist = []
8516    for filename in filelist
8517
8518        let ftype = getftype(filename)
8519        if ftype ==# "link"
8520            " indicate a symbolic link
8521            let pfile= filename."@"
8522
8523        elseif ftype ==# "socket"
8524            " indicate a socket
8525            let pfile= filename."="
8526
8527        elseif ftype ==# "fifo"
8528            " indicate a fifo
8529            let pfile= filename."|"
8530
8531        elseif ftype ==# "dir"
8532            " indicate a directory
8533            let pfile= filename."/"
8534
8535        elseif exists("b:netrw_curdir") && b:netrw_curdir !~ '^.*://' && !isdirectory(s:NetrwFile(filename))
8536            if has("win32")
8537                if filename =~ '\.[eE][xX][eE]$' || filename =~ '\.[cC][oO][mM]$' || filename =~ '\.[bB][aA][tT]$'
8538                    " indicate an executable
8539                    let pfile= filename."*"
8540                else
8541                    " normal file
8542                    let pfile= filename
8543                endif
8544            elseif executable(filename)
8545                " indicate an executable
8546                let pfile= filename."*"
8547            else
8548                " normal file
8549                let pfile= filename
8550            endif
8551
8552        else
8553            " normal file
8554            let pfile= filename
8555        endif
8556
8557        if pfile =~ '//$'
8558            let pfile= substitute(pfile,'//$','/','e')
8559        endif
8560        let pfile= strpart(pfile,dirnamelen)
8561        let pfile= substitute(pfile,'^[/\\]','','e')
8562
8563        if w:netrw_liststyle == s:LONGLIST
8564            let longfile = printf("%-".g:netrw_maxfilenamelen."S",pfile)
8565            let sz       = getfsize(filename)
8566            let szlen    = 15 - (strdisplaywidth(longfile) - g:netrw_maxfilenamelen)
8567            let szlen    = (szlen > 0) ? szlen : 0
8568
8569            if g:netrw_sizestyle =~# "[hH]"
8570                let sz= s:NetrwHumanReadable(sz)
8571            endif
8572            let fsz  = printf("%".szlen."S",sz)
8573            let pfile= longfile."  ".fsz." ".strftime(g:netrw_timefmt,getftime(filename))
8574        endif
8575
8576        if     g:netrw_sort_by =~# "^t"
8577            " sort by time (handles time up to 1 quintillion seconds, US)
8578            " Decorate listing by prepending a timestamp/  .  Sorting will then be done based on time.
8579            let t  = getftime(filename)
8580            let ft = printf("%018d",t)
8581            let ftpfile= ft.'/'.pfile
8582            let resultfilelist += [ftpfile]
8583
8584        elseif g:netrw_sort_by =~ "^s"
8585            " sort by size (handles file sizes up to 1 quintillion bytes, US)
8586            let sz   = getfsize(filename)
8587            let fsz  = printf("%018d",sz)
8588            let fszpfile= fsz.'/'.pfile
8589            let resultfilelist += [fszpfile]
8590
8591        else
8592            " sort by name
8593            let resultfilelist += [pfile]
8594        endif
8595    endfor
8596
8597    return resultfilelist
8598endfunction
8599
8600" s:NetrwLocalExecute: uses system() to execute command under cursor ("X" command support) {{{2
8601function s:NetrwLocalExecute(cmd)
8602    let ykeep= @@
8603    " sanity check
8604    if !executable(a:cmd)
8605        call netrw#msg#Notify('ERROR', printf("the file<%s> is not executable!", a:cmd))
8606        let @@= ykeep
8607        return
8608    endif
8609
8610    let optargs= input(":!".a:cmd,"","file")
8611    let result= system(a:cmd.optargs)
8612
8613    " strip any ansi escape sequences off
8614    let result = substitute(result,"\e\\[[0-9;]*m","","g")
8615
8616    " show user the result(s)
8617    echomsg result
8618    let @@= ykeep
8619
8620endfunction
8621
8622" s:NetrwLocalRename: rename a local file or directory {{{2
8623function s:NetrwLocalRename(path) range
8624
8625    if !exists("w:netrw_bannercnt")
8626        let w:netrw_bannercnt= b:netrw_bannercnt
8627    endif
8628
8629    " preparation for removing multiple files/directories
8630    let ykeep     = @@
8631    let ctr       = a:firstline
8632    let svpos     = winsaveview()
8633    let all       = 0
8634
8635    " rename files given by the markfilelist
8636    if exists("s:netrwmarkfilelist_{bufnr('%')}")
8637        for oldname in s:netrwmarkfilelist_{bufnr("%")}
8638            if exists("subfrom")
8639                let newname= substitute(oldname,subfrom,subto,'')
8640            else
8641                call inputsave()
8642                let newname= input("Moving ".oldname." to : ",oldname,"file")
8643                call inputrestore()
8644                if newname =~ ''
8645                    " two ctrl-x's : ignore all of string preceding the ctrl-x's
8646                    let newname = substitute(newname,'^.*','','')
8647                elseif newname =~ ''
8648                    " one ctrl-x : ignore portion of string preceding ctrl-x but after last /
8649                    let newname = substitute(newname,'[^/]*','','')
8650                endif
8651                if newname =~ '^s/'
8652                    let subfrom = substitute(newname,'^s/\([^/]*\)/.*/$','\1','')
8653                    let subto   = substitute(newname,'^s/[^/]*/\(.*\)/$','\1','')
8654                    let newname = substitute(oldname,subfrom,subto,'')
8655                endif
8656            endif
8657            if !all && filereadable(newname)
8658                call inputsave()
8659                let response= input("File<".newname."> already exists; do you want to overwrite it? (y/all/n) ")
8660                call inputrestore()
8661                if response == "all"
8662                    let all= 1
8663                elseif response != "y" && response != "yes"
8664                    " refresh the directory
8665                    NetrwKeepj call s:NetrwRefresh(1,s:NetrwBrowseChgDir(1,'./',0))
8666                    NetrwKeepj call winrestview(svpos)
8667                    let @@= ykeep
8668                    return
8669                endif
8670            endif
8671            call rename(oldname,newname)
8672        endfor
8673        call s:NetrwUnmarkList(bufnr("%"),b:netrw_curdir)
8674
8675    else
8676
8677        " attempt to rename files/directories
8678        while ctr <= a:lastline
8679            exe "NetrwKeepj ".ctr
8680
8681            " sanity checks
8682            if line(".") < w:netrw_bannercnt
8683                let ctr= ctr + 1
8684                continue
8685            endif
8686            let curword= s:NetrwGetWord()
8687            if curword == "./" || curword == "../"
8688                let ctr= ctr + 1
8689                continue
8690            endif
8691
8692            NetrwKeepj norm! 0
8693            let reset_ssl = 0
8694            if exists('+shellslash') && !&ssl
8695                let reset_ssl = 1
8696                set ssl
8697            endif
8698            " Consistently use / as directory separator
8699            let oldname= netrw#fs#ComposePath(a:path,curword)
8700            if reset_ssl
8701                set nossl
8702            endif
8703
8704            call inputsave()
8705            let newname= input("Moving ".oldname." to : ",substitute(oldname,'/*$','','e'))
8706            call inputrestore()
8707
8708            call rename(oldname,newname)
8709            let ctr= ctr + 1
8710        endwhile
8711    endif
8712
8713    " refresh the directory
8714    NetrwKeepj call s:NetrwRefresh(1,s:NetrwBrowseChgDir(1,'./',0))
8715    NetrwKeepj call winrestview(svpos)
8716    let @@= ykeep
8717endfunction
8718
8719" s:NetrwLocalRm: {{{2
8720function s:NetrwLocalRm(path) range
8721    if !exists("w:netrw_bannercnt")
8722        let w:netrw_bannercnt = b:netrw_bannercnt
8723    endif
8724
8725    " preparation for removing multiple files/directories
8726    let ykeep = @@
8727    let ret = 0
8728    let all = 0
8729    let svpos = winsaveview()
8730
8731    if exists("s:netrwmarkfilelist_{bufnr('%')}")
8732        " remove all marked files
8733        for fname in s:netrwmarkfilelist_{bufnr("%")}
8734            let ok = s:NetrwLocalRmFile(a:path, fname, all)
8735            if ok =~# '^a\%[ll]$'
8736                let all = 1
8737            elseif ok =~# "n\%[o]"
8738                break
8739            endif
8740        endfor
8741        call s:NetrwUnMarkFile(1)
8742
8743    else
8744        " remove (multiple) files and directories
8745
8746        let keepsol = &l:sol
8747        setl nosol
8748        let ctr = a:firstline
8749        while ctr <= a:lastline
8750            exe "NetrwKeepj ".ctr
8751
8752            " sanity checks
8753            if line(".") < w:netrw_bannercnt
8754                let ctr = ctr + 1
8755                continue
8756            endif
8757
8758            let curword = s:NetrwGetWord()
8759            if curword == "./" || curword == "../"
8760                let ctr = ctr + 1
8761                continue
8762            endif
8763
8764            let ok = s:NetrwLocalRmFile(a:path, curword, all)
8765            if ok =~# '^a\%[ll]$'
8766                let all = 1
8767            elseif ok =~# "n\%[o]"
8768                break
8769            endif
8770
8771            let ctr = ctr + 1
8772        endwhile
8773
8774        let &l:sol = keepsol
8775    endif
8776
8777    " refresh the directory
8778    if bufname("%") != "NetrwMessage"
8779        NetrwKeepj call s:NetrwRefresh(1, s:NetrwBrowseChgDir(1, './', 0))
8780        NetrwKeepj call winrestview(svpos)
8781    endif
8782
8783    let @@= ykeep
8784endfunction
8785
8786" s:NetrwLocalRmFile: remove file fname given the path {{{2
8787"                     Give confirmation prompt unless all==1
8788function s:NetrwLocalRmFile(path, fname, all)
8789    let all = a:all
8790    let ok = ""
8791    let dir = 0
8792    NetrwKeepj norm! 0
8793    let rmfile = s:NetrwFile(netrw#fs#ComposePath(a:path, escape(a:fname, '\\')))->fnamemodify(':.')
8794
8795    " if not a directory
8796    if rmfile !~ '^"' && (rmfile =~ '@$' || rmfile !~ '[\/]$')
8797        let msg = "Confirm deletion of file <%s> [{y(es)},n(o),a(ll)]: "
8798    else
8799        let msg = "Confirm *recursive* deletion of directory <%s> [{y(es)},n(o),a(ll)]: "
8800        let dir = 1
8801    endif
8802
8803    " Ask confirmation
8804    if !all
8805        echohl Statement
8806        call inputsave()
8807        let ok = input(printf(msg, rmfile))
8808        call inputrestore()
8809        echohl NONE
8810        if ok =~# '^a\%[ll]$' || ok =~# '^y\%[es]$'
8811            let all = 1
8812        else
8813            let ok = 'no'
8814        endif
8815    endif
8816
8817    if !dir && (all || empty(ok))
8818        " This works because delete return 0 if successful
8819        if netrw#fs#Remove(rmfile)
8820            call netrw#msg#Notify('ERROR', printf("unable to delete <%s>!", rmfile))
8821        else
8822            " Remove file only if there are no pending changes
8823            execute printf('silent! bwipeout %s', fnameescape(rmfile))
8824        endif
8825
8826    elseif dir && (all || empty(ok))
8827        " Remove trailing /
8828        let rmfile = substitute(rmfile, '[\/]$', '', 'e')
8829        if delete(rmfile, "rf")
8830            call netrw#msg#Notify('ERROR', printf("unable to delete directory <%s>!", rmfile))
8831        endif
8832
8833    endif
8834
8835    return ok
8836endfunction
8837
8838" Support Functions: {{{1
8839
8840" netrw#Call: allows user-specified mappings to call internal netrw functions {{{2
8841function netrw#Call(funcname,...)
8842    return call("s:".a:funcname,a:000)
8843endfunction
8844
8845" netrw#Expose: allows UserMaps and pchk to look at otherwise script-local variables {{{2
8846"               I expect this function to be used in
8847"                 :PChkAssert netrw#Expose("netrwmarkfilelist")
8848"               for example.
8849function netrw#Expose(varname)
8850    if exists("s:".a:varname)
8851        exe "let retval= s:".a:varname
8852        if exists("g:netrw_pchk")
8853            if type(retval) == 3
8854                let retval = copy(retval)
8855                let i      = 0
8856                while i < len(retval)
8857                    let retval[i]= substitute(retval[i],expand("$HOME"),'~','')
8858                    let i        = i + 1
8859                endwhile
8860            endif
8861            return string(retval)
8862        else
8863        endif
8864    else
8865        let retval= "n/a"
8866    endif
8867
8868    return retval
8869endfunction
8870
8871" netrw#Modify: allows UserMaps to set (modify) script-local variables {{{2
8872function netrw#Modify(varname,newvalue)
8873    exe "let s:".a:varname."= ".string(a:newvalue)
8874endfunction
8875
8876"  netrw#RFC2396: converts %xx into characters {{{2
8877function netrw#RFC2396(fname)
8878    return substitute(a:fname, '%\(\x\x\)', '\=printf("%c","0x".submatch(1))', 'ge')
8879endfunction
8880
8881" netrw#UserMaps: supports user-specified maps {{{2
8882"                 see :help function()
8883"
8884"                 g:Netrw_UserMaps is a List with members such as:
8885"                       [[keymap sequence, function reference],...]
8886"
8887"                 The referenced function may return a string,
8888"                       refresh : refresh the display
8889"                       -other- : this string will be executed
8890"                 or it may return a List of strings.
8891"
8892"                 Each keymap-sequence will be set up with a nnoremap
8893"                 to invoke netrw#UserMaps(a:islocal).
8894"                 Related functions:
8895"                   netrw#Expose(varname)          -- see s:varname variables
8896"                   netrw#Modify(varname,newvalue) -- modify value of s:varname variable
8897"                   netrw#Call(funcname,...)       -- call internal netrw function with optional arguments
8898function netrw#UserMaps(islocal)
8899
8900    " set up usermaplist
8901    if exists("g:Netrw_UserMaps") && type(g:Netrw_UserMaps) == 3
8902        for umap in g:Netrw_UserMaps
8903            " if umap[0] is a string and umap[1] is a string holding a function name
8904            if type(umap[0]) == 1 && type(umap[1]) == 1
8905                exe "nno <buffer> <silent> ".umap[0]." :call <SID>UserMaps(".a:islocal.",'".umap[1]."')<cr>"
8906            else
8907                call netrw#msg#Notify('WARNING', printf('ignoring usermap <%s> -- not a [string,funcref] entry', string(umap[0])))
8908            endif
8909        endfor
8910    endif
8911endfunction
8912
8913" s:NetrwBadd: adds marked files to buffer list or vice versa {{{2
8914"              cb : bl2mf=0  add marked files to buffer list
8915"              cB : bl2mf=1  use bufferlist to mark files
8916"              (mnemonic: cb = copy (marked files) to buffer list)
8917function s:NetrwBadd(islocal,bl2mf)
8918    if a:bl2mf
8919        " cB: add buffer list to marked files
8920        redir => bufl
8921        ls
8922        redir END
8923        let bufl = map(split(bufl,"\n"),'substitute(v:val,''^.\{-}"\(.*\)".\{-}$'',''\1'','''')')
8924        for fname in bufl
8925            call s:NetrwMarkFile(a:islocal,fname)
8926        endfor
8927    else
8928        " cb: add marked files to buffer list
8929        for fname in s:netrwmarkfilelist_{bufnr("%")}
8930            exe "badd ".fnameescape(fname)
8931        endfor
8932        let curbufnr = bufnr("%")
8933        let curdir   = s:NetrwGetCurdir(a:islocal)
8934        call s:NetrwUnmarkList(curbufnr,curdir)                   " remove markings from local buffer
8935    endif
8936endfunction
8937
8938" s:DeleteBookmark: deletes a file/directory from Netrw's bookmark system {{{2
8939"   Related Functions: s:MakeBookmark() s:NetrwBookHistHandler() s:NetrwBookmark()
8940function s:DeleteBookmark(fname)
8941    call s:MergeBookmarks()
8942
8943    if exists("g:netrw_bookmarklist")
8944        let indx= index(g:netrw_bookmarklist,a:fname)
8945        if indx == -1
8946            let indx= 0
8947            while indx < len(g:netrw_bookmarklist)
8948                if g:netrw_bookmarklist[indx] =~ a:fname
8949                    call remove(g:netrw_bookmarklist,indx)
8950                    let indx= indx - 1
8951                endif
8952                let indx= indx + 1
8953            endwhile
8954        else
8955            " remove exact match
8956            call remove(g:netrw_bookmarklist,indx)
8957        endif
8958    endif
8959
8960endfunction
8961
8962" s:FileReadable: o/s independent filereadable {{{2
8963function s:FileReadable(fname)
8964    if g:netrw_cygwin
8965        let ret = filereadable(s:NetrwFile(substitute(a:fname,g:netrw_cygdrive.'/\(.\)','\1:/','')))
8966    else
8967        let ret = filereadable(s:NetrwFile(a:fname))
8968    endif
8969
8970    return ret
8971endfunction
8972
8973"  s:GetTempfile: gets a tempname that'll work for various o/s's {{{2
8974"                 Places correct suffix on end of temporary filename,
8975"                 using the suffix provided with fname
8976function s:GetTempfile(fname)
8977
8978    if !exists("b:netrw_tmpfile")
8979        " get a brand new temporary filename
8980        let tmpfile= tempname()
8981
8982        let tmpfile= substitute(tmpfile,'\','/','ge')
8983
8984        " sanity check -- does the temporary file's directory exist?
8985        if !isdirectory(s:NetrwFile(substitute(tmpfile,'[^/]\+$','','e')))
8986            call netrw#msg#Notify('ERROR', printf('your <%s> directory is missing!', substitute(tmpfile,'[^/]\+$','','e')))
8987            return ""
8988        endif
8989
8990        " let netrw#NetSource() know about the tmpfile
8991        let s:netrw_tmpfile= tmpfile " used by netrw#NetSource() and netrw#BrowseX()
8992
8993        " o/s dependencies
8994        if g:netrw_cygwin != 0
8995            let tmpfile = substitute(tmpfile,'^\(\a\):',g:netrw_cygdrive.'/\1','e')
8996        elseif has("win32")
8997            if !exists("+shellslash") || !&ssl
8998                let tmpfile = substitute(tmpfile,'/','\','g')
8999            endif
9000        else
9001            let tmpfile = tmpfile
9002        endif
9003        let b:netrw_tmpfile= tmpfile
9004    else
9005        " re-use temporary filename
9006        let tmpfile= b:netrw_tmpfile
9007    endif
9008
9009    " use fname's suffix for the temporary file
9010    " Restrict the suffix to word characters so shell metacharacters in a
9011    " remote filename (e.g. sftp://host/foo.txt;id) cannot ride along into
9012    " the tempfile name and out into a downstream shell command.
9013    if a:fname != ""
9014        if a:fname =~ '\.\w\+$'
9015            if a:fname =~ '\.tar\.gz$' || a:fname =~ '\.tar\.bz2$' || a:fname =~ '\.tar\.xz$'
9016                let suffix = ".tar".substitute(a:fname,'^.*\(\.\w\+\)$','\1','e')
9017            elseif a:fname =~ '.txz$'
9018                let suffix = ".txz".substitute(a:fname,'^.*\(\.\w\+\)$','\1','e')
9019            else
9020                let suffix = substitute(a:fname,'^.*\(\.\w\+\)$','\1','e')
9021            endif
9022            let tmpfile= substitute(tmpfile,'\.tmp$','','e')
9023            let tmpfile .= suffix
9024            let s:netrw_tmpfile= tmpfile " supports netrw#NetSource()
9025        endif
9026    endif
9027
9028    return tmpfile
9029endfunction
9030
9031" s:MakeSshCmd: transforms input command using USEPORT HOSTNAME into {{{2
9032"               a correct command for use with a system() call
9033function s:MakeSshCmd(sshcmd)
9034    let machine = shellescape(s:machine, 1)
9035    if s:user != ''
9036        let machine    = shellescape(s:user, 1).'@'.machine
9037    endif
9038    let sshcmd = substitute(a:sshcmd,'\<HOSTNAME\>',machine,'')
9039    if exists("g:netrw_port") && g:netrw_port != ""
9040        let sshcmd= substitute(sshcmd,"USEPORT",g:netrw_sshport.' '.shellescape(g:netrw_port,1),'')
9041    elseif exists("s:port") && s:port != ""
9042        let sshcmd= substitute(sshcmd,"USEPORT",g:netrw_sshport.' '.shellescape(s:port,1),'')
9043    else
9044        let sshcmd= substitute(sshcmd,"USEPORT ",'','')
9045    endif
9046    return sshcmd
9047endfunction
9048
9049" s:MakeBookmark: enters a bookmark into Netrw's bookmark system {{{2
9050" Note that bookmark paths should always be absolute.
9051function s:MakeBookmark(fname)
9052
9053    if !exists("g:netrw_bookmarklist")
9054        let g:netrw_bookmarklist = []
9055    endif
9056
9057    " Normalize path to prevent duplicate entries
9058    let bookmark_path = netrw#fs#AbsPath(s:NetrwFile(a:fname))
9059    let ignore_case = 0
9060    if has('win32')
9061        let bookmark_path = substitute(bookmark_path, '\\', '/', 'ge')
9062        let ignore_case = 1
9063    endif
9064    let bookmark_path = simplify(bookmark_path)
9065
9066    if isdirectory(bookmark_path) && bookmark_path !~ '/$'
9067        let bookmark_path .= '/'
9068    endif
9069
9070    if index(g:netrw_bookmarklist, bookmark_path, 0, ignore_case) == -1
9071        " Not currently in the bookmarks list, so include it
9072        call add(g:netrw_bookmarklist, bookmark_path)
9073        call sort(g:netrw_bookmarklist)
9074    endif
9075
9076endfunction
9077
9078" s:MergeBookmarks: merge current bookmarks with saved bookmarks {{{2
9079function s:MergeBookmarks()
9080    " get bookmarks from .netrwbook file
9081    let savefile= s:NetrwHome()."/.netrwbook"
9082    if filereadable(s:NetrwFile(savefile))
9083        NetrwKeepj call s:NetrwBookHistSave()
9084        NetrwKeepj call delete(savefile)
9085    endif
9086endfunction
9087
9088" s:NetrwBMShow: {{{2
9089function s:NetrwBMShow()
9090    redir => bmshowraw
9091    menu
9092    redir END
9093    let bmshowlist = split(bmshowraw,'\n')
9094    if bmshowlist != []
9095        let bmshowfuncs= filter(bmshowlist,'v:val =~# "<SNR>\\d\\+_BMShow()"')
9096        if bmshowfuncs != []
9097            let bmshowfunc = substitute(bmshowfuncs[0],'^.*:\(call.*BMShow()\).*$','\1','')
9098            if bmshowfunc =~# '^call.*BMShow()'
9099                exe "sil! NetrwKeepj ".bmshowfunc
9100            endif
9101        endif
9102    endif
9103endfunction
9104
9105" s:NetrwCursor: responsible for setting cursorline/cursorcolumn based upon g:netrw_cursor {{{2
9106function s:NetrwCursor(editfile)
9107    if !exists("w:netrw_liststyle")
9108        let w:netrw_liststyle= g:netrw_liststyle
9109    endif
9110
9111
9112    if &ft != "netrw"
9113    " if the current window isn't a netrw directory listing window, then use user cursorline/column
9114    " settings.  Affects when netrw is used to read/write a file using scp/ftp/etc.
9115
9116    elseif g:netrw_cursor == 8
9117        if w:netrw_liststyle == s:WIDELIST
9118            setl cursorline
9119            setl cursorcolumn
9120        else
9121            setl cursorline
9122        endif
9123    elseif g:netrw_cursor == 7
9124        setl cursorline
9125    elseif g:netrw_cursor == 6
9126        if w:netrw_liststyle == s:WIDELIST
9127            setl cursorline
9128        endif
9129    elseif g:netrw_cursor == 4
9130        " all styles: cursorline, cursorcolumn
9131        setl cursorline
9132        setl cursorcolumn
9133
9134    elseif g:netrw_cursor == 3
9135        " thin-long-tree: cursorline, user's cursorcolumn
9136        " wide          : cursorline, cursorcolumn
9137        if w:netrw_liststyle == s:WIDELIST
9138            setl cursorline
9139            setl cursorcolumn
9140        else
9141            setl cursorline
9142        endif
9143
9144    elseif g:netrw_cursor == 2
9145        " thin-long-tree: cursorline, user's cursorcolumn
9146        " wide          : cursorline, user's cursorcolumn
9147        setl cursorline
9148
9149    elseif g:netrw_cursor == 1
9150        " thin-long-tree: user's cursorline, user's cursorcolumn
9151        " wide          : cursorline,        user's cursorcolumn
9152        if w:netrw_liststyle == s:WIDELIST
9153            setl cursorline
9154        else
9155        endif
9156
9157    else
9158        " all styles: user's cursorline, user's cursorcolumn
9159        let &l:cursorline   = s:netrw_usercul
9160        let &l:cursorcolumn = s:netrw_usercuc
9161    endif
9162
9163endfunction
9164
9165" s:RestoreCursorline: restores cursorline/cursorcolumn to original user settings {{{2
9166function s:RestoreCursorline()
9167    if exists("s:netrw_usercul")
9168        let &l:cursorline   = s:netrw_usercul
9169    endif
9170    if exists("s:netrw_usercuc")
9171        let &l:cursorcolumn = s:netrw_usercuc
9172    endif
9173endfunction
9174
9175" s:RestoreRegister: restores all registers given in the dict {{{2
9176function s:RestoreRegister(dict)
9177    for [key, val] in items(a:dict)
9178        if key == 'unnamed'
9179            let key = ''
9180        endif
9181        call setreg(key, val[0], val[1])
9182    endfor
9183endfunction
9184
9185" s:NetrwEnew: opens a new buffer, passes netrw buffer variables through {{{2
9186function s:NetrwEnew(...)
9187
9188    " Clean out the last buffer:
9189    " Check if the last buffer has # > 1, is unlisted, is unnamed, and does not appear in a window
9190    " If so, delete it.
9191    let bufid = bufnr('$')
9192    if bufid > 1 && !buflisted(bufid) && bufloaded(bufid) && bufname(bufid) == "" && bufwinid(bufid) == -1
9193        execute printf("silent! bdelete! %s", bufid)
9194    endif
9195
9196    " grab a function-local-variable copy of buffer variables
9197    if exists("b:netrw_bannercnt")      |let netrw_bannercnt       = b:netrw_bannercnt      |endif
9198    if exists("b:netrw_browser_active") |let netrw_browser_active  = b:netrw_browser_active |endif
9199    if exists("b:netrw_cpf")            |let netrw_cpf             = b:netrw_cpf            |endif
9200    if exists("b:netrw_curdir")         |let netrw_curdir          = b:netrw_curdir         |endif
9201    if exists("b:netrw_explore_bufnr")  |let netrw_explore_bufnr   = b:netrw_explore_bufnr  |endif
9202    if exists("b:netrw_explore_indx")   |let netrw_explore_indx    = b:netrw_explore_indx   |endif
9203    if exists("b:netrw_explore_line")   |let netrw_explore_line    = b:netrw_explore_line   |endif
9204    if exists("b:netrw_explore_list")   |let netrw_explore_list    = b:netrw_explore_list   |endif
9205    if exists("b:netrw_explore_listlen")|let netrw_explore_listlen = b:netrw_explore_listlen|endif
9206    if exists("b:netrw_explore_mtchcnt")|let netrw_explore_mtchcnt = b:netrw_explore_mtchcnt|endif
9207    if exists("b:netrw_fname")          |let netrw_fname           = b:netrw_fname          |endif
9208    if exists("b:netrw_lastfile")       |let netrw_lastfile        = b:netrw_lastfile       |endif
9209    if exists("b:netrw_liststyle")      |let netrw_liststyle       = b:netrw_liststyle      |endif
9210    if exists("b:netrw_method")         |let netrw_method          = b:netrw_method         |endif
9211    if exists("b:netrw_option")         |let netrw_option          = b:netrw_option         |endif
9212    if exists("b:netrw_prvdir")         |let netrw_prvdir          = b:netrw_prvdir         |endif
9213
9214    NetrwKeepj call s:NetrwOptionsRestore("w:")
9215    " when tree listing uses file TreeListing... a new buffer is made.
9216    " Want the old buffer to be unlisted.
9217    " COMBAK: this causes a problem, see P43
9218    "  setl nobl
9219    let netrw_keepdiff= &l:diff
9220    call s:NetrwEditFile("enew!","","")
9221    let &l:diff= netrw_keepdiff
9222    NetrwKeepj call s:NetrwOptionsSave("w:")
9223
9224    " copy function-local-variables to buffer variable equivalents
9225    if exists("netrw_bannercnt")      |let b:netrw_bannercnt       = netrw_bannercnt      |endif
9226    if exists("netrw_browser_active") |let b:netrw_browser_active  = netrw_browser_active |endif
9227    if exists("netrw_cpf")            |let b:netrw_cpf             = netrw_cpf            |endif
9228    if exists("netrw_curdir")         |let b:netrw_curdir          = netrw_curdir         |endif
9229    if exists("netrw_explore_bufnr")  |let b:netrw_explore_bufnr   = netrw_explore_bufnr  |endif
9230    if exists("netrw_explore_indx")   |let b:netrw_explore_indx    = netrw_explore_indx   |endif
9231    if exists("netrw_explore_line")   |let b:netrw_explore_line    = netrw_explore_line   |endif
9232    if exists("netrw_explore_list")   |let b:netrw_explore_list    = netrw_explore_list   |endif
9233    if exists("netrw_explore_listlen")|let b:netrw_explore_listlen = netrw_explore_listlen|endif
9234    if exists("netrw_explore_mtchcnt")|let b:netrw_explore_mtchcnt = netrw_explore_mtchcnt|endif
9235    if exists("netrw_fname")          |let b:netrw_fname           = netrw_fname          |endif
9236    if exists("netrw_lastfile")       |let b:netrw_lastfile        = netrw_lastfile       |endif
9237    if exists("netrw_liststyle")      |let b:netrw_liststyle       = netrw_liststyle      |endif
9238    if exists("netrw_method")         |let b:netrw_method          = netrw_method         |endif
9239    if exists("netrw_option")         |let b:netrw_option          = netrw_option         |endif
9240    if exists("netrw_prvdir")         |let b:netrw_prvdir          = netrw_prvdir         |endif
9241
9242    if a:0 > 0
9243        let b:netrw_curdir= a:1
9244        if b:netrw_curdir =~ '/$'
9245            if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST
9246                setl nobl
9247                file NetrwTreeListing
9248                setl nobl bt=nowrite bh=hide
9249                nno <silent> <buffer> [    :sil call <SID>TreeListMove('[')<cr>
9250                nno <silent> <buffer> ]    :sil call <SID>TreeListMove(']')<cr>
9251            else
9252                call s:NetrwBufRename(b:netrw_curdir)
9253            endif
9254        endif
9255    endif
9256endfunction
9257
9258" s:NetrwInsureWinVars: insure that a netrw buffer has its w: variables in spite of a wincmd v or s {{{2
9259function s:NetrwInsureWinVars()
9260    if !exists("w:netrw_liststyle")
9261        let curbuf = bufnr("%")
9262        let curwin = winnr()
9263        let iwin   = 1
9264        while iwin <= winnr("$")
9265            exe iwin."wincmd w"
9266            if winnr() != curwin && bufnr("%") == curbuf && exists("w:netrw_liststyle")
9267                " looks like ctrl-w_s or ctrl-w_v was used to split a netrw buffer
9268                let winvars= w:
9269                break
9270            endif
9271            let iwin= iwin + 1
9272        endwhile
9273        exe "keepalt ".curwin."wincmd w"
9274        if exists("winvars")
9275            for k in keys(winvars)
9276                let w:{k}= winvars[k]
9277            endfor
9278        endif
9279    endif
9280endfunction
9281
9282" s:NetrwLcd: handles changing the (local) directory {{{2
9283"   Returns: 0=success
9284"           -1=failed
9285function s:NetrwLcd(newdir)
9286
9287    let err472= 0
9288    try
9289        exe 'NetrwKeepj sil lcd '.fnameescape(a:newdir)
9290    catch /^Vim\%((\a\+)\)\=:E344/
9291        " Vim's lcd fails with E344 when attempting to go above the 'root' of a Windows share.
9292        " Therefore, detect if a Windows share is present, and if E344 occurs, just settle at
9293        " 'root' (ie. '\').  The share name may start with either backslashes ('\\Foo') or
9294        " forward slashes ('//Foo'), depending on whether backslashes have been converted to
9295        " forward slashes by earlier code; so check for both.
9296        if has("win32") && !g:netrw_cygwin
9297            if a:newdir =~ '^\\\\\w\+' || a:newdir =~ '^//\w\+'
9298                let dirname = '\'
9299                exe 'NetrwKeepj sil lcd '.fnameescape(dirname)
9300            endif
9301        endif
9302    catch /^Vim\%((\a\+)\)\=:E472/
9303        let err472= 1
9304    endtry
9305
9306    if err472
9307        call netrw#msg#Notify('ERROR', printf('unable to change directory to <%s> (permissions?)', a:newdir))
9308        if !exists("w:netrw_prvdir")
9309            call s:NetrwOptionsRestore("w:")
9310            exe "setl ".g:netrw_bufsettings
9311        endif
9312        return -1
9313    endif
9314
9315    return 0
9316endfunction
9317
9318" s:NetrwSaveWordPosn: used to keep cursor on same word after refresh, {{{2
9319" changed sorting, etc.  Also see s:NetrwRestoreWordPosn().
9320function s:NetrwSaveWordPosn()
9321    let s:netrw_saveword= '^'.fnameescape(getline('.')).'$'
9322endfunction
9323
9324" s:NetrwHumanReadable: takes a number and makes it "human readable" {{{2
9325"                       1000 -> 1K, 1000000 -> 1M, 1000000000 -> 1G
9326function s:NetrwHumanReadable(sz)
9327
9328    if g:netrw_sizestyle ==# 'h'
9329        if a:sz >= 1000000000
9330            let sz = printf("%.1f",a:sz/1000000000.0)."g"
9331        elseif a:sz >= 10000000
9332            let sz = printf("%d",a:sz/1000000)."m"
9333        elseif a:sz >= 1000000
9334            let sz = printf("%.1f",a:sz/1000000.0)."m"
9335        elseif a:sz >= 10000
9336            let sz = printf("%d",a:sz/1000)."k"
9337        elseif a:sz >= 1000
9338            let sz = printf("%.1f",a:sz/1000.0)."k"
9339        else
9340            let sz= a:sz
9341        endif
9342
9343    elseif g:netrw_sizestyle ==# 'H'
9344        if a:sz >= 1073741824
9345            let sz = printf("%.1f",a:sz/1073741824.0)."G"
9346        elseif a:sz >= 10485760
9347            let sz = printf("%d",a:sz/1048576)."M"
9348        elseif a:sz >= 1048576
9349            let sz = printf("%.1f",a:sz/1048576.0)."M"
9350        elseif a:sz >= 10240
9351            let sz = printf("%d",a:sz/1024)."K"
9352        elseif a:sz >= 1024
9353            let sz = printf("%.1f",a:sz/1024.0)."K"
9354        else
9355            let sz= a:sz
9356        endif
9357
9358    else
9359        let sz= a:sz
9360    endif
9361
9362    return sz
9363endfunction
9364
9365" s:NetrwRestoreWordPosn: used to keep cursor on same word after refresh, {{{2
9366"  changed sorting, etc.  Also see s:NetrwSaveWordPosn().
9367function s:NetrwRestoreWordPosn()
9368    sil! call search(s:netrw_saveword,'w')
9369endfunction
9370
9371" s:RestoreBufVars: {{{2
9372function s:RestoreBufVars()
9373
9374    if exists("s:netrw_curdir")        |let b:netrw_curdir         = s:netrw_curdir        |endif
9375    if exists("s:netrw_lastfile")      |let b:netrw_lastfile       = s:netrw_lastfile      |endif
9376    if exists("s:netrw_method")        |let b:netrw_method         = s:netrw_method        |endif
9377    if exists("s:netrw_fname")         |let b:netrw_fname          = s:netrw_fname         |endif
9378    if exists("s:netrw_machine")       |let b:netrw_machine        = s:netrw_machine       |endif
9379    if exists("s:netrw_browser_active")|let b:netrw_browser_active = s:netrw_browser_active|endif
9380
9381endfunction
9382
9383" s:RemotePathAnalysis: {{{2
9384function s:RemotePathAnalysis(dirname)
9385
9386    "                method   ://    user    @      machine      :port           /path
9387    let dirpat  = '^\(\w\{-}\)://\(\([^@]\+\)@\)\=\([^/:#]\+\)\%([:#]\(\d\+\)\)\=/\(.*\)$'
9388    let s:method  = substitute(a:dirname,dirpat,'\1','')
9389    let s:user    = substitute(a:dirname,dirpat,'\3','')
9390    let s:machine = substitute(a:dirname,dirpat,'\4','')
9391    let s:port    = substitute(a:dirname,dirpat,'\5','')
9392    let s:path    = substitute(a:dirname,dirpat,'\6','')
9393    let s:fname   = substitute(s:path,'^.*/\ze.','','')
9394    if s:machine =~ '@'
9395        let dirpat    = '^\(.*\)@\(.\{-}\)$'
9396        let s:user    = s:user.'@'.substitute(s:machine,dirpat,'\1','')
9397        let s:machine = substitute(s:machine,dirpat,'\2','')
9398    endif
9399
9400
9401endfunction
9402
9403" s:RemoteSystem: runs a command on a remote host using ssh {{{2
9404"                 Returns status
9405" Runs system() on
9406"    [cd REMOTEDIRPATH;] a:cmd
9407" Note that it doesn't do netrw#os#Escape(a:cmd)!
9408function s:RemoteSystem(cmd)
9409    if !executable(g:netrw_ssh_cmd)
9410        call netrw#msg#Notify('ERROR', printf('g:netrw_ssh_cmd<%s> is not executable!', g:netrw_ssh_cmd))
9411    elseif !exists("b:netrw_curdir")
9412        call netrw#msg#Notify('ERROR', "for some reason b:netrw_curdir doesn't exist!")
9413    else
9414        let cmd      = s:MakeSshCmd(g:netrw_ssh_cmd." USEPORT HOSTNAME")
9415        let remotedir= substitute(b:netrw_curdir,'^.*//[^/]\+/\(.*\)$','\1','')
9416        if remotedir != ""
9417            let cmd= cmd.' cd '.netrw#os#Escape(remotedir).";"
9418        else
9419            let cmd= cmd.' '
9420        endif
9421        let cmd= cmd.a:cmd
9422        let ret= system(cmd)
9423    endif
9424    return ret
9425endfunction
9426
9427" s:RestoreWinVars: (used by Explore() and NetrwSplit()) {{{2
9428function s:RestoreWinVars()
9429    if exists("s:bannercnt")      |let w:netrw_bannercnt       = s:bannercnt      |unlet s:bannercnt      |endif
9430    if exists("s:col")            |let w:netrw_col             = s:col            |unlet s:col            |endif
9431    if exists("s:curdir")         |let w:netrw_curdir          = s:curdir         |unlet s:curdir         |endif
9432    if exists("s:explore_bufnr")  |let w:netrw_explore_bufnr   = s:explore_bufnr  |unlet s:explore_bufnr  |endif
9433    if exists("s:explore_indx")   |let w:netrw_explore_indx    = s:explore_indx   |unlet s:explore_indx   |endif
9434    if exists("s:explore_line")   |let w:netrw_explore_line    = s:explore_line   |unlet s:explore_line   |endif
9435    if exists("s:explore_listlen")|let w:netrw_explore_listlen = s:explore_listlen|unlet s:explore_listlen|endif
9436    if exists("s:explore_list")   |let w:netrw_explore_list    = s:explore_list   |unlet s:explore_list   |endif
9437    if exists("s:explore_mtchcnt")|let w:netrw_explore_mtchcnt = s:explore_mtchcnt|unlet s:explore_mtchcnt|endif
9438    if exists("s:fpl")            |let w:netrw_fpl             = s:fpl            |unlet s:fpl            |endif
9439    if exists("s:hline")          |let w:netrw_hline           = s:hline          |unlet s:hline          |endif
9440    if exists("s:line")           |let w:netrw_line            = s:line           |unlet s:line           |endif
9441    if exists("s:liststyle")      |let w:netrw_liststyle       = s:liststyle      |unlet s:liststyle      |endif
9442    if exists("s:method")         |let w:netrw_method          = s:method         |unlet s:method         |endif
9443    if exists("s:prvdir")         |let w:netrw_prvdir          = s:prvdir         |unlet s:prvdir         |endif
9444    if exists("s:treedict")       |let w:netrw_treedict        = s:treedict       |unlet s:treedict       |endif
9445    if exists("s:treetop")        |let w:netrw_treetop         = s:treetop        |unlet s:treetop        |endif
9446    if exists("s:winnr")          |let w:netrw_winnr           = s:winnr          |unlet s:winnr          |endif
9447endfunction
9448
9449" s:Rexplore: implements returning from a buffer to a netrw directory {{{2
9450"
9451"             s:SetRexDir() sets up <2-leftmouse> maps (if g:netrw_retmap
9452"             is true) and a command, :Rexplore, which call this function.
9453"
9454"             s:netrw_posn is set up by s:NetrwBrowseChgDir()
9455"
9456"             s:rexposn_BUFNR used to save/restore cursor position
9457function s:NetrwRexplore(islocal,dirname)
9458    if exists("s:netrwdrag")
9459        return
9460    endif
9461
9462    if &ft == "netrw" && exists("w:netrw_rexfile") && w:netrw_rexfile != ""
9463        " a :Rex while in a netrw buffer means: edit the file in w:netrw_rexfile
9464        exe "NetrwKeepj e ".w:netrw_rexfile
9465        unlet w:netrw_rexfile
9466        return
9467    endif
9468
9469    " ---------------------------
9470    " :Rex issued while in a file
9471    " ---------------------------
9472
9473    " record current file so :Rex can return to it from netrw
9474    let w:netrw_rexfile= expand("%")
9475
9476    if !exists("w:netrw_rexlocal")
9477        return
9478    endif
9479    if w:netrw_rexlocal
9480        NetrwKeepj call netrw#LocalBrowseCheck(w:netrw_rexdir)
9481    else
9482        NetrwKeepj call s:NetrwBrowse(0,w:netrw_rexdir)
9483    endif
9484    if exists("s:initbeval")
9485        setl beval
9486    endif
9487    if exists("s:rexposn_".bufnr("%"))
9488        " restore position in directory listing
9489        NetrwKeepj call winrestview(s:rexposn_{bufnr('%')})
9490        if exists("s:rexposn_".bufnr('%'))
9491            unlet s:rexposn_{bufnr('%')}
9492        endif
9493    else
9494    endif
9495
9496    if has("syntax") && exists("g:syntax_on") && g:syntax_on
9497        if exists("s:explore_match")
9498            exe "2match netrwMarkFile /".s:explore_match."/"
9499        endif
9500    endif
9501
9502endfunction
9503
9504" s:SaveBufVars: save selected b: variables to s: variables {{{2
9505"                use s:RestoreBufVars() to restore b: variables from s: variables
9506function s:SaveBufVars()
9507
9508    if exists("b:netrw_curdir")        |let s:netrw_curdir         = b:netrw_curdir        |endif
9509    if exists("b:netrw_lastfile")      |let s:netrw_lastfile       = b:netrw_lastfile      |endif
9510    if exists("b:netrw_method")        |let s:netrw_method         = b:netrw_method        |endif
9511    if exists("b:netrw_fname")         |let s:netrw_fname          = b:netrw_fname         |endif
9512    if exists("b:netrw_machine")       |let s:netrw_machine        = b:netrw_machine       |endif
9513    if exists("b:netrw_browser_active")|let s:netrw_browser_active = b:netrw_browser_active|endif
9514
9515endfunction
9516
9517" s:SavePosn: saves position associated with current buffer into a dictionary {{{2
9518function s:SavePosn(posndict)
9519
9520    if !exists("a:posndict[bufnr('%')]")
9521        let a:posndict[bufnr("%")]= []
9522    endif
9523    call add(a:posndict[bufnr("%")],winsaveview())
9524
9525    return a:posndict
9526endfunction
9527
9528" s:RestorePosn: restores position associated with current buffer using dictionary {{{2
9529function s:RestorePosn(posndict)
9530    if exists("a:posndict")
9531        if has_key(a:posndict,bufnr("%"))
9532            let posnlen= len(a:posndict[bufnr("%")])
9533            if posnlen > 0
9534                let posnlen= posnlen - 1
9535                call winrestview(a:posndict[bufnr("%")][posnlen])
9536                call remove(a:posndict[bufnr("%")],posnlen)
9537            endif
9538        endif
9539    endif
9540endfunction
9541
9542" s:SaveWinVars: (used by Explore() and NetrwSplit()) {{{2
9543function s:SaveWinVars()
9544    if exists("w:netrw_bannercnt")      |let s:bannercnt       = w:netrw_bannercnt      |endif
9545    if exists("w:netrw_col")            |let s:col             = w:netrw_col            |endif
9546    if exists("w:netrw_curdir")         |let s:curdir          = w:netrw_curdir         |endif
9547    if exists("w:netrw_explore_bufnr")  |let s:explore_bufnr   = w:netrw_explore_bufnr  |endif
9548    if exists("w:netrw_explore_indx")   |let s:explore_indx    = w:netrw_explore_indx   |endif
9549    if exists("w:netrw_explore_line")   |let s:explore_line    = w:netrw_explore_line   |endif
9550    if exists("w:netrw_explore_listlen")|let s:explore_listlen = w:netrw_explore_listlen|endif
9551    if exists("w:netrw_explore_list")   |let s:explore_list    = w:netrw_explore_list   |endif
9552    if exists("w:netrw_explore_mtchcnt")|let s:explore_mtchcnt = w:netrw_explore_mtchcnt|endif
9553    if exists("w:netrw_fpl")            |let s:fpl             = w:netrw_fpl            |endif
9554    if exists("w:netrw_hline")          |let s:hline           = w:netrw_hline          |endif
9555    if exists("w:netrw_line")           |let s:line            = w:netrw_line           |endif
9556    if exists("w:netrw_liststyle")      |let s:liststyle       = w:netrw_liststyle      |endif
9557    if exists("w:netrw_method")         |let s:method          = w:netrw_method         |endif
9558    if exists("w:netrw_prvdir")         |let s:prvdir          = w:netrw_prvdir         |endif
9559    if exists("w:netrw_treedict")       |let s:treedict        = w:netrw_treedict       |endif
9560    if exists("w:netrw_treetop")        |let s:treetop         = w:netrw_treetop        |endif
9561    if exists("w:netrw_winnr")          |let s:winnr           = w:netrw_winnr          |endif
9562endfunction
9563
9564" s:SetBufWinVars: (used by NetrwBrowse() and LocalBrowseCheck()) {{{2
9565"   To allow separate windows to have their own activities, such as
9566"   Explore **/pattern, several variables have been made window-oriented.
9567"   However, when the user splits a browser window (ex: ctrl-w s), these
9568"   variables are not inherited by the new window.  SetBufWinVars() and
9569"   UseBufWinVars() get around that.
9570function s:SetBufWinVars()
9571    if exists("w:netrw_liststyle")      |let b:netrw_liststyle      = w:netrw_liststyle      |endif
9572    if exists("w:netrw_bannercnt")      |let b:netrw_bannercnt      = w:netrw_bannercnt      |endif
9573    if exists("w:netrw_method")         |let b:netrw_method         = w:netrw_method         |endif
9574    if exists("w:netrw_prvdir")         |let b:netrw_prvdir         = w:netrw_prvdir         |endif
9575    if exists("w:netrw_explore_indx")   |let b:netrw_explore_indx   = w:netrw_explore_indx   |endif
9576    if exists("w:netrw_explore_listlen")|let b:netrw_explore_listlen= w:netrw_explore_listlen|endif
9577    if exists("w:netrw_explore_mtchcnt")|let b:netrw_explore_mtchcnt= w:netrw_explore_mtchcnt|endif
9578    if exists("w:netrw_explore_bufnr")  |let b:netrw_explore_bufnr  = w:netrw_explore_bufnr  |endif
9579    if exists("w:netrw_explore_line")   |let b:netrw_explore_line   = w:netrw_explore_line   |endif
9580    if exists("w:netrw_explore_list")   |let b:netrw_explore_list   = w:netrw_explore_list   |endif
9581endfunction
9582
9583" s:SetRexDir: set directory for :Rexplore {{{2
9584function s:SetRexDir(islocal,dirname)
9585    let w:netrw_rexdir         = a:dirname
9586    let w:netrw_rexlocal       = a:islocal
9587    let s:rexposn_{bufnr("%")} = winsaveview()
9588endfunction
9589
9590" s:ShowLink: used to modify thin and tree listings to show links {{{2
9591function s:ShowLink()
9592    if exists("b:netrw_curdir")
9593        keepp :norm! $?\a
9594        "call histdel("/",-1)
9595        if exists("w:netrw_liststyle") && w:netrw_liststyle == s:TREELIST && exists("w:netrw_treetop")
9596            let basedir = s:NetrwTreePath(w:netrw_treetop)
9597        else
9598            let basedir = b:netrw_curdir.'/'
9599        endif
9600        let fname = basedir.s:NetrwGetWord()
9601        let resname = resolve(fname)
9602        if resname =~ '^\M'.basedir
9603            let dirlen  = strlen(basedir)
9604            let resname = strpart(resname,dirlen)
9605        endif
9606        let modline = getline(".")."\t --> ".resname
9607        setl noro ma
9608        call setline(".",modline)
9609        setl ro noma nomod
9610    endif
9611endfunction
9612
9613" s:ShowStyle: {{{2
9614function s:ShowStyle()
9615    if !exists("w:netrw_liststyle")
9616        let liststyle= g:netrw_liststyle
9617    else
9618        let liststyle= w:netrw_liststyle
9619    endif
9620    if     liststyle == s:THINLIST
9621        return s:THINLIST.":thin"
9622    elseif liststyle == s:LONGLIST
9623        return s:LONGLIST.":long"
9624    elseif liststyle == s:WIDELIST
9625        return s:WIDELIST.":wide"
9626    elseif liststyle == s:TREELIST
9627        return s:TREELIST.":tree"
9628    else
9629        return 'n/a'
9630    endif
9631endfunction
9632
9633" s:TreeListMove: supports [[, ]], [], and ][ in tree mode {{{2
9634function s:TreeListMove(dir)
9635    let curline      = getline('.')
9636    let prvline      = (line(".") > 1)?         getline(line(".")-1) : ''
9637    let nxtline      = (line(".") < line("$"))? getline(line(".")+1) : ''
9638    let curindent    = substitute(getline('.'),'^\(\%('.s:treedepthstring.'\)*\)[^'.s:treedepthstring.'].\{-}$','\1','e')
9639    let indentm1     = substitute(curindent,'^'.s:treedepthstring,'','')
9640    let treedepthchr = substitute(s:treedepthstring,' ','','g')
9641    let stopline     = exists("w:netrw_bannercnt")? w:netrw_bannercnt : 1
9642    "  COMBAK : need to handle when on a directory
9643    "  COMBAK : need to handle ]] and ][.  In general, needs work!!!
9644    if curline !~ '/$'
9645        if     a:dir == '[[' && prvline != ''
9646            NetrwKeepj norm! 0
9647            let nl = search('^'.indentm1.'\%('.s:treedepthstring.'\)\@!','bWe',stopline) " search backwards
9648        elseif a:dir == '[]' && nxtline != ''
9649            NetrwKeepj norm! 0
9650            let nl = search('^\%('.curindent.'\)\@!','We') " search forwards
9651            if nl != 0
9652                NetrwKeepj norm! k
9653            else
9654                NetrwKeepj norm! G
9655            endif
9656        endif
9657    endif
9658
9659endfunction
9660
9661" s:UpdateBuffersMenu: does emenu Buffers.Refresh (but due to locale, the menu item may not be called that) {{{2
9662"                      The Buffers.Refresh menu calls s:BMShow(); unfortunately, that means that that function
9663"                      can't be called except via emenu.  But due to locale, that menu line may not be called
9664"                      Buffers.Refresh; hence, s:NetrwBMShow() utilizes a "cheat" to call that function anyway.
9665function s:UpdateBuffersMenu()
9666    if has("gui") && has("menu") && has("gui_running") && &go =~# 'm' && g:netrw_menu
9667        try
9668            sil emenu Buffers.Refresh\ menu
9669        catch /^Vim\%((\a\+)\)\=:E/
9670            let v:errmsg= ""
9671            sil NetrwKeepj call s:NetrwBMShow()
9672        endtry
9673    endif
9674endfunction
9675
9676" s:UseBufWinVars: (used by NetrwBrowse() and LocalBrowseCheck() {{{2
9677"              Matching function to s:SetBufWinVars()
9678function s:UseBufWinVars()
9679    if exists("b:netrw_liststyle")       && !exists("w:netrw_liststyle")      |let w:netrw_liststyle       = b:netrw_liststyle      |endif
9680    if exists("b:netrw_bannercnt")       && !exists("w:netrw_bannercnt")      |let w:netrw_bannercnt       = b:netrw_bannercnt      |endif
9681    if exists("b:netrw_method")          && !exists("w:netrw_method")         |let w:netrw_method          = b:netrw_method         |endif
9682    if exists("b:netrw_prvdir")          && !exists("w:netrw_prvdir")         |let w:netrw_prvdir          = b:netrw_prvdir         |endif
9683    if exists("b:netrw_explore_indx")    && !exists("w:netrw_explore_indx")   |let w:netrw_explore_indx    = b:netrw_explore_indx   |endif
9684    if exists("b:netrw_explore_listlen") && !exists("w:netrw_explore_listlen")|let w:netrw_explore_listlen = b:netrw_explore_listlen|endif
9685    if exists("b:netrw_explore_mtchcnt") && !exists("w:netrw_explore_mtchcnt")|let w:netrw_explore_mtchcnt = b:netrw_explore_mtchcnt|endif
9686    if exists("b:netrw_explore_bufnr")   && !exists("w:netrw_explore_bufnr")  |let w:netrw_explore_bufnr   = b:netrw_explore_bufnr  |endif
9687    if exists("b:netrw_explore_line")    && !exists("w:netrw_explore_line")   |let w:netrw_explore_line    = b:netrw_explore_line   |endif
9688    if exists("b:netrw_explore_list")    && !exists("w:netrw_explore_list")   |let w:netrw_explore_list    = b:netrw_explore_list   |endif
9689endfunction
9690
9691" s:UserMaps: supports user-defined UserMaps {{{2
9692"               * calls a user-supplied funcref(islocal,curdir)
9693"               * interprets result
9694"             See netrw#UserMaps()
9695function s:UserMaps(islocal,funcname)
9696    if !exists("b:netrw_curdir")
9697        let b:netrw_curdir= getcwd()
9698    endif
9699    let Funcref = function(a:funcname)
9700    let result  = Funcref(a:islocal)
9701
9702    if     type(result) == 1
9703        " if result from user's funcref is a string...
9704        if result == "refresh"
9705            call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
9706        elseif result != ""
9707            exe result
9708        endif
9709
9710    elseif type(result) == 3
9711        " if result from user's funcref is a List...
9712        for action in result
9713            if action == "refresh"
9714                call s:NetrwRefresh(a:islocal,s:NetrwBrowseChgDir(a:islocal,'./',0))
9715            elseif action != ""
9716                exe action
9717            endif
9718        endfor
9719    endif
9720endfunction
9721
9722" Deprecated: {{{1
9723
9724" }}}
9725" Settings Restoration: {{{1
9726
9727let &cpo= s:keepcpo
9728unlet s:keepcpo
9729
9730" }}}
9731" vim:ts=8 sts=4 sw=4 et fdm=marker