66from pyvim .completion import DocumentCompleter
77from pyvim .reporting import report
88
9+ import stat
910import os
1011import weakref
1112
@@ -127,7 +128,7 @@ def reload(self):
127128 self .buffer .document = Document (text , cursor_position )
128129 self ._file_content = text
129130
130- def write (self , location = None ):
131+ def write (self , location = None , force = False ):
131132 """
132133 Write file to I/O backend.
133134 """
@@ -144,15 +145,40 @@ def write(self, location=None):
144145 self .editor .show_message ('Unknown location: %r' % location )
145146
146147 # Write it.
147- try :
148- io .write (self .location , self .buffer .text + '\n ' , self .encoding )
149- self .is_new = False
150- except Exception as e :
151- # E.g. "No such file or directory."
152- self .editor .show_message ('%s' % e )
153- else :
154- # When the save succeeds: update: _file_content.
155- self ._file_content = self .buffer .text
148+ toggle_write_permission = False
149+ done = False
150+ while (not done ):
151+ try :
152+ io .write (self .location , self .buffer .text + '\n ' , self .encoding )
153+ self .is_new = False
154+ if toggle_write_permission :
155+ try :
156+ os .chmod (self .location , os .stat (self .location ).st_mode & ~ stat .S_IWRITE )
157+ done = True
158+ except Exception as e :
159+ self .editor .show_message ('%s' % e )
160+ done = True
161+ except Exception as e :
162+ if os .path .isfile (self .location ) and (not os .access (self .location , os .W_OK )): # File is not writable
163+ if force :
164+ if not toggle_write_permission :
165+ try :
166+ os .chmod (self .location , os .stat (self .location ).st_mode | stat .S_IWRITE )
167+ toggle_write_permission = True
168+ except Exception as e :
169+ self .editor .show_message ('%s' % e )
170+ done = True
171+ else :
172+ # E.g. "No such file or directory."
173+ self .editor .show_message ('%s' % e )
174+ done = True
175+ else :
176+ self .editor .show_message ("'readonly' option is set (add ! to override)" )
177+ done = True
178+ else :
179+ # When the save succeeds: update: _file_content.
180+ self ._file_content = self .buffer .text
181+ done = True
156182
157183 def get_display_name (self , short = False ):
158184 """
0 commit comments