I am attempting to write a vim function in my vimrc. It should modify the currently edited file (eg abc.txt), then write the modified contents to another file (eg abc_x.txt), and finally return to continue editing abc.txt.
So far I've attempted the following:
function! Write_new_file() " Hold the original and new file names in variables. let l:fn_no_ext = expand('%:p:r') let l:fn_ext = expand('%:e') let l:original_name = l:fn_no_ext.'.'.l:fn_ext let l:new_name = l:fn_no_ext.'_x.'.l:fn_ext " Save the current state of the original file. write " Rename the currently edited contents to the new file name. exe 'file '.l:new_name " Make all the modifications to the now renamed edited contents. call Many_Modifications() " Save the modified contents to the new file. write! " Use the original file name to return to editing the original file. exe 'edit! '.l:original_name endfunction The problem:
If this function is defined in a script other than my vimrc, it works as expected. However, if the function is defined in my vimrc, the edit command at the very end causes error E127. The output looks like this:
Error detected while processing /home/edward/.vim/vimrc: line 111: E127: Cannot redefine function Write_new_file: It is in use Press ENTER or type command to continue Based on the fact that, when I comment out the edit in the function, the error disappears (of course, then I don't get the behavior I want), I am guessing that the edit is the source of the problem.
Based on the fact that the error message says that the error was detected while processing my vimrc, I am guessing that something about executing the edit statement makes vim re-source my vimrc, and since my vimrc contains the definition of Write_new_file(), the error is triggered.
Of course, these are just guesses.
Is there a way to use the edit command in a function defined in my vimrc that does not throw an error, or alternatively is there a different way to achieve my goal that does not involve manually sourcing a script once during each session?
For anyone who is wondering what my use case is: I am writing text that has to contain many instances of different long sequences of characters. To ease the typing, for each such long sequence, I've come up with a unique shorter one that I type instead. Obviously I have to replace my sequences with the expected ones, before the files are usable. The process of creating any such file is iterative, ie: write, check validity, keep writing. Therefore I need a script that writes a usable file and returns me to where I left off in my text.
I suppose I could accomplish my goal with sed, however, I've already invested considerable effort writing the replacement scripts in vimscript, and I'd hate to have to re-implement. Also, I have a secondary goal to become more proficient in the use of vim.