Search code examples
vimfile-format

Vim execute :e ++ff=dos from vimrc


Occasionally I have to work with mixed Unix/DOS files in Vim. That file will show ^M on the end on most of the lines. I can't convert the whole file to just Unix format.

Fix for that is :e ++ff=dos

I have tried to incorporate that in my vimrc at least as a shorcut (if not autocmd) but without success.

ga for ^M will show:

<^M>  13,  Hex 0d,  Octal 15

This won't work from vimrc:

function! Fix_dos()
    execute "normal :e ++ff=dos<cr>"
endfunction

I have tried something with conceal feature, but that won't conceal all ^M chars.

:set conceallevel=2
:syntax match Todo /\r/ conceal

Also, is there a way to detect if file will show ^M chars?

Thanks for your help.


Solution

  • If you do :e +ff=dos, you convert the file to DOS format; i.e. after writing, all line endings will be converted to CR-LF. You've mentioned that you cannot convert to the whole file to Unix format, but if converting to DOS is okay, then this is the solution.

    For your function, you don't need to go through :normal, as the :e command is an Ex command, and those can be directly used in a function. You only need :normal for normal-mode commands like dd. Therefore, you can rewrite:

    function! Fix_dos()
        " This would be the correct syntax, but no need for :normal:
        "execute "normal :e ++ff=dos\<cr>"
        " Also, no need for execute:
        "execute "e ++ff=dos"
        edit ++ff=dos
    endfunction
    

    In fact, I would define:

    :command! FixDos edit ++ff=dos
    

    If you cannot covert the entire file, you'll have to live with the ^M; best you can do is trying to hide them, as you've tried with concealing. This variant might catch more instances of ^M by also appying inside other syntax groups:

    :syntax match Todo /\r/ conceal containedin=ALL