Vim double-indents python files - python

I get the following behavior. Given this settings.py snippet, hitting 'o' from line 33
31# Application definition
32
33 INSTALLED_APPS = [
34 'rest_framework',
I get this
31# Application definition
32
33 INSTALLED_APPS = [
34 |<-cursor is here, two indents, 8 spaces
35 'rest_framework',
What I really want would be one indent, or a total of 4 spaces, in line with the rest of the list. What gives? I'm using the following .vimrc which I mostly cribbed from here.
set nocompatible " required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" Add all your plugins here (note older versions of Vundle used Bundle instead of Plugin)
" Themes
Plugin 'altercation/vim-colors-solarized'
Plugin 'jnurmine/Zenburn'
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
if has('gui_running')
set background=dark
colorscheme solarized
else
colorscheme zenburn
endif
au BufNewFile,BufRead *.py set tabstop=4 shiftwidth=4 textwidth=79 expandtab autoindent fileformat=unix
set encoding=utf-8
set nu
let python_highlight_all=1
syntax on
set backspace=indent,eol,start

This happens because of default vim indentation plugin for Python. It inserts 2 shiftwidth on the first line below [.
You can see code which causes this behaviour here: https://github.com/vim/vim/blob/0b9e4d1224522791c0dbbd45742cbd688be823f3/runtime/indent/python.vim#L74
I would recommend you to install vim-python-pep8-indent plugin which does indentation inside parenthesis exactly as you need.

According to the code of python.vim provided by #Alik, you can notice that it inserts 2 shiftwidth by default.
return indent(plnum) + (exists("g:pyindent_open_paren") ? eval(g:pyindent_open_paren) : (shiftwidth() * 2))
But you can change this using the g:pyindent_open_paren variable.
For instance:
let g:pyindent_open_paren=shiftwidth()
Or
let g:pyindent_open_paren=4

Related

vim with python: [missing-function-docstring] Missing function or method docstring

I have vim 9.0 with Python support: I have auto complete and Syntax checking for Python installed. Here is my ~/.vimrc file contents:
set nocompatible " required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" add all your plugins here (note older versions of Vundle
" used Bundle instead of Plugin)
" ...
Plugin 'tmhedberg/SimpylFold'
Plugin 'vim-scripts/indentpython.vim'
Plugin 'vim-syntastic/syntastic'
Plugin 'nvie/vim-flake8'
Plugin 'jnurmine/Zenburn'
Plugin 'altercation/vim-colors-solarized'
Plugin 'scrooloose/nerdtree'
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'kien/ctrlp.vim'
Plugin 'tpope/vim-fugitive'
Plugin 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}
Bundle 'Valloric/YouCompleteMe'
set clipboard=unnamed
set nu
let NERDTreeIgnore=['\.pyc$', '\~$'] "ignore files in NERDTree
"if has('gui_running')
" set background=dark
" colorscheme solarized
"else
" colorscheme zenburn
"endif
"so ~/.vim/bundle/vim-colors-solarized/autoload/togglebg.vim
let python_highlight_all=1
syntax on
let g:ycm_autoclose_preview_window_after_completion=1
map <leader>g :YcmCompleter GoToDefinitionElseDeclaration<CR>
set splitbelow
set splitright
"split navigations
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>
" Enable folding
set foldmethod=indent
set foldlevel=99
" Enable folding with the spacebar
nnoremap <space> za
"au BufNewFile,BufRead *.py
" \ setlocal tabstop=4 set softtabstop=4 set shiftwidth=4 set textwidth=79 set expandtab set autoindent set fileformat=unix
au FileType *.js, *.html, *.css
\ setlocal tabstop=2 set softtabstop=2 set shiftwidth=2
"au BufNewFile,BufRead *.js,*.html,*.css,*.vue
"\ set tabstop=2 |
"\ set softtabstop=2 |
"\ set shiftwidth=2
"Flagging Unnecessary Whitespace
highlight BadWhitespace ctermbg=red guibg=darkred
au FileType *.py, *.pyw, *.c, *.h match BadWhitespace /\s\+$/
"au BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/
set encoding=utf-8
"All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
To test the Python support, I created a simple script as the Figure below shows. It has weird warning in two of its lines: [missing-function-docstring] Missing function or method docstring.
How can I suppress such kind of error/warning?
Nothing to worry about. It's a normal behaviour of the YCM Plugin:
From YCM Documentation:
The GetDoc subcommand:
Displays the preview window populated with quick
info about the identifier under the cursor.
Depending on the file type, this includes things like:
The type or declaration of identifier,
Doxygen/javadoc comments,
Python docstrings,
etc.
Thus, when trying to perform its GetDoc functionality in order to display information about the function under the cursor, YCM simply tells you that the function testing() does not have a documentation associated with it.

Custom python editor

I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.
Is there similar type of editor already exists that I can build something upon?
Can I develop such editor? If yes, how?
Try PyCharm, probably this software will cover all your needs
I would suggest, that you use the PyDev plugin for eclipse. PyDev has a lot of stuff, that increases the efficiency. You find it under: http://www.pydev.org/
Best Regards
1574ad6
You can use vim editor by including this line in your ~/.vimrc file.
:h ins-completion
Now you can use the below keyboard shortcut for auto complete feature for your custom functions.
Completion can be done for:
Whole lines |i_CTRL-X_CTRL-L|
keywords in the current file |i_CTRL-X_CTRL-N|
keywords in 'dictionary' |i_CTRL-X_CTRL-K|
keywords in 'thesaurus', thesaurus-style |i_CTRL-X_CTRL-T|
keywords in the current and included files |i_CTRL-X_CTRL-I|
tags |i_CTRL-X_CTRL-]|
file names |i_CTRL-X_CTRL-F|
definitions or macros |i_CTRL-X_CTRL-D|
Vim command-line |i_CTRL-X_CTRL-V|
if you want to learn the vim basics use this link :Vim Basics
You can use this .vimrc file for python development :
set title
autocmd FileType python set expandtab ts=4 sw=4
"autocmd FileType python set sw=4
"autocmd FileType python set sts=4
"autocmd FileType python set ts=4
" enable syntax highlighting
"autocmd FileType python syntax enable
" show line numbers
" set numbe
" set tabs to have 4 spaces
" autocmd FileType python set ts=4
" indent when moving to the next line while writing code
"set autoindent
" expand tabs into spaces
"autocmd FileType python set expandtab
" when using the >> or << commands, shift lines by 4 spaces
"autocmd FileType python set shiftwidth=4
" show a visual line under the cursor's current line
" set cursorline
" show the matching part of the pair for [] {} and ()
set showmatch
" enable all Python syntax highlighting features
autocmd FileType python let python_highlight_all = 1
" to change the default colour of the string to white.
highlight String guifg=1 guibg=11
:h ins-completion

VIM: EOF error when python code requires input

I did setup Vim on my OS X machine, but when I try to execute a code
x=input("which one you like? ")
print(x)
I get an error:
I should mention that there was similar thread, but no acceptable solution was suggested except for not writing any interactive programs..
I will post my .vimrc file content, maybe it can help:
set nocompatible
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
"git interface
Plugin 'tpope/vim-fugitive'
"filesystem
Plugin 'scrooloose/nerdtree'
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'kien/ctrlp.vim'
"html
Plugin 'isnowfy/python-vim-instant-markdown'
Plugin 'jtratner/vim-flavored-markdown'
Plugin 'suan/vim-instant-markdown'
Plugin 'nelstrom/vim-markdown-preview'
"python sytax checker
Plugin 'nvie/vim-flake8'
Plugin 'vim-scripts/Pydiction'
Plugin 'vim-scripts/indentpython.vim'
Plugin 'scrooloose/syntastic'
"auto-completion stuff
"Plugin 'klen/python-mode'
Plugin 'Valloric/YouCompleteMe'
Plugin 'klen/rope-vim'
"Plugin 'davidhalter/jedi-vim'
Plugin 'ervandew/supertab'
""code folding
Plugin 'tmhedberg/SimpylFold'
"Colors!!!
Plugin 'altercation/vim-colors-solarized'
Plugin 'jnurmine/Zenburn'
call vundle#end()
filetype plugin indent on " enables filetype detection
let g:SimpylFold_docstring_preview = 1
"autocomplete
let g:ycm_autoclose_preview_window_after_completion=1
"custom keys
let mapleader=" "
map <leader>g :YcmCompleter GoToDefinitionElseDeclaration<CR>
"
call togglebg#map("<F5>")
"colorscheme zenburn
"set guifont=Monaco:h14
let NERDTreeIgnore=['\.pyc$', '\~$'] "ignore files in NERDTree
"I don't like swap files
set noswapfile
"turn on numbering
set nu
"python with virtualenv support
py << EOF
import os.path
import sys
import vim
if 'VIRTUA_ENV' in os.environ:
project_base_dir = os.environ['VIRTUAL_ENV']
sys.path.insert(0, project_base_dir)
activate_this = os.path.join(project_base_dir,'bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
EOF
"it would be nice to set tag files by the active virtualenv here
":set tags=~/mytags "tags for ctags and taglist
"omnicomplete
autocmd FileType python set omnifunc=pythoncomplete#Complete
"------------Start Python PEP 8 stuff----------------
" Number of spaces that a pre-existing tab is equal to.
au BufRead,BufNewFile *py,*pyw,*.c,*.h set tabstop=4
"spaces for indents
au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
au BufRead,BufNewFile *.py set softtabstop=4
" Use the below highlight group when displaying bad whitespace is desired.
highlight BadWhitespace ctermbg=red guibg=red
" Display tabs at the beginning of a line in Python mode as bad.
au BufRead,BufNewFile *.py,*.pyw match BadWhitespace /^\t\+/
" Make trailing whitespace be flagged as bad.
au BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/
" Wrap text after a certain number of characters
au BufRead,BufNewFile *.py,*.pyw, set textwidth=100
" Use UNIX (\n) line endings.
au BufNewFile *.py,*.pyw,*.c,*.h set fileformat=unix
" Set the default file encoding to UTF-8:
set encoding=utf-8
" For full syntax highlighting:
let python_highlight_all=1
syntax on
" Keep indentation level from previous line:
autocmd FileType python set autoindent
" make backspaces more powerfull
set backspace=indent,eol,start
"Folding based on indentation:
autocmd FileType python set foldmethod=indent
"use space to open folds
nnoremap <space> za
"----------Stop python PEP 8 stuff--------------
Pauliuss-MacBook-Pro:~ Paulius$ less .vimrc
" Use UNIX (\n) line endings.
au BufNewFile *.py,*.pyw,*.c,*.h set fileformat=unix
" Set the default file encoding to UTF-8:
set encoding=utf-8
" For full syntax highlighting:
let python_highlight_all=1
syntax on
" Keep indentation level from previous line:
autocmd FileType python set autoindent
" make backspaces more powerfull
set backspace=indent,eol,start
"Folding based on indentation:
autocmd FileType python set foldmethod=indent
"use space to open folds
nnoremap <space> za
If you do :w !python, the standard input is a temporary file or pipe with your code, which python naturally reads to the end in order to execute the script, hence it's EOF when it gets to input(), and input is not from a terminal.
To solve this problem, insert a line
#!/usr/bin/env python
as the first line of your code file, save it, do :!chmod +x % once and then execute it with :!%.

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

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