robin/laufey

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

zeertzjqMerge pull request #41069 from zeertzjq/vim-b0e0b229d7c004ade

master
22.2 KiB661 linesraw
1" zip.vim: Handles browsing zipfiles
2" AUTOLOAD PORTION
3" Date:		2024 Aug 21
4" Version:	34
5" Maintainer:	This runtime file is looking for a new maintainer.
6" Former Maintainer:	Charles E Campbell
7" Last Change:
8" 2024 Jun 16 by Vim Project: handle whitespace on Windows properly (#14998)
9" 2024 Jul 23 by Vim Project: fix 'x' command
10" 2024 Jul 24 by Vim Project: use delete() function
11" 2024 Jul 30 by Vim Project: fix opening remote zipfile
12" 2024 Aug 04 by Vim Project: escape '[' in name of file to be extracted
13" 2024 Aug 05 by Vim Project: workaround for the FreeBSD's unzip
14" 2024 Aug 05 by Vim Project: clean-up and make it work with shellslash on Windows
15" 2024 Aug 18 by Vim Project: correctly handle special globbing chars
16" 2024 Aug 21 by Vim Project: simplify condition to detect MS-Windows
17" 2025 Mar 11 by Vim Project: handle filenames with leading '-' correctly
18" 2025 Jul 12 by Vim Project: drop ../ on write to prevent path traversal attacks
19" 2025 Sep 22 by Vim Project: support PowerShell Core
20" 2025 Dec 20 by Vim Project: use :lcd instead of :cd
21" 2026 Feb 08 by Vim Project: use system() instead of :!
22" 2026 Mar 08 by Vim Project: Make ZipUpdatePS() check for powershell
23" 2026 Apr 01 by Vim Project: Detect more path traversal attacks
24" 2026 Apr 05 by Vim Project: Detect more path traversal attacks
25" 2026 Apr 14 by Vim Project: Detect more path traversal attacks on Windows
26" 2026 Apr 15 by Vim Project: Detect more path traversal attacks on Windows
27" 2026 Jun 20 by Vim Project: Fix wrong escaping for the powershell calls
28" 2026 Jul 25 by Vim Project: Improved Compatibility for powershell 5 and pwsh 7
29" License:	Vim License  (see vim's :help license)
30" Copyright:	Copyright (C) 2005-2019 Charles E. Campbell {{{1
31"		Permission is hereby granted to use and distribute this code,
32"		with or without modifications, provided that this copyright
33"		notice is copied with it. Like anything else that's free,
34"		zip.vim and zipPlugin.vim are provided *as is* and comes with
35"		no warranty of any kind, either expressed or implied. By using
36"		this plugin, you agree that in no event will the copyright
37"		holder be liable for any damages resulting from the use
38"		of this software.
39
40" ---------------------------------------------------------------------
41" Load Once: {{{1
42if &cp || exists("g:loaded_zip")
43 finish
44endif
45let g:loaded_zip= "v34"
46let s:keepcpo= &cpo
47set cpo&vim
48
49let s:zipfile_escape = ' ?&;\'
50let s:ERROR          = 2
51let s:WARNING        = 1
52let s:NOTE           = 0
53
54" ---------------------------------------------------------------------
55"  Global Values: {{{1
56if !exists("g:zip_zipcmd")
57 let g:zip_zipcmd= "zip"
58endif
59if !exists("g:zip_unzipcmd")
60 let g:zip_unzipcmd= "unzip"
61endif
62if !exists("g:zip_extractcmd")
63 let g:zip_extractcmd= g:zip_unzipcmd
64endif
65if !exists("g:zip_pwsh")
66  let g:zip_pwsh=''
67endif
68
69" ---------------------------------------------------------------------
70"  required early
71" s:Mess: {{{2
72fun! s:Mess(group, msg)
73  redraw!
74  exe "echohl " . a:group
75  echomsg a:msg
76  echohl Normal
77endfun
78
79if !has('nvim-0.10') && v:version < 901
80 " required for defer
81 call s:Mess('WarningMsg', "***warning*** this version of zip needs vim 9.1 or later")
82 finish
83endif
84
85" ---------------------------------------------------------------------
86"  Compatibility checks
87" PowerShell: {{{2
88" Existence of powershell always means a Windows OS. By default the
89" `zip`/`unzip` is not installed on Windows, but the runtime of
90" powershell support relative functionalities about zip compression
91" and extraction.
92" In the following implementations we'll use some powershell scripts
93" to manipulate zip files. All these scripts should available to both
94" Windows PowerShell 5 and pwsh 7+.
95
96let s:ps = ''
97" order: `g:zip_pwsh` > `&shell`, with executable check
98if &shell =~# 'powershell' || g:zip_pwsh =~# 'powershell'
99  if executable('powershell')
100    let s:ps = 'powershell'
101  endif
102endif
103if (empty(g:zip_pwsh) && &shell =~# 'pwsh') || g:zip_pwsh =~# 'pwsh'
104  if executable('pwsh')
105    let s:ps = 'pwsh'
106  endif
107endif
108
109fun! s:isPS()
110  return !empty(s:ps)
111endfun
112
113" ---------------------------------------------------------------------
114" sanity checks
115" s:SafeExecutable: {{{2
116fun! s:SafeExecutable(exe)
117  " fails when exe is a full path with spaces
118  let exe = substitute(a:exe, '\s\+.*$', '', '')
119  if !executable(exe) && !s:isPS()
120    return v:false
121  endif
122  if !dist#vim#IsSafeExecutable('zip', exe) && !s:isPS()
123    call s:Mess('Error', "Warning: NOT executing " .. a:exe .. " from current directory!") 
124    return v:false
125  endif
126  return v:true
127endfun
128" ----------------
129"  PowerShell: {{{1
130" ----------------
131
132function! s:TryExecGnuFallBackToPs(executable, gnu_func_call, ...)
133  " Check that a gnu executable is available, run the gnu_func_call if so. If
134  " the gnu executable is not available or if gnu_func_call fails, try
135  " ps_func_call if `s:isPS()`. If all attempts fail, print errors.
136  " a:executable - (string) name of the executable program
137  " a:gnu_func_call - (string) a gnu function call to execute
138  " a:1 - (optional string) a PowerShell function call to execute.
139  let failures = []
140  if executable(substitute(a:executable,'\s\+.*$','',''))
141    try
142      exe a:gnu_func_call
143      return
144    catch
145      call add(failures, 'Failed to execute '.a:gnu_func_call)
146    endtry
147  else
148    call add(failures, a:executable.' not available on your system')
149  endif
150  if s:isPS() && a:0 == 1
151    try
152      exe a:1
153      return
154    catch
155      call add(failures, 'Fallback to PowerShell attempted but failed: '.a:1)
156    endtry
157  endif
158  for msg in failures
159    call s:Mess('Error', msg)
160  endfor
161endfunction
162
163
164function! s:ZipBrowsePS(zipfile)
165  " Browse the contents of a zip file using PowerShell's
166  " Equivalent `unzip -Z1 -- zipfile`
167  let cmds = [
168        \ 'Add-Type -AssemblyName System.IO.Compression.FileSystem;',
169        \ '$zip = [System.IO.Compression.ZipFile]::OpenRead(' . s:PSEscape(a:zipfile) . ');',
170        \ '$zip.Entries | ForEach-Object { $_.FullName };',
171        \ '$zip.Dispose()'
172        \ ]
173  return s:ps . ' -NoProfile -Command ' . s:Escape(join(cmds, ' '), 1)
174endfunction
175
176function! s:ZipReadPS(zipfile, fname, tempfile)
177  " Read a filename within a zipped file to a temporary file.
178  " Equivalent to `unzip -p -- zipfile fname > tempfile`
179  if s:isPS()
180    call s:Mess('WarningMsg', "***warning*** PowerShell can display, but cannot update, files in archive subfolders")
181  endif
182  let cmds = [
183        \ 'Add-Type -AssemblyName System.IO.Compression.FileSystem;',
184        \ '$zip = [System.IO.Compression.ZipFile]::OpenRead(' . s:PSEscape(a:zipfile) . ');',
185        \ '$fileEntry = $zip.Entries | Where-Object { $_.FullName -eq ' . s:PSEscape(a:fname) . ' };',
186        \ '$stream = $fileEntry.Open();',
187        \ '$fileStream = [System.IO.File]::Create(' . s:PSEscape(a:tempfile) . ');',
188        \ '$stream.CopyTo($fileStream);',
189        \ '$fileStream.Close();',
190        \ '$stream.Close();',
191        \ '$zip.Dispose()'
192        \ ]
193  return s:ps . ' -NoProfile -Command ' . s:Escape(join(cmds, ' '))
194endfunction
195
196function! s:ZipUpdatePS(zipfile, fname)
197  " Update a filename within a zipped file
198  " Equivalent to `zip -u zipfile fname`
199  if s:isPS() && a:fname =~ '/'
200    call s:Mess('Error', "***error*** PowerShell cannot update files in archive subfolders")
201    return ':'
202  endif
203  return 'Compress-Archive -Path ' . s:PSEscape(a:fname) . ' -Update -DestinationPath ' . s:PSEscape(a:zipfile)
204endfunction
205
206function! s:ZipExtractFilePS(zipfile, fname)
207  " Extract a single file from an archive
208  " Equivalent to `unzip -o zipfile fname`
209  if a:fname =~ '/'
210    call s:Mess('Error', "***error*** PowerShell cannot extract files in archive subfolders")
211    return ':'
212  endif
213  let cmds = [
214        \ 'Add-Type -AssemblyName System.IO.Compression.FileSystem;',
215        \ '$zip = [System.IO.Compression.ZipFile]::OpenRead(' . s:PSEscape(a:zipfile) . ');',
216        \ '$fileEntry = $zip.Entries | Where-Object { $_.FullName -eq ' . s:PSEscape(a:fname) . ' };',
217        \ '$stream = $fileEntry.Open();',
218        \ '$fileStream = [System.IO.File]::Create(' . s:PSEscape(a:fname) . ');',
219        \ '$stream.CopyTo($fileStream);',
220        \ '$fileStream.Close();',
221        \ '$stream.Close();',
222        \ '$zip.Dispose()'
223        \ ]
224  return s:ps . ' -NoProfile -Command ' . s:Escape(join(cmds, ' '))
225endfunction
226
227function! s:ZipDeleteFilePS(zipfile, fname)
228  " Delete a single file from an archive
229  " Equivalent to `zip -d zipfile fname`
230  let cmds = [
231        \ 'Add-Type -AssemblyName System.IO.Compression.FileSystem;',
232        \ '$zip = [System.IO.Compression.ZipFile]::Open(' . s:PSEscape(a:zipfile) . ', ''Update'');',
233        \ '$entry = $zip.Entries | Where-Object { $_.Name -eq ' . s:PSEscape(a:fname) . ' };',
234        \ 'if ($entry) { $entry.Delete(); $zip.Dispose() }',
235        \ 'else { $zip.Dispose() }'
236        \ ]
237  return s:ps . ' -NoProfile -Command ' . s:Escape(join(cmds, ' '))
238endfunction
239
240" ----------------
241"  Functions: {{{1
242" ----------------
243
244" ---------------------------------------------------------------------
245" zip#Browse: {{{2
246fun! zip#Browse(zipfile)
247  " sanity check: ensure that the zipfile has "PK" as its first two letters
248  "               (zip files have a leading PK as a "magic cookie")
249  if filereadable(a:zipfile) && readblob(a:zipfile, 0, 2) != 0z50.4B
250   exe "noswapfile noautocmd e " .. fnameescape(a:zipfile)
251   return
252  endif
253
254  let dict = s:SetSaneOpts()
255  defer s:RestoreOpts(dict)
256
257  " sanity checks
258  if !s:SafeExecutable(g:zip_unzipcmd)
259   call s:Mess('Error', "***error*** (zip#Browse) sorry, your system doesn't appear to have the ".g:zip_unzipcmd." program")
260   return
261  endif
262  if !filereadable(a:zipfile)
263   if a:zipfile !~# '^\a\+://'
264    " if it's an url, don't complain, let url-handlers such as vim do its thing
265    call s:Mess('Error', "***error*** (zip#Browse) File not readable <".a:zipfile.">")
266   endif
267   return
268  endif
269  if &ma != 1
270   set ma
271  endif
272  let b:zipfile= a:zipfile
273
274  setlocal noswapfile
275  setlocal buftype=nofile
276  setlocal bufhidden=hide
277  setlocal nobuflisted
278  setlocal nowrap
279
280  " Oct 12, 2021: need to re-use Bram's syntax/tar.vim.
281  " Setting the filetype to zip doesn't do anything (currently),
282  " but it is perhaps less confusing to curious perusers who do
283  " a :echo &ft
284  setf zip
285  run! syntax/tar.vim
286
287  " give header
288  call append(0, ['" zip.vim version '.g:loaded_zip,
289 \                '" Browsing zipfile '.a:zipfile,
290 \                '" Select a file with cursor and press ENTER'])
291  keepj $
292
293  let gnu_cmd = "keepj sil r! " . g:zip_unzipcmd . " -Z1 -- " . s:Escape(a:zipfile, 1)
294  let ps_cmd = 'keepj sil r! ' . s:ZipBrowsePS(a:zipfile)
295  call s:TryExecGnuFallBackToPs(g:zip_unzipcmd, gnu_cmd, ps_cmd)
296
297  if v:shell_error != 0
298   call s:Mess('WarningMsg', "***warning*** (zip#Browse) ".fnameescape(a:zipfile)." is not a zip file")
299   keepj sil! %d
300   let eikeep= &ei
301   set ei=BufReadCmd,FileReadCmd
302   exe "keepj r ".fnameescape(a:zipfile)
303   let &ei= eikeep
304   keepj 1d
305   return
306  endif
307
308  " Maps associated with zip plugin
309  setlocal noma nomod ro
310  noremap <silent> <buffer>	<cr>		:call <SID>ZipBrowseSelect()<cr>
311  noremap <silent> <buffer>	x		:call zip#Extract()<cr>
312  if &mouse != ""
313   noremap <silent> <buffer>	<leftmouse>	<leftmouse>:call <SID>ZipBrowseSelect()<cr>
314  endif
315
316endfun
317
318" ---------------------------------------------------------------------
319" ZipBrowseSelect: {{{2
320fun! s:ZipBrowseSelect()
321  let dict = s:SetSaneOpts()
322  defer s:RestoreOpts(dict)
323  let fname= getline(".")
324  if !exists("b:zipfile")
325   return
326  endif
327
328  " sanity check
329  if fname =~ '^"'
330   return
331  endif
332  if fname =~ '/$'
333   call s:Mess('Error', "***error*** (zip#Browse) Please specify a file, not a directory")
334   return
335  endif
336
337  " get zipfile to the new-window
338  let zipfile = b:zipfile
339  let curfile = expand("%")
340
341  noswapfile new
342  if !exists("g:zip_nomax") || g:zip_nomax == 0
343   wincmd _
344  endif
345  let s:zipfile_{winnr()}= curfile
346  exe "noswapfile e ".fnameescape("zipfile://".zipfile.'::'.fname)
347  filetype detect
348
349endfun
350
351" ---------------------------------------------------------------------
352" zip#Read: {{{2
353fun! zip#Read(fname,mode)
354  let dict = s:SetSaneOpts()
355  defer s:RestoreOpts(dict)
356
357  if has("unix")
358   let zipfile = substitute(a:fname,'zipfile://\(.\{-}\)::[^\\].*$','\1','')
359   let fname   = substitute(a:fname,'zipfile://.\{-}::\([^\\].*\)$','\1','')
360  else
361   let zipfile = substitute(a:fname,'^.\{-}zipfile://\(.\{-}\)::[^\\].*$','\1','')
362   let fname   = substitute(a:fname,'^.\{-}zipfile://.\{-}::\([^\\].*\)$','\1','')
363  endif
364  let fname    = fname->substitute('[', '[[]', 'g')->escape('?*\\')
365  " sanity check
366  if !s:SafeExecutable(g:zip_unzipcmd)
367   call s:Mess('Error', "***error*** (zip#Read) sorry, your system doesn't appear to have the ".g:zip_unzipcmd." program")
368   return
369  endif
370
371  " the following code does much the same thing as
372  "   exe "keepj sil! r! ".g:zip_unzipcmd." -p -- ".s:Escape(zipfile,1)." ".s:Escape(fname,1)
373  " but allows zipfile://... entries in quickfix lists
374  let temp = tempname()
375  let fn   = expand('%:p')
376
377  let gnu_cmd = g:zip_unzipcmd . ' -p -- ' . s:Escape(zipfile) . ' ' . s:Escape(fname) . ' > ' . s:Escape(temp)
378  let gnu_cmd = 'call system(' . string(gnu_cmd) . ')'
379  let ps_cmd = 'call system(' . string(s:ZipReadPS(zipfile, fname, temp)) . ')'
380  call s:TryExecGnuFallBackToPs(g:zip_unzipcmd, gnu_cmd, ps_cmd)
381
382  sil exe 'keepalt file '.temp
383  sil keepj e!
384  sil exe 'keepalt file '.fnameescape(fn)
385  call delete(temp)
386
387  filetype detect
388
389  " cleanup
390  set nomod
391
392endfun
393
394" ---------------------------------------------------------------------
395" zip#Write: {{{2
396fun! zip#Write(fname)
397  let dict = s:SetSaneOpts()
398  let need_rename = 0
399  defer s:RestoreOpts(dict)
400
401  " sanity checks
402  if !s:SafeExecutable(g:zip_zipcmd)
403    call s:Mess('Error', "***error*** (zip#Write) sorry, your system doesn't appear to have the ".g:zip_zipcmd." program")
404    return
405  endif
406
407  if simplify(a:fname) =~ '\.\.[/\\]'
408    call s:Mess('Error', "***error*** (zip#Write) Path Traversal Attack detected, not writing!")
409    return
410  endif
411
412  let curdir= getcwd()
413  let tmpdir= tempname()
414  if tmpdir =~ '\.'
415    let tmpdir= substitute(tmpdir,'\.[^.]*$','','e')
416  endif
417  call mkdir(tmpdir,"p")
418
419  " attempt to change to the indicated directory
420  if s:ChgDir(tmpdir,s:ERROR,"(zip#Write) cannot lcd to temporary directory")
421    return
422  endif
423
424  " place temporary files under .../_ZIPVIM_/
425  if isdirectory("_ZIPVIM_")
426    call delete("_ZIPVIM_", "rf")
427  endif
428  call mkdir("_ZIPVIM_")
429  lcd _ZIPVIM_
430
431  if has("unix")
432    let zipfile = substitute(a:fname,'zipfile://\(.\{-}\)::[^\\].*$','\1','')
433    let fname   = substitute(a:fname,'zipfile://.\{-}::\([^\\].*\)$','\1','')
434    " fname should not start with a leading slash to avoid writing anywhere into the system
435    if fname =~ '^/'
436      call s:Mess('Error', "***error*** (zip#Write) Path Traversal Attack detected, not writing!")
437      call s:ChgDir(curdir,s:WARNING,"(zip#Write) unable to return to ".curdir."!")
438      return
439    endif
440  else
441    let zipfile = substitute(a:fname,'^.\{-}zipfile://\(.\{-}\)::[^\\].*$','\1','')
442    let fname   = substitute(a:fname,'^.\{-}zipfile://.\{-}::\([^\\].*\)$','\1','')
443    " fname should not start with drive letter, UNC path, or leading slash
444    if fname =~ '^\%(\a:[\\/]\|[\\/]\)'
445      call s:Mess('Error', "***error*** (zip#Write) Path Traversal Attack detected, not writing!")
446      call s:ChgDir(curdir,s:WARNING,"(zip#Write) unable to return to ".curdir."!")
447      return
448    endif
449  endif
450  if fname =~ '^[.]\{1,2}/'
451    let gnu_cmd = g:zip_zipcmd . ' -d ' . s:Escape(fnamemodify(zipfile,":p")) . ' ' . s:Escape(fname)
452    let gnu_cmd = 'call system(' . string(gnu_cmd) . ')'
453    let ps_cmd = $"call system({string(s:ZipDeleteFilePS(zipfile, fname))})"
454    call s:TryExecGnuFallBackToPs(g:zip_zipcmd, gnu_cmd, ps_cmd)
455    let fname = fname->substitute('^\([.]\{1,2}/\)\+', '', 'g')
456    let need_rename = 1
457  endif
458
459  if fname =~ '/'
460    let dirpath = substitute(fname,'/[^/]\+$','','e')
461    if has("win32unix") && executable("cygpath")
462    let dirpath = substitute(system("cygpath ".s:Escape(dirpath)),'\n','','e')
463    endif
464    call mkdir(dirpath,"p")
465  endif
466  if zipfile !~ '/'
467    let zipfile= curdir.'/'.zipfile
468  endif
469
470  " don't overwrite files forcefully
471  exe "w ".fnameescape(fname)
472  if has("win32unix") && executable("cygpath")
473    let zipfile = substitute(system("cygpath ".s:Escape(zipfile)),'\n','','e')
474  endif
475
476  if (has("win32") || has("win95") || has("win64") || has("win16")) && &shell !~? 'sh$'
477    let fname = substitute(fname, '[', '[[]', 'g')
478  endif
479
480  let gnu_cmd = g:zip_zipcmd . ' -u '. s:Escape(fnamemodify(zipfile,":p")) . ' ' . s:Escape(fname)
481  let gnu_cmd = 'call system(''' . substitute(gnu_cmd, "'", "''", 'g') . ''')'
482  let zip = fnamemodify(zipfile, ':p')
483  let ps_cmd = s:ZipUpdatePS(zip, fname)
484  let ps_cmd = 'call system(''' . substitute(ps_cmd, "'", "''", 'g') . ''')'
485  call s:TryExecGnuFallBackToPs(g:zip_zipcmd, gnu_cmd, ps_cmd)
486  if s:isPS()
487    " Vim flashes 'creation in progress ...' from what I believe is the
488    " ProgressAction stream of PowerShell. Unfortunately, this cannot be
489    " suppressed (as of 250824) due to an open PowerShell issue.
490    " https://github.com/PowerShell/PowerShell/issues/21074
491    " This necessitates a redraw of the buffer.
492    redraw!
493  endif
494
495  if v:shell_error != 0
496    call s:Mess('Error', "***error*** (zip#Write) sorry, unable to update ".zipfile." with ".fname)
497
498  elseif s:zipfile_{winnr()} =~ '^\a\+://'
499    " support writing zipfiles across a network
500    let netzipfile= s:zipfile_{winnr()}
501    1split|enew
502    let binkeep= &binary
503    let eikeep = &ei
504    set binary ei=all
505    exe "noswapfile e! ".fnameescape(zipfile)
506    call netrw#NetWrite(netzipfile)
507    let &ei     = eikeep
508    let &binary = binkeep
509    q!
510    unlet s:zipfile_{winnr()}
511  elseif need_rename
512    exe $"sil keepalt file {fnameescape($"zipfile://{zipfile}::{fname}")}"
513    call s:Mess('Warning', "***error*** (zip#Browse) Path Traversal Attack detected, dropping relative path")
514  endif
515
516  " cleanup and restore current directory
517  lcd ..
518  call delete("_ZIPVIM_", "rf")
519  call s:ChgDir(curdir,s:WARNING,"(zip#Write) unable to return to ".curdir."!")
520  call delete(tmpdir, "rf")
521  setlocal nomod
522endfun
523
524" ---------------------------------------------------------------------
525" zip#Extract: extract a file from a zip archive {{{2
526fun! zip#Extract()
527
528  let dict = s:SetSaneOpts()
529  defer s:RestoreOpts(dict)
530
531  " sanity checks
532  if !s:SafeExecutable(g:zip_extractcmd)
533    call s:Mess('Error', "***error*** (zip#Extract) sorry, your system doesn't appear to have the ".g:zip_extractcmd." program")
534    return
535  endif
536
537  let fname= getline(".")
538
539  " sanity check
540  if fname =~ '^"'
541    return
542  endif
543  if fname =~ '/$'
544    call s:Mess('Error', "***error*** (zip#Extract) Please specify a file, not a directory")
545    return
546  elseif fname =~ '^[.]\?[.]/' || simplify(fname) =~ '\.\.[/\\]'
547    call s:Mess('Error', "***error*** (zip#Browse) Path Traversal Attack detected, not extracting!")
548    return
549  endif
550  " block absolute paths
551  if has("unix")
552    if fname =~ '^/'
553      call s:Mess('Error', "***error*** (zip#Extract) Path Traversal Attack detected, not extracting!")
554      return
555    endif
556  else
557    if fname =~ '^\%(\a:[\\/]\|[\\/]\)'
558      call s:Mess('Error', "***error*** (zip#Extract) Path Traversal Attack detected, not extracting!")
559      return
560    endif
561  endif
562  if filereadable(fname)
563    call s:Mess('Error', "***error*** (zip#Extract) <" .. fname .."> already exists in directory, not overwriting!")
564    return
565  endif
566  let target = fname->substitute('\[', '[[]', 'g')
567  " unzip 6.0 does not support -- to denote end-of-arguments
568  " unzip 6.1 (2010) apparently supports, it, but hasn't been released
569  " so the workaround is to use glob '[-]' so that it won't be considered an argument
570  " else, it would be possible to use 'unzip -o <file.zip> '-d/tmp' to extract the whole archive
571  let target = target->substitute('^-', '[&]', '')
572  if &shell =~ 'cmd' && has("win32")
573    let target = target
574		\ ->substitute('[?*]', '[&]', 'g')
575		\ ->substitute('[\\]', '?', 'g')
576		\ ->shellescape()
577    " there cannot be a file name with '\' in its name, unzip replaces it by _
578    let fname = fname->substitute('[\\?*]', '_', 'g')
579  else
580    let target = target->escape('*?\\')->shellescape()
581  endif
582
583  " extract the file mentioned under the cursor
584  let gnu_cmd = g:zip_extractcmd . ' -o '. shellescape(b:zipfile) . ' ' . target
585  let gnu_cmd = 'call system(' . string(gnu_cmd) . ')'
586  let ps_cmd = 'call system(' . string(s:ZipExtractFilePS(b:zipfile, fname)) . ')'
587  call s:TryExecGnuFallBackToPs(g:zip_extractcmd, gnu_cmd, ps_cmd)
588
589  if v:shell_error != 0
590    call s:Mess('Error', "***error*** ".g:zip_extractcmd." ".b:zipfile." ".fname.": failed!")
591  elseif !filereadable(fname) && !s:isPS()
592    call s:Mess('Error', "***error*** attempted to extract ".fname." but it doesn't appear to be present!")
593  else
594    echomsg "***note*** successfully extracted ".fname
595  endif
596endfun
597
598" ---------------------------------------------------------------------
599" s:Escape: {{{2
600fun! s:Escape(fname, isfilt = 0)
601  if a:isfilt
602   let qnameq = shellescape(a:fname, 1)
603  else
604   let qnameq = shellescape(a:fname)
605  endif
606  return qnameq
607endfun
608
609" s:PSEscape: Escape a string for Powershell, shellescape() does not work here {{{2
610fun! s:PSEscape(str)
611  return "'" .. substitute(a:str, "'", "''", 'g') .. "'"
612endfun
613
614" ---------------------------------------------------------------------
615" s:ChgDir: {{{2
616fun! s:ChgDir(newdir,errlvl,errmsg)
617  try
618   exe "lcd ".fnameescape(a:newdir)
619  catch /^Vim\%((\a\+)\)\=:E344/
620   redraw!
621   if a:errlvl == s:NOTE
622    echomsg "***note*** ".a:errmsg
623   elseif a:errlvl == s:WARNING
624    call s:Mess("WarningMsg", "***warning*** ".a:errmsg)
625   elseif a:errlvl == s:ERROR
626    call s:Mess("Error", "***error*** ".a:errmsg)
627   endif
628   return 1
629  endtry
630
631  return 0
632endfun
633
634" ---------------------------------------------------------------------
635" s:SetSaneOpts: {{{2
636fun! s:SetSaneOpts()
637  let dict = {}
638  let dict.report = &report
639  let dict.shellslash = &shellslash
640
641  let &report = 10
642  if exists('+shellslash')
643    let &shellslash = 0
644  endif
645
646  return dict
647endfun
648
649" ---------------------------------------------------------------------
650" s:RestoreOpts: {{{2
651fun! s:RestoreOpts(dict)
652  for [key, val] in items(a:dict)
653    exe $"let &{key} = {val}"
654  endfor
655endfun
656
657" ------------------------------------------------------------------------
658" Modelines And Restoration: {{{1
659let &cpo= s:keepcpo
660unlet s:keepcpo
661" vim:ts=8 fdm=marker