Automatically inserting a header in vim - python

Is there a way to auto add a header when i open a new file in vim?
My objective is to automatically add the shebang "#! /usr/bin/python" when i open a new file using the command "vim test.py". If the file is already present, no header should be inserted.

Add this line in your configuration file:
autocmd BufNewFile *.py 0put =\"#!/usr/bin/python\<nl>\"|$

This might be over-kill, but you could look at one of the snippet scripts for Vim, e.g. snipMate -- http://www.vim.org/scripts/script.php?script_id=2540
But, for what you want, you might just map a key to a command that reads in a file. For example:
nmap <leader>r :r boiler_mashbang<cr>
And, then put your boilerplate in the file: boiler_mashbang.

Related

How can I make Vim open .py files in different lines?

Previously, I used Spyder to write my files, but recently began making the transition to Vim. When I open a .py file using Vim, all previous lines are blended into the first, but separated with ^M.
My ~/.vimrc file uses filetype plugin indent on which I thought would solve this issue.
Thanks!
A file that has only ^M (also known as <CR>, or carriage return) as line separator is using the file format of mac. That seems to be the format of the file you're opening here.
Since this file format is so unusual, Vim will not try to detect it. You can tell Vim to detect it by adding the following to your vimrc file:
set file formats+=mac
Alternatively, you can use this format while opening a single file by using:
:e ++ff=mac script.py
You might want to convert these files to the more normal unix file format. You can do so after opening a file, with:
:set ff=unix
And then saving the file, with :w or similar.
From what I know ^M is the special character used for carriage return in vim. You should just be able to replace it
:%s/^M/\r/g
I would imagine that the ^M is there as some kind of specific configuration spider uses that couldn't be translated well in vim. I am just speculating here, could be totally wrong.
Substituting using hexadecimal notation is better in my opinion:
:%s/\%x0D$//e
Explanation: If the user try to type caret M instead of CtrlvEnter he of she will think that is a mistake.

.vimrc file not working as expected

If I open a python file with vim, and set it to have a ruler and auto-line break with this command:
:set textwidth=109 colorcolumn=110
It works like a charm! However ... if I edit ~/.vimrc and add this line at the bottom
autocmd FileType py set textwidth=109 colorcolumn=110
exit the python file, and open it again, nothing happens. Seems like something is overriding my setting, but can't figure out what is doing that (because I'm fairly new to vim). My basic vimrc file is this: https://github.com/amix/vimrc/blob/master/vimrcs/basic.vim
Can someone point me in the right direction on what am I doing wrong?
Note: the same thing is happening for Javascript files when I try to "replace" Tabs with 2 spaces in indentation:
autocmd FileType js setlocal sw=2 sts=2 et
The issue is that the correct filetypes are python and javascript (or similar, like javascript.jsx if you have additional syntax files), not py and js. You can check the filetype used for a file by :set ft?.
Also, you may prefer setlocal (to affect only the current buffer) instead of set.

Vim cannot save to temporary files created by python

Goal
I am trying to create and edit a temporary file in vim (exactly the same behavior as a commit script in git/hg/svn).
Current code
I found a method to do so in this answer:
call up an EDITOR (vim) from a python script
import sys, tempfile, os
from subprocess import call
EDITOR = os.environ.get('EDITOR','vim')
initial_message = "write message here:"
with tempfile.NamedTemporaryFile(suffix=".tmp") as tmp:
tmp.write(initial_message)
tmp.flush()
call([EDITOR, tmp.name])
tmp.seek(0)
print tmp.read()
The Issue
When I run the above code, the tempfile does not read the changes made in vim. Here is the output after I have added several other lines in vim:
fgimenez#dn0a22805f> ./note.py
Please edit the file:
fgimenez#dn0a22805f>
Now for the interesting (weird) part. If I change my editor to nano or emacs, the script works just fine! So far, this only seems to break when I use vim or textedit.
As another experiment, I tried calling a couple editors in a row to see what happens. The modified code is:
with tempfile.NamedTemporaryFile(suffix=".tmp") as tmp:
tmp.write(initial_message)
tmp.flush()
# CALLING TWO EDITORS HERE, VIM THEN NANO
call(['vim', tmp.name])
raw_input("pausing between editors, just press enter")
call(['nano', tmp.name])
tmp.seek(0)
print tmp.read()
I.e. I edit with vim then nano. What happens is that nano DOES register the changes made by vim, but python doesn't register anything (same result as before):
fgimenez#dn0a22805f> ./note.py
Please edit the file:
fgimenez#dn0a22805f>
BUT, if I edit with nano first, then vim, python still registers the nano edits but not the vim ones!
with tempfile.NamedTemporaryFile(suffix=".tmp") as tmp:
tmp.write(initial_message)
tmp.flush()
# CALLING TWO EDITORS HERE, NANO THEN VIM
call(['nano', tmp.name])
raw_input("pausing between editors, just press enter")
call(['vim', tmp.name])
tmp.seek(0)
print tmp.read()
Ouput from running the program and adding a\nb\nc in nano and d\ne\nf in vim:
fgimenez#dn0a22805f> ./note.py
Please edit the file:
a
b
c
fgimenez#dn0a22805f>
It seems as if using vim or textedit eliminates the ability to append to the file. I'm completely confused here, and I just want to edit my notes in vim...
Edit 1: Clarifications
I am on osx Mavericks
I call vim from the shell (not MacVim) and end the session with ZZ (also tried :w :q)
I'm no Python expert, but it looks like you're keeping the handle to the temp file open while Vim is editing the file, and then attempt to read in the edited contents from the handle. By default, Vim creates a copy of the original file, writes the new contents to another file, and then renames it to the original (see :help 'backupcopy' for the details; other editors like nano apparently don't do it this way). This means that the Python handle still points to the original file (even though it may have already been deleted from the file system, depending on the Vim settings), and you get the original content.
You either need to reconfigure Vim (see :help 'writebackup'), or (better) change the Python implementation to re-open the same temp file name after Vim has exited, in order to get a handle to the new written file contents.
I had the same problem on OS X after my code worked fine on Linux. As Ingo suggests, you can get the latest contents by re-opening the file. To do this, you probably want to create a temporary file with delete=False and then explicitly delete the file when you're done:
import sys, tempfile, os
from subprocess import call
EDITOR = os.environ.get('EDITOR','vim')
initial_message = "write message here:"
with tempfile.NamedTemporaryFile(suffix=".tmp", delete=False) as tmp:
tmp.write(initial_message)
tmp.flush()
call([EDITOR, tmp.name])
tmp.close()
with open(tmp.name) as f:
print f.read()
os.unlink(tmp.name)

how to map F4 run a no name file on vim?

I add a line in _vimrc .
map <F4> :w<cr>:!python %<cr>
If the file contain name ,it can run,if the file is a new edited which contain no name ,when i press F4 ,it can't run .
I want to make my configuration more smart ,and don't want to save it ,give it a name and press F4,how can i revise map <F4> :w<cr>:!python %<cr> to make the no name python file to run ?
How about using :w !{cmd}? (This does not require you to save before run the command).
:map <F4> :w !python<cr>
According to vim help :w_c:
:[range]w[rite] [++opt] !{cmd}
Execute {cmd} with [range] lines as standard input
(note the space in front of the '!'). {cmd} is
executed like with ":!{cmd}", any '!' is replaced with
the previous command |:!|.
NOTE This will not work as expected if the Python program itself use filename. (For example, __file__ will yield '<stdin>')

How do I modify program files in Python?

In the actual window where I right code is there a way to insert part of the code into everyline that I already have. Like insert a comma into all lines at the first spot>?
You need a file editor, not python.
Install the appropriate VIM variant for your operating system
Open the file you want to modify using VIM
Type: :%s/^/,/
Type: :wq
If you are in UNIX environment, open up a terminal, cd to the directory your file is in and use the sed command. I think this may work:
sed "s/\n/\n,/" your_filename.py > new_filename.py
What this says is to replace all \n (newline character) to \n, (newline character + comma character) in your_filename.py and to output the result into new_filename.py.
UPDATE: This is much better:
sed "s/^/,/" your_filename.py > new_filename.py
This is very similar to the previous example, however we use the regular expression token ^ which matches the beginning of each line (and $ is the symbol for end).
There are chances this doesn't work or that it doesn't even apply to you because you didn't really provide that much information in your question (and I would have just commented on it, but I can't because I don't have enough reputation or something). Good luck.
Are you talking about the interactive shell? (a.k.a. opening up a prompt and typing python)? You can't go back and edit what those previous commands did (as they have been executed), but you can hit the up arrow to flip through those commands to edit and reexecute them.
If you're doing anything very long, the best bet is to write your program into your text editor of choice, save that file, then launch it.
Adding a comma to the start of every line with Python:
import sys
src = open(sys.argv[1])
dest = open('withcommas-' + sys.argv[1],'w')
for line in src:
dest.write(',' + line)
src.close()
dest.close()
Call like so: C:\Scripts>python commaz.py cc.py. This is a bizzare thing to do, but who am I to argue.
Code is data. You could do this like you would with any other text file. Open the file, read the line, stick a comma on the front of it, then write it back to file.
Also, most modern IDEs/text editors have the ability to define macros. You could post a question asking for specific help for your editor. For example, in Emacs I would use C-x ( to start defining a macro, then ',' to write a comma, then C-b C-n to go back a character and down a line, then C-x ) to end my macro. I could then run this macro with C-x e, pressing e to execute it an additional time.

Categories