aurum / plugin / aurum / vimdiff.vim

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
"▶1 
scriptencoding utf-8
if !exists('s:_pluginloaded')
    execute frawor#Setup('0.0', {'@/os': '0.0',
                \     '@aurum/cmdutils': '0.0',
                \         '@aurum/edit': '0.0',
                \               '@/fwc': '0.0',
                \          '@/mappings': '0.0',
                \         '@/resources': '0.0',
                \          '@/commands': '0.0',
                \         '@/functions': '0.0',
                \           '@/options': '0.0',}, 0)
    call FraworLoad('@/commands')
    call FraworLoad('@/functions')
    let s:vimdcomp=[]
    let s:vimdfunc={}
    call s:_f.command.add('AuVimDiff', s:vimdfunc, {'nargs': '*',
                \                                'complete': s:vimdcomp})
    finish
elseif s:_pluginloaded
    finish
endif
let s:_options={
            \   'usewin': {'default': 0, 'filter': 'bool'},
        \}
let s:_messages={
            \'nodfile': 'Failed to deduce which file to diff with',
            \ 'nodrev': 'Unsure what revision should be diffed with',
        \}
let s:lastfullid=0
"▶1 diffrestore
let s:diffsaveopts=['diff', 'foldcolumn', 'foldenable', 'foldmethod',
            \       'foldlevel', 'scrollbind', 'cursorbind', 'wrap']
call filter(s:diffsaveopts, 'exists("+".v:val)')
function s:F.diffrestore(buf, onenter)
    if !bufexists(a:buf) || !exists('t:auvimdiff_origbufvar') ||
                \t:auvimdiff_origbufvar.bufnr!=a:buf
        return
    endif
    let dbvar=t:auvimdiff_origbufvar
    if a:onenter
        if has_key(dbvar, 'diffbuf')
            if bufexists(dbvar.diffbuf)
                return
            else
                call s:F.diffrestore(a:buf, 0)
            endif
        elseif !has_key(dbvar, 'diffsaved')
            return
        endif
        augroup AurumDiff
            autocmd! BufEnter <buffer>
        augroup END
        if b:changedtick!=dbvar.diffsaved.changedtick
            return
        endif
        let curpos=getpos('.')
        call winrestview(dbvar.diffsaved.winview)
        normal! zR
        for line in dbvar.diffsaved.closedfolds
            try
                execute line.'foldclose'
            catch /\VVim(foldclose):E490:/
                normal! zM
                break
            endtry
        endfor
        call setpos('.', curpos)
        unlet dbvar.diffsaved
        unlet t:auvimdiff_origbufvar
        augroup AuVimDiff
            autocmd! BufEnter <buffer>
        augroup END
    else
        for option in s:diffsaveopts
            call setbufvar(a:buf, '&'.option, dbvar.diffsaved[option])
        endfor
        if has_key(dbvar, 'diffbuf')
            if exists('t:auvimdiff_diffbufvar')
                unlet t:auvimdiff_diffbufvar
            endif
            unlet dbvar.diffbuf
        endif
        if bufnr('%')==a:buf
            call s:F.diffrestore(a:buf, 1)
        endif
        if exists('t:auvimdiff_prevbuffers')
            unlet t:auvimdiff_prevbuffers
        endif
    endif
endfunction
"▶1 findwindow
function s:F.findwindow()
    let curwin=winnr()
    let curwinh=winheight(curwin)
    let curwinw=winwidth(curwin)
    let r=0
    let vertical=(stridx(&diffopt, 'vertical')!=-1)
    for wc in vertical ? ['l', 'h'] : ['j', 'k']
        execute 'wincmd' wc
        if winnr()!=curwin && ((vertical)?(winheight(0)==curwinh):
                    \                     (winwidth(0) ==curwinw))
            let r=1
            break
        endif
        execute curwin 'wincmd w'
    endfor
    return r
endfunction
"▶1 diffsplit
function s:F.diffsplit(difftarget, usewin)
    if !empty(filter(range(1, winnr('$')), 'getwinvar(v:val, "&diff")'))
        tab split
    endif
    let buf=bufnr('%')
    let t:auvimdiff_origbufvar={'bufnr': buf}
    let existed=bufexists(a:difftarget)
    let dbvar=t:auvimdiff_origbufvar
    let diffsaved={}
    let filetype=&filetype
    let dbvar.diffsaved=diffsaved
    for option in s:diffsaveopts
        let diffsaved[option]=getbufvar(buf, '&'.option)
    endfor
    let diffsaved.winview=winsaveview()
    let cursor=getpos('.')[1:]
    let diffsaved.changedtick=b:changedtick
    let closedfolds=[]
    let diffsaved.closedfolds=closedfolds
    for line in range(1, line('$'))
        if foldclosed(line)!=-1
            execute line.'foldopen'
            call insert(closedfolds, line)
        endif
    endfor
    call s:_f.mapgroup.map('AuVimDiff', buf)
    "▶2 `usewin' option support
    " Uses left/right or upper/lower window if it has similar dimensions
    if (a:usewin==-1 ? s:_f.getoption('usewin') : a:usewin) && winnr('$')>1
        diffthis
        if s:F.findwindow()
            let prevbuf=s:_r.cmdutils.prevbuf()
            execute 'silent edit' fnameescape(a:difftarget)
            diffthis
        else
            execute 'silent diffsplit' fnameescape(a:difftarget)
        endif
    else
        execute 'silent diffsplit' fnameescape(a:difftarget)
    endif
    "▲2
    if bufwinnr(buf)!=-1
        execute bufwinnr(buf).'wincmd w'
        call cursor(cursor)
        wincmd p
    endif
    if &filetype isnot# filetype
        let &filetype=filetype
    endif
    let dbuf=bufnr('%')
    let t:auvimdiff_prevbuffers={dbuf : 0}
    let t:auvimdiff_diffbufvar={'bufnr': dbuf}
    let ddbvar=t:auvimdiff_diffbufvar
    let ddbvar.srcbuf=dbuf
    let ddbvar.existed=existed
    if exists('prevbuf')
        let ddbvar.prevbuf=prevbuf
        let t:auvimdiff_prevbuffers[dbuf]=prevbuf
    endif
    let dbvar.diffbuf=dbuf
    call s:_f.mapgroup.map('AuVimDiff', dbuf)
    augroup AuVimDiff
        execute 'autocmd BufWipeOut <buffer> '.
                    \':call s:F.diffrestore('.buf.', 0)'
        execute 'autocmd BufEnter   <buffer='.buf.'> '.
                    \':call s:F.diffrestore('.buf.', 1)'
    augroup END
endfunction
let s:_augroups+=['AuVimDiff']
"▶1 exit
function s:F.exit()
    let buf=bufnr('%')
    let cmd="\<C-\>\<C-n>"
    "▶2 AuV full was used
    if exists('t:auvimdiff_full')
        let vdid=t:auvimdiff_full
        let tabnr=tabpagenr()
        for tabnr in range(1, tabnr)
            if gettabvar(tabnr, 'auvimdiff_full') is vdid
                break
            endif
        endfor
        let vdtabcond="exists('t:auvimdiff_full') && t:auvimdiff_full is ".vdid
        let cmd.=":tabnext ".tabnr."\n"
        let cmd.=":while tabpagenr('$')>1 && ".vdtabcond." | ".
                    \"tabclose! | ".
                    \"endwhile\n"
        let cmd.=":if ".vdtabcond." | ".
                    \"only! | ".
                    \"enew! | ".
                    \"endif\n"
        return cmd
    "▶2 diffsplit() was not used
    elseif !exists('t:auvimdiff_diffbufvar') ||
                \!exists('t:auvimdiff_origbufvar') ||
                \(buf!=t:auvimdiff_diffbufvar.bufnr &&
                \ buf!=t:auvimdiff_origbufvar.bufnr)
        if &diff && exists('t:auvimdiff_prevbuffers')
            for dbuf in map(filter(range(1, winnr('$')),
                      \            'getwinvar(v:val, "&diff")'),
                      \     'winbufnr(v:val)')
                if has_key(t:auvimdiff_prevbuffers, dbuf)
                    let prevbuf=remove(t:auvimdiff_prevbuffers, dbuf)
                    if prevbuf
                        let cmd.=':buffer '.prevbuf."\n"
                    endif
                    let cmd.=':bwipeout! '.dbuf."\n"
                endif
                call s:_f.mapgroup.unmap('AuVimDiff', dbuf)
            endfor
            let cmd.=":diffoff!\n"
        else
            call s:_f.mapgroup.unmap('AuVimDiff', buf)
        endif
        if exists('t:auvimdiff_prevbuffers')
            unlet t:auvimdiff_prevbuffers
        endif
        return cmd
    endif
    "▲2
    let dbvar=t:auvimdiff_origbufvar
    let ddbvar=t:auvimdiff_diffbufvar
    let isorig=(buf==dbvar.bufnr)
    call s:_f.mapgroup.unmap('AuVimDiff', buf)
    let cmd.=":diffoff!\n"
    "▶2 Original buffer
    if isorig
        if bufexists(dbvar.diffbuf)
            call s:_f.mapgroup.unmap('AuVimDiff', dbvar.diffbuf)
            if bufwinnr(dbvar.diffbuf)!=-1
                if has_key(ddbvar, 'prevbuf') && bufexists(ddbvar.prevbuf)
                    let cmd.=':'.bufwinnr(dbvar.diffbuf)."wincmd w\n".
                                \':buffer '.ddbvar.prevbuf."\n".
                                \"\<C-w>p"
                endif
                if !ddbvar.existed
                    let cmd.=':if bufexists('.dbvar.diffbuf.') | '.
                                \   'bwipeout '.dbvar.diffbuf.' | '.
                                \"endif\n"
                endif
            else
                let cmd.=':if bufexists('.dbvar.diffbuf.') | '.
                            \   'bwipeout '.dbvar.diffbuf.' | '.
                            \"endif\n"
            endif
        endif
        let cmd.=':call <SNR>'.s:_sid."_Eval(".
                    \               "'s:F.diffrestore(".buf.", 0)')\n"
    "▶2 Opened buffer
    else
        if has_key(ddbvar, 'prevbuf') && bufexists(ddbvar.prevbuf)
            let cmd.=':buffer '.ddbvar.prevbuf."\n"
        endif
        if bufexists(ddbvar.srcbuf)
            call s:_f.mapgroup.unmap('AuVimDiff', ddbvar.srcbuf)
            if bufwinnr(ddbvar.srcbuf)!=-1
                let cmd.=':'.bufwinnr(ddbvar.srcbuf)."wincmd w\n"
            endif
        endif
        if !ddbvar.existed
            let cmd.=':if bufexists('.buf.') | '.
                        \   'bwipeout '.buf.' | '.
                        \"endif\n"
        endif
        let cmd.=':call <SNR>'.s:_sid."_Eval(".
                    \           "'s:F.diffrestore(".ddbvar.srcbuf.", 0)')\n"
    endif
    "▲2
    return cmd
endfunction
"▶1 AuVimDiff mappings
call s:_f.mapgroup.add('AuVimDiff', {
            \  'Exit': {'lhs': 'X', 'rhs': s:F.exit},
        \}, {'mode': 'n', 'silent': 1, 'dontmap': 1, 'leader': ',',})
"▶1 openfile
function s:F.openfile(usewin, hasbuf, repo, revs, file)
    "▶2 Open first buffer
    let frev=a:revs[0]
    if a:hasbuf
        let fbuf=bufnr('%')
    else
        let t:auvimdiff_prevbuffers={}
        let prevbuf=s:_r.cmdutils.prevbuf()
        if frev is 0
            execute 'silent edit' fnameescape(s:_r.os.path.join(a:repo.path,
                        \                     a:file))
        else
            call s:_r.run('silent edit', 'file', a:repo, frev, a:file)
        endif
        let t:auvimdiff_prevbuffers[bufnr('%')]=prevbuf
        let fbuf=bufnr('%')
    endif
    call s:_f.mapgroup.map('AuVimDiff', fbuf)
    "▶2 Open subsequent buffers
    let i=0
    for rev in a:revs[1:]
        if rev is 0
            let f=a:file
        else
            let f=s:_r.fname('file', a:repo, rev, a:file)
        endif
        if !i && a:hasbuf && len(a:revs)==2
            let existed=bufexists(f)
            call s:F.diffsplit(f, a:usewin)
            if !existed
                setlocal bufhidden=wipe
            endif
        else
            if !i && a:usewin && winnr('$')>1
                diffthis
                if s:F.findwindow()
                    let prevbuf=s:_r.cmdutils.prevbuf()
                    execute 'silent edit' fnameescape(f)
                    diffthis
                    let t:auvimdiff_prevbuffers[bufnr('%')]=prevbuf
                else
                    execute 'silent diffsplit' fnameescape(f)
                    let t:auvimdiff_prevbuffers[bufnr('%')]=0
                endif
            else
                execute 'silent diffsplit' fnameescape(f)
                let t:auvimdiff_prevbuffers[bufnr('%')]=0
            endif
            call s:_f.mapgroup.map('AuVimDiff', bufnr('%'))
        endif
        let i+=1
    endfor
    "▲2
    return fbuf
endfunction
"▶1 opentab
function s:F.opentab(repo, revs, file, fdescr)
    "▶2 Open first revision
    let frev=a:revs[0]
    if !has_key(a:fdescr, 1) || a:fdescr[1] is# 'removed'
                \            || a:fdescr[1] is# 'deleted'
        tabnew
        let existed=0
    elseif frev is 0
        let fname=fnameescape(s:_r.os.path.join(a:repo.path, a:file))
        let existed=bufexists(fname)
        execute 'silent tabedit' fname
    else
        let existed=s:_r.run('silent tabedit', 'file', a:repo, frev, a:file)
    endif
    if !existed
        setlocal bufhidden=wipe
    endif
    let t:auvimdiff_full=s:lastfullid
    call s:_f.mapgroup.map('AuVimDiff', bufnr('%'))
    "▶2 Open subsequent revisions
    let i=1
    let vertical=(stridx(&diffopt, 'vertical')!=-1)
    for rev in a:revs[1:]
        if !has_key(a:fdescr, i) || a:fdescr[i] is# 'added'
                    \            || a:fdescr[i] is# 'unknown'
            diffthis
            if vertical
                vnew
            else
                new
            endif
            diffthis
            let existed=0
        else
            let existed=s:_r.run('silent diffsplit','file', a:repo, rev, a:file)
        endif
        if !existed
            setlocal bufhidden=wipe
        endif
        call s:_f.mapgroup.map('AuVimDiff', bufnr('%'))
        let i+=1
    endfor
    1 wincmd w
    "▲2
endfunction
"▶1 vimdfunc
" TODO exclude binary files from full diff
function s:vimdfunc.function(opts, ...)
    "▶2 repo and revisions
    let [hasbuf, repo, rev, file]=s:_r.cmdutils.getrrf(a:opts, 0, 0)
    call s:_r.cmdutils.checkrepo(repo)
    let revs=[]
    if rev isnot 0
        let rev=repo.functions.getrevhex(repo, rev)
    endif
    if get(a:opts, 'curfile', 0)
        let revs+=[0]
    endif
    if a:0
        let revs+=map(copy(a:000), 'repo.functions.getrevhex(repo, v:val)')
        if len(revs)==1
            call insert(revs, rev)
        endif
    else
        if empty(revs)
            let revs+=[rev]
        endif
        let revs+=[repo.work_hex]
    endif
    if revs[1] is# revs[0]
        let revs[1]=get(repo.functions.getcs(repo, '.').parents, 0, 0)
        if revs[1] is 0
            call s:_f.throw('nodrev')
        endif
    endif
    "▲2
    if get(a:opts, 'full', 0)
        let statuses=map(revs[1:], 'repo.functions.status(repo,v:val,revs[0])')
        let files={}
        let i=1
        "▶2 Get accepted statuses list
        let stypes=['modified']
        if get(a:opts, 'untracked', 0)
            let stypes+=['added', 'removed', 'deleted', 'unknown']
        elseif !get(a:opts, 'onlymodified', 1)
            let stypes+=['added', 'removed']
        endif
        "▶2 Get file statuses
        for status in statuses
            for [k, fs] in filter(items(status), 'index(stypes, v:val[0])!=-1')
                for f in fs
                    if !has_key(files, f)
                        let files[f]={}
                    endif
                    let files[f][i]=k
                endfor
            endfor
            let i+=1
        endfor
        "▶2 Filter out only requested files
        if has_key(a:opts, 'files')
            let filepats=map(filter(copy(a:opts.files), 'v:val isnot# ":"'),
                        \    's:_r.globtopat(repo.functions.reltorepo(repo, '.
                        \                                            'v:val))')
            let files2={}
            "▶3 Current file
            if len(filepats)!=len(a:opts.files)
                if file isnot# 0 && has_key(files, file)
                    let files2[file]=remove(files, file)
                else
                    call s:_f.throw('nodfile')
                endif
            endif
            "▲3
            for pattern in filepats
                call map(filter(keys(files), 'v:val=~#pattern'),
                            \'extend(files2, {v:val : remove(files, v:val)})')
            endfor
            let files=files2
        endif
        "▲2
        let s:lastfullid+=1
        for [f, d] in items(files)
            call s:F.opentab(repo, revs, f, d)
        endfor
    else
        if file is 0
            call s:_f.throw('nodfile')
        endif
        let usewin=get(a:opts, 'usewin', -1)
        let usewin=(usewin==-1 ? s:_f.getoption('usewin') : usewin)
        let fbuf=s:F.openfile(usewin, hasbuf, repo, revs, file)
        if bufwinnr(fbuf)!=-1
            execute bufwinnr(fbuf).'wincmd w'
        endif
    endif
endfunction
let s:vimdfunc['@FWC']=['-onlystrings '.
            \           '{  repo  '.s:_r.cmdutils.nogetrepoarg.
            \           '  ?file  type ""'.
            \           ' *?files (match /\W/)'.
            \           ' !?full'.
            \           ' !?untracked'.
            \           ' !?onlymodified'.
            \           ' !?curfile'.
            \           ' !?usewin'.
            \           '}'.
            \           '+ type ""', 'filter']
call add(s:vimdcomp,
            \substitute(substitute(s:vimdfunc['@FWC'][0],
            \'\vfile\s+type\s*\V""', 'file path',        ''),
            \'\V+ type ""',          '+ '.s:_r.comp.rev, ''))
"▶1 Post resource
call s:_f.postresource('vimdiff', {'split': s:F.diffsplit,})
"▶1
call frawor#Lockvar(s:, '_r,_pluginloaded,lastfullid')
" vim: ft=vim ts=4 sts=4 et fmr=▶,▲
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.