1

I'm trying to improve the command from neovim help that show diff between buffer and original file.

problem is the new buffer opens without syntax highlighting because it has no file type. so I tried to save the filetype into variables and registers but I'm unable to use it in the setf command later (even manually)

Here's my latest attempt:

command! DiffOrig call setreg('f', &filetype) | vert new | set buftype=nofile | read ++edit # | 0d_
    \ | diffthis | setf @f | wincmd p | diffthis

In this attempt I manage to save the original filetype to register, but I don't manage to use it as argument for setf.

How can I make it work?

2 Answers 2

2

VimScript sets a strong difference between "commands" and "expressions" (including "variables"). Only few commands accept expressions, while others, like set or setfiletype, only accept strings. This is why one has to use execute so often. Yet in this case, simple let is more than enough. Here is a complete implementation of DiffOrig with filetype set:

command! -bar DiffOrig
    \   vnew +setlocal\ buftype=nofile
    \ | let &filetype = getbufvar(0, '&filetype')
    \ | read ++edit #
    \ | 1delete_
    \ | diffthis
    \ | wincmd p
    \ | diffthis
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the great answer! Just one thing to clear - does the backslash after the set means call the buffer [space] ?
@prophet-five See :h +cmd
2

You can do this by using let: let &ft=@f. :setf only takes literal strings.

This may also be tidier in a function, where you could use a local variable instead of a register. If you want to do that, you can define a private function by prefixing the function name with s:, and then referring to it with <SID>. So something like this:

function! s:DoDiffOrig()
  let oldft=&ft
  " ...
  let &ft=oldft
  wincmd p
  diffthis
endfunction

command! DiffOrig call <SID>DoDiffOrig()<CR>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.