59vuww
Last Updated: May 11, 2017
·
10.16K
· croaky
8e2b996de3842c6ef7e68a82fa5f01f5

Fix "Can't open file for writing" in Vim

I learned this tip watching Sean Griffin in Hands-On Backbone.js on Rails.

The error

Edit a new file in a directory that does not exist yet, such as app/views/application:

:e app/views/application/index.html.erb

Try to save the file:

:x

An error will display:

"app/views/application/index.html.erb" E212: Can't open file for writing
Press ENTER or type command to continue

The error means is it can't save the file because app/views/application doesn't exist. So, we have to create it.

Making the directory in the shell

I used to suspend Vim:

Ctrl+Z

Then, create the directory from the shell:

mkdir app/views/application

Then, bring Vim back to the foreground:

fg

Making the directory in Vim

What Sean does in Hands-On Backbone.js on Rails is create the directory right from Vim:

:!mkdir -p %:h

Much faster!

How it works

% is the current file in Vim. %:h is the directory in which the current file is located. So, when editing app/views/application/index.html.erb, the command expands to mkdir -p app/views/application.

Bonus!

For the fastest approach yet, use vim-mkdir to just automatically make the directory when it doesn't exist, with no manual intervention necessary.

Say Thanks
Respond

2 Responses
Add your response

12698
D42a7264714dee5006b9c99d2567a320

Is there a similar solution for when we have no write permissions to a catalog and have to restart vim with sudo?

over 1 year ago ·
12717
D42a7264714dee5006b9c99d2567a320

@jimmykane thanks!

over 1 year ago ·