How do I make a file writable from inside Vim - vim

I am frequently opening files that are readonly, I would like to know if there is a way to make them writable from inside Vim. I do not mean :w!, I need the file to be writeable after I close Vim.

If you are on a unix based machine you can always just use the unix command.
:!chmod 777 %
http://ss64.com/bash/chmod.html
Otherwise on windows, you should look into the calcs command:
http://www.delawarepchelp.com/system/dos/calcs.htm

The issue comes from the fact that after changing the file attributes Vim will detect it and will try to reload the file and you will loose what you typed.
The best seems to create a function that redefines the autocmd FileChangedShell to do nothing when the attribute change is detected.
See this example of setting file attributes without reloading a buffer where an example is given for making all files executables.
This should do the trick for you

I found this solution elsewhere:
:set readonly!
:set modifiable
my situation was that vim was opening my file, which I chmod 777 from the commandline before opening, as readonly. Not sure if this helps you at all...
edit: forgot the second command. only the combination of the two worked.

you can use :! to execute shell commands. So you could change the user using :!chown myusername filename or change the access right using for example :!chmod o+w filename

Additionally, if the file was writeable only by another user (and you are not owner, so can't chmod it) you might map this command:
:command SuWrite %!sudo tee %
Of course, sudo -u username for other users

!sudo chmod 777 %
When it asks if you want to use the buffer, type "O" for ok.

You can use the SudoWrite command from the vim-eunuch plugin, which enables you to write to a file with sudo even if you forgot to open vim with sudo. It's a great way to eliminate that annoying behavior when you forget.

Related

How can I save a write protected file in vi?

I'm trying to save my modified "menu.lst" file in vi. When I save the file, vi says: 'menu.lst' is read only.
How can I fix this?
The file you are trying to save is read-only, meaning you cannot modify its contents. It needs to be marked as writable. The process varies depending on your OS. Here are some helpful resources on how to change permissions of files:
For Windows 10: Nibbleguru: How to remove read-only attribute in Windows 10
For Linux (using chmod): TLDP: File Permissions
For macOS: Chron: How to Change File Permission From Read-Only to Read-Write on a Mac
EDIT:
As filbranden pointed out, for Grub's files, you should be opening vi using the sudo command. Grub's files are meant to be modified by root only. You should be opening your files using sudo vi menu.lst instead.
I have this on my vimrc
cnoremap w!! execute 'silent! write !sudo tee % >/dev/null' <bar> edit!
command! SaveAsRoot w !sudo tee %
cnoreabbrev sudow SaveAsRoot
For instant use, just copy to the clipboard and run:
:#+
:SaveAsRoot
The :#+ loads your clipboard into vim memory which allows you to run the given commands while not saved on your vimrc.
People suggest using sudo vi(m) on unix, but this could have unwanted consequences: all commands executed in this window are done by root and so you could accidentally do unwanted things like deleting file or just creating files owned by root.
Instead you should think about using sudoedit instead. It will copy the file to /tmp and open it in $EDITOR (if you are using vim, you should set it in your ~/.profile / ~/.bash_profile).
But beware: Something I stumbled across: the original file is only replaced when you close vim - no matter how often you save! (This is, because you are editing the file in /tmp and not the original).
It is not that I don't use sudo vim but if I do, I am extra cautious about what I do ;) I do it for example if I know that I will need to edit multiple files as root, or that I want to execute other commands from within vim as root (e.g. git)
And something even more important to me: sudo vim is using roots vimrc instead of mine, but with sudoedit I have my own config...

How to edit _vimrc file?

I am having trouble saving my settings on vim. I know that in order to do that I need to open the vimrc file but when I do that it says that the file is readonly and won't let me edit it, preventing me from saving my settings.
It says that in order to force save it or override it, I need to add the ! mark after :w in the command section, which I do, but it still does not work.
I can't find any other solution to this problem.
Note: I am using Windows 8.1.
On Windows, you may need to run your editor as administrator to write to your system's _vimrc file.
You may also create a _vimrc in your home directory (e.g. C:\Users\Piet\_vimrc, see the output of :echo $HOME) without administrator access.
You can solve it this way:
Instead of :w, type :w !sudo tee %. I guess it should work.
(my answer is based on this tutotial where the whole problem is well-described)
You may be editing the one global vimrc in /etc/vimrc to which you don't have access.
Make sure you're editing ~/.vimrc and check that you have read and write priviledges to the file (ls -l ~/.vimrc). Since the file is in your home folder you should have those privilages but it won't hurt to verify.

vimrc settings for user dont work for root

I have modified the .vimrc file in my user. The settings dont work when i switch to superuser.
When i check the contents of the file (using vim editor) i can see the mapped keystrokes of newlines
(with all the text extending on the rightside beyond screen on same line), but when i check the contents of .vimrc as root, i see all the text in the same window screen one below the other (this may be a very stupid difference, but that is the only difference i noticed. all the data in the file is same).
i am unable to understand what is wrong and how can i correct it.
root is a user too, when you start vim with root, vim load the root's Home/.vimrc usually it is /root/.vimrc
You can cp or ln -s your user's vimrc to /root if this is a personal desktop machine.
I hope I understood your problem.
You did not state a precise question, so for the sake of completeness :
If what you want is being able to modify files as root using your user's vim and .vimrc, you can do
sudo -e /path/to/your/file
sudo will use the editor configured in $EDITOR as the current user, to edit a temporary copy of the file that will get copied over when you write the file.
The caveat is that you will not be able to have any edition history between sessions. For example, if you modify /etc/group once, save the changes and quit, and then reopen the file again, you will not be able to undo the modification you did at first.
For Neovim users, you can do what comes next:
If your root user settings for neovim are important, make a
backup for those dotfiles.
Create a symbolic link from your default user to /root/.config directory.
sudo mv /root/.config/nvim /root/.config/nvim.bkp; sudo ln -s $HOME/.config/nvim /root/.config/
Be aware that some plugins may need some files that are not under
.config/nvim directory.
On Debian GNU/Linux there is also a shared configuration file in /usr/share/vim/vimrc. (Actually this is a soft link to /etc/vim/vimrc.) See the bottom of the man page on vim.

Can I gain root permission without leaving vim?

Sometimes when I edit a file which require root permission (e.g. files under /etc), but I forget run vim as sudo.
After edit finished, and type :wq to save and leave, I find I can't, even using !wq, because the file is readonly.
If I leave and re-edit the file, all my work will lost, but if not, I cannot save my edit. So, how can I gain root permission to write without leaving vim?
To force a save use the following command
:w !sudo tee %
It will prompt you for your password.
The mentioned trick with tee is nice; if you need this often I'd recommend the SudoEdit plugin, which offers a :SudoWrite command (and even a sudo: protocol handler).

Save file as root after editing as non-root

Ok so this happens to me all the time. There has to be a better solution. Let's say you do vim /etc/somefile.conf and then you do i but realize you are not sudo and you can't write. So then I lose my changes by doing :q then sudo !! and make my changes again. Is there a better way to do this?
Try
:w !sudo tee "%"
The w ! takes the entire file and pipes it into a shell command. The shell command is sudo tee which runs tee as superuser. % is replaced with the current file name. Quotes needed for files that have either spaces or any other special characters in their names.
Depending on the extent of your changes, it might be faster to save (:w) your file with a different name, and then use sudo and cat to overwrite the content of the original file:
sudo sh -c 'cat changed > file'
Note that both cp and mv will replace the original file and its attributes (ownership, permissions, ACLs) will be lost. Do not use them unless you know how to fix the permissions afterwards.
Save the file elsewhere (like your home folder) and then sudo mv it to overwrite the original?
Save the changes as another file and the make the approrpiate replacement.
When vim starts up, the statusbar says [readonly], and the first time you try to edit, it says W10: Warning: Changing a readonly file and pauses for a full second. This is enough warning for me to quit and say sudoedit /etc/somefile.conf.
You can enforce this with a plugin: Make buffer modifiable state match file readonly state.
I use zsh templates and function completion.
Specifically this one. If I don't have write permissions, it prompts for my sudo password and automatically runs "sudo vim"…amongst other things.
I used this:
function! SaveAsSudo()
let v=winsaveview()
let a=system("stat -c \%a " . shellescape(expand('%')))
let a=substitute(a,"\n","","g")
let a=substitute(a,"\r","","g")
call system("sudo chmod 666 " . shellescape(expand('%')))
w
call system("sudo chmod " . a . " " . shellescape(expand('%')))
call winrestview(v)
endfunction
I have mapped <F2> to :w<CR>. & <F8> to :call SaveAsSudo()<CR>
Only advantage this answer provides over the sudo tee option is: vim does not complain about unsaved buffer or file modified externally.

Resources