MacVim Python Indentation Issue - python

For the past 6 hours, I have been trying to find the source of an annoying bug in my MacVim setup. For reasons detailed below, the first time I opened up a Python file, the indentation was set correctly from the file $VIMRUNTIME/ftplugin/python.vim, which for me was /usr/local/Cellar/macvim/7.4-72/MacVim.app/Contents/Resources/vim/runtime/ftplugin.
However on every subsequent Python file load, the shiftwidth reverted to the global default of 2, which I have set in my .vimrc. In tracking down the issue, I finally came upon this code in the $VIMRUNTIME/ftpluin/python.vim file:
if exists('*<SID>Python_jump') | finish | endif
fun! <SID>Python_jump(motion) range
let cnt = v:count1
let save = #/ " save last search pattern
mark '
while cnt > 0
silent! exe a:motion
let cnt = cnt - 1
endwhile
call histdel('/', -1)
let #/ = save " restore last search pattern
endfun
if has("gui_win32") && !exists("b:browsefilter")
let b:browsefilter = "Python Files (*.py)\t*.py\n" .
\ "All Files (*.*)\t*.*\n"
endif
" As suggested by PEP8.
setlocal expandtab shiftwidth=4 softtabstop=4 tabstop=8
On the first load, <SID>Python_jump isn't defined, so the PEP8 style indentation settings are applied. However, on every next load, the function is available and so the shiftwidth settings are never applied. If I comment out the if exists('*<SID>Python_jump') | finish | endif line, it works as expected and the indentation settings are set correctly on every file load.
Now, what I'm wondering is if this is a genuine problem faced by others as well; in which case I should probably fix it and open up a pull request on the MacVim repo, or do I have something else wrong? I have tried disabling every plugin (I use Vundle, so I just commented out their Bundle lines in my .vimrc), but the result is the same.
Edit
As pointed out by krystah, a au FileType python set shiftwidth=4 also fixes the issue.

I have the same issue. Putting the following line in .vimrc fixed it though.
au FileType python set shiftwidth=4

Related

Pydiction <Tab> isnot popping up with code completion suggestions

I installed Pathogen
and followed http://rkulla.github.io/pydiction/ for installing pydiction
Configuration in my /root/.vimrc also I changed in the path which is given by :echo $MYVIMRC
My .vimrc file :-
filetype plugin on
let g:pydiction_location = '/root/.vim/bundle/pydiction/complete-dict'
let g:pydiction_menu_height = 3
But after these all instructions also I am not getting any suggessions ( by giving tab key) from complete-dict
If anything I left to configure please help me
when I am pressing C-N also in my vim file it is showing like this :-
-- Keyword completion (^N^P) Pattern not found

Do python files need to be on the same drive as the plugin Python-mode for its functionality to work

I'm using the plugin python-mode for gVim on a windows machine.
I have the following python-mode specific settings in my vimrc file:
"------------------------------------------------------------
" settings for Python-mode
" "-----------------------------------------------------------
map <Leader>g :call RopeGotoDefinition()<CR>
let ropevim_enable_shortcuts = 1
let g:pymode_rope_goto_def_newwin = "vnew"
let g:pymode_rope_extended_complete = 1
let g:pymode_breakpoint = 0
let g:pymode_syntax = 1
let g:pymode_syntax_builtin_objs = 0
let g:pymode_syntax_builtin_funcs = 0
map <Leader>b Oimport ipdb; ipdb.set_trace() # BREAKPOINT<C-c>
"Better navigating through omnicomplete option list
set completeopt=longest,menuone
function! OmniPopup(action)
if pumvisible()
if a:action == 'j'
return "\<C-N>"
elseif a:action == 'k'
return "\<C-P>"
endif
endif
return a:action
endfunction
inoremap <silent><C-j> <C-R>=OmniPopup('j')<CR>
inoremap <silent><C-k> <C-R>=OmniPopup('k')<CR>
These were suggested in this tutorial.
vimrc is on my M: drive.
Now if I open vim (set to open in the M: drive) and then open a python file on say the P: drive and then try to save that file I get the following error message:
If I move the file pi.py to the M: drive then everything is happy but surely to use files in vim it shouldn't be a condition that the file being edited is on the same drive as vim?
Can I change my settings for Python-mode to function on files from other drives?
EDIT
Python-mode has the following setting which looks promising:
" Additional python paths
let g:pymode_paths = []
So in vimrc I've added
let g:pymode_paths = ['P:\Comp Apps\Python\']
But still if I open a .py file from that location i get the same error message.
If I execute :lcd %:p:h then the python-mode plugin seems to be working. I can also use set autochdir in my vimrc: not sure if there are any disadvantages to using this setting.

Vim won't properly indent Python code when using the = command

When I use the = command to indent an entire Python file or a section it won't properly indent it. Here's my vimrc:
set nocompatible
syntax on
set ruler
set tabstop=2
set softtabstop=2
set shiftwidth=2
set expandtab
set smarttab
set hlsearch
set incsearch
set ignorecase
set autoindent
" turn on line numbers:
set number
" Toggle line numbers and fold column for easy copying:
nnoremap <F2> :set nonumber!<CR>:set foldcolumn=0<CR>
nnoremap <F4> :set nospell!<CR>
nnoremap <F3> :set invpaste paste?<Enter>
imap <F3> <C-O><F3>
set pastetoggle=<F3>
filetype on
filetype plugin indent on
filetype plugin on
" Execute file being edited with <Shift> + e:
map <buffer> <S-e> :w<CR>:!/usr/bin/env python % <CR>
let g:solarized_termcolors=256
set background=dark
colorscheme solarized
"set spell spelllang=en_us
set backspace=indent,eol,start
autocmd FileType python set complete+=k~/.vim/syntax/python.vim isk+=.,(
autocmd VimEnter * NERDTree
Also when I loop through my python files using w or b for instance, or when deleting it won't delete properly. For instance it will not stop on the . or ( when deleting a work before them and will even delete these.
You should get rid of filetype on and filetype plugin on: filetype plugin indent on is the only line you need.
edit
The problem with . and ( is almost certainly caused by iskeyword. I vaguely remember someone having the same problem because he/she found out in some misinformed blog post that he/she needed dictionary-based completion. Because the entries in his/her dictionary file where in the form .method(, he/she needed the . to be considered a keyword character.
Try this command when editing a Python file:
:verbose set iskeyword?
It should return a comma separated list of values that includes . and ( and the place where it is set. It's most likely to be a third party python ftplugin because the default ftplugin doesn't touch iskeyword.
This line is what is causing the ./( problem:
autocmd FileType python set complete+=k~/.vim/syntax/python.vim isk+=.,(
You absolutely don't need that completion mechanism because Vim's default omnicompletion is powerful enough.
Because of how that completion mechanism is implemented and how your dictionary file may be written, . and ( must be considered by Vim as keyword characters.
Your custom/ syntax file may not even be formed like that so this setting may not even work.
isk is the short form of iskeyword, the option that defines what is a keyword character.
You seem to have copied settings from someone else without understanding what they did. The simple fact that the answer to your question was in your own ~/.vimrc should suffice to show you how wrong this idea is.
you can paste normally usign the :set paste, I have a very handy macro for that:
set pastetoggle=<F10>
You can set it to be any other key, just add it to your .vimrc file

Vim and python: context-unaware autocompletion of language methods

I am writing a little python script to learn VIM basics (I'm a beginner with VIM).
I've configured VIM to work with omnicompletion, and it does.
For example, if I write str. then press ctr+x, ctr+o it suggests me all of the string methods.
However in my code I have something like this:
for line in inFile.readlines():
something = line.rpartition(" ")[0]
I'd like VIM to autocomplete the rpartition method name after typing line.rpart. I don't expect it to know line object type, but I'd like VIM to propose a context-unaware completion list based on python libraries acquaintance.
For example if with eclipse i try to complete
anObject.rpart
it suggests me the rpartition method even if it has nothing to do with anObject!
Is it possible to get this to work with VIM?
Thanks.
My .vimrc file:
set showcmd
set textwidth=80
set expandtab
set smarttab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set number
set autoindent
filetype indent on
filetype plugin on
autocmd BufRead,BufNewFile *.py syntax on
autocmd BufRead,BufNewFile *.py set ai
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,with,try,except,finally,def,class
set modeline
syntax on
" Closes the Omni-Completion tip window when a selection is
" made
autocmd CursorMovedI * if pumvisible() == 0|pclose|endif
autocmd InsertLeave * if pumvisible() == 0|pclose|endif
Seriously, use Jedi!
It's really much better than all the other autocompletions around.
May the force be with you!
You definitely should take a look at PySmell which can be installed for Vim easily. It generates a completion menu based on a static analysis for a given project. It also can generate completion suggestions based on tags it produces for external libraries like the Python Standard Library or Django Lib.
I was happy with Vims Python omnicimpletion, but since I switched to PySmell, I never looked back.

Describe your customized Vim editor for Python/Django development?

I've recently switched entirely to Vim for all my Python/Django development. It took me a lot of time to customize it to the point it is today, and God knows how hard it was for me to find help regarding the best vim plugins out there suited for Python/Django development.
I decided to ask this question so people like me could benefit directly from your experience:
You've built the perfect Python/Djangoish Vim editor? Describe it for us (plugins, scripts, customized .vimrc, colorschemes ..etc).
Thanks
My Configuration
Ok, this is my own configuration. actually I've chosen to create a simple Vim configuration so I can master the little number of plugins I've chosen to install instead of make a big stack of plugins that I'll never master nor use. This is the list of the plugins I use the most:
NERDTree for file management,
SnipMate which is an implementation of TextMate's snippets feature,
Code Completion is handled with Omnicompletion which come by default in Vim,
Pydoc to integrate the Python Documentation into Vim,
TagList for source code browsing, very useful in large files.
Pyflakes script to highlight Python code on the fly with warnings
Also I've created a python.vim file in $HOME/.vim/ftplugin/ containing this script so I can run python code from Vim just by running Shift+e:
" Execute file being edited with <Shift> + e:
map <buffer> <S-e> :w<CR>:!/usr/bin/env python % <CR>
Also I've collected some useful .vimrc customizations:
set nocompatible " use vim defaults
set number " show line numbers
colorscheme desert
set tags=tags;$HOME/.vim/tags/ "recursively searches directory for 'tags' file
set expandtab " tabs are converted to spac
set tabstop=4 " numbers of spaces of tab character
set shiftwidth=4 " numbers of spaces to (auto)indent
set showcmd " display incomplete commands
set hlsearch " highlight searches
set incsearch " do incremental searching
set ruler " show the cursor position all the time
set numberwidth=4 " line numbering takes up 5 spaces
set ignorecase " ignore case when searching
set nowrap " stop lines from wrapping
filetype plugin indent on " turn on the indent plugins
syntax on " syntax highlighing
" TagList Plugin Configuration
let Tlist_Ctags_Cmd='/usr/bin/ctags' " point taglist to ctags
let Tlist_GainFocus_On_ToggleOpen = 1 " Focus on the taglist when its toggled
let Tlist_Close_On_Select = 1 " Close when something's selected
let Tlist_Use_Right_Window = 1 " Project uses the left window
let Tlist_File_Fold_Auto_Close = 1 " Close folds for inactive files
" Omnicompletion functions
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
au FileType py set expandtab
au FileType py set foldmethod=indent
map <F2> :previous<CR> " map F2 to open previous buffer
map <F3> :next<CR> " map F3 to open next buffer
map <F4> :NERDTreeToggle<CR> " map F4 to open NERDTree
map <F5> :TlistToggle<CR> " map F5 to toggle the Tag Listing
map <silent><C-Left> <C-T> " taglist - map Ctrl-LeftArrow to jump to the method/property under your cursor
map <silent><C-Right> <C-]> " taglist - map Ctrl-RhitArrow to jump back to your source code
map <silent><A-Right> :tabnext<CR> " map Alt-RightArrow to jump to the next tab
map <silent><A-Left> :tabprevious<CR> " map Alt-LeftArrow to jump to the previous tab
I don't really have much Django specific mods, although I have given the jinja2 syntax a higher priority than the django template syntax.
For Python specifically:
For Python syntax checking I use PyFlakes with highlight SpellBad ctermbg=darkred
Sometimes (rarely) I feeld the need for autocompletion and in that case I use Eclim
For the rest, the default stuff. Tab size 4, soft tabs, etc...
Vim Settings:
256 Color scheme desert256
if ((&term == 'screen') || (&term == 'screen-bce') || (&term == 'xterm'))
set t_Co=256
set t_Sb=^[[4%dm
set t_Sf=^[[3%dm
colo desert256
endif
Lots of tabs (tabe, tabn)
Lots of splits (both vertical and horizontal)
I am not going to post my whole .vimrc file here, but I have a similiar setup as you. This is less Python/Django specific though, except for some custom snippets for snipMate and python-mode. Here the vim plugins I am using:
Pathogen: better organized vim plugin structure in .vim dir
comments.vim: faster language specific commenting with ctrl-c and ctrl-x
NERDTree
NERDTree tabs
syntastic: Syntax checking plugin (for me mainly used for non-python code)
surround.vim and autoclose.vim: Easier handling of brackets, opening and closing tags etc.
matchit: extends the % command to also match and circle through for example html tags. For circling through Python code statements (eg. if-elif-else) you can download python_match.vim and put it into your ftplugin/python/ dir. I put it into ~/.vim/bundle/matchit/ftplugin/python/
python-mode: Great plugin for Python editing. Has automated pyflakes/pep8 checking (or pylint if you want) on file save. I deactivated the auto complete via let g:pymode_rope = 0 in my .vimrc file though, since it lagged for me on each file save. Also the syntax highlighting is extended for python code.
snipMate (custom snippets for python follow below)
tagBar: I can't live without an outline for huge code files.
Some custom python snippets I use quite frequently:
snippet #utf
# -*- coding: utf-8 -*-
snippet ds
"""
${1: }
"""
# just the first (or last) three quites for the docstring
snippet dss
"""${1: }
# For file headers
snippet dsfile
"""
:File: ${1:`Filename('$1.py', 'foo.py')`}
:Author: ${2:`g:snips_author`}
:Description: ${3}
"""
snippet pdb
import pdb
pdb.set_trace()

Categories