aboutsummaryrefslogblamecommitdiff
path: root/autoload/write_mkpath.vim
blob: 7610b87c2bfe02c99c07f38f7cf56d8966cc26fa (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

                                                                         
                                   











                                                                              
              
                  
                 
                                                                  
      
                  

       


                                          
       
 


                                 



                                                                        




                                                                             
           
" Handle a :write operation; prompt for directory creation if needed with
" 'confirm', force it with :write!
function! write_mkpath#(path) abort

  " Get all directory elements leading up to directory
  let dir = fnamemodify(a:path, ':h')

  " Directory exists, we don't need to do anything
  if isdirectory(dir)
    return
  endif

  " If :write! was issued, we'll try to create the missing path; failing that,
  " if 'confirm' is enabled, and the user responds affirmatively to the
  " prompt, that will do, too.  Otherwise, we will allow the write to fail.
  if v:cmdbang
    let mkpath = 1
  elseif &confirm
    let mkpath = confirm('Create path '.dir.'?', "&Yes\n&No") == 1
  else
    let mkpath = 0
  endif

  " Stop here if we're not creating a path
  if !mkpath
    return
  endif

  " Create the full required path
  call mkdir(dir, 'p')

  " Prod Vim into realising the buffer's directory exists now, so that a
  " subsequent change of working directory doesn't break it
  silent keepalt file %

  " Re-run the BufWritePre hooks, now that the directory exists and a useable
  " filename has been set; this will start this function again from the top,
  " but stop when it sees the directory now exists
  doautocmd BufWritePre

endfunction