vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

zip.vim (21852B)


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