一键完成Python开发环境搭建: Cygwin+Vim

准备工作

首先安装Cygwin, 安装很简单, 下载32位或者64位可执行文件。双击使用默认设置安装即可, 注意在源的选择时, 可以选择科大源:http://mirrors.ustc.edu.cn, 比较快。为了方便下面安装apt-cyg包管理器, 我们在首次安装时, 按下图安装lynx包管理器:

安装lynx包管理器

为了方便命令行执行Cygwin安装包的过程, 我们还需要安装apt-cyg, 按照官网提示, 在Cygwin64 Terminal中执行如下命令即可。

lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg
install apt-cyg /bin

至此, 准备工作完成了。

强大的一键安装脚本

我自己写了一个一键安装脚本。 该脚本有如下特征:

  • 自动生成规范的vimrc
  • 设置Cygwin的Term为vim模式, 命令行也可以用vim快捷键了(例如j/k/b/e等移动快捷键)
  • 设置Cygwin的Term的Solarized配色/编码
  • 备份Cygwin默认路径(带windows路径)到~/.path
  • 默认安装curl,wget,git,vim,ctags等必备程序
  • 默认安装python3-devel, pip3,autopep8(python开发必备)
  • 默认安装gcc-g++,make,cmake,libclang-devel-static(C++编译环境, 因为YouCompleteMe插件需要编译)
  • 高亮脚本安装步骤
vimrc的说明
  • 自动生成的vimrc默认安装了如下的插件
    " for fold
    Plug 'Konfekt/FastFold'
    " for ctags
    Plug 'ludovicchabant/vim-gutentags'
    " for powerline
    Plug 'vim-airline/vim-airline'
    Plug 'vim-airline/vim-airline-themes'
    Plug 'powerline/fonts', { 'do' : './install.sh'}
    " for session
    Plug 'thaerkh/vim-workspace'
    " for grammar check
    "Plug 'vim-syntastic/syntastic'
    " for soloarlized
    Plug 'altercation/vim-colors-solarized'
    " solarized for cygwin
    Plug 'mavnn/mintty-colors-solarized'
    " for python formatting
    Plug 'tell-k/vim-autopep8'
    " for autocomplete
    Plug 'Valloric/YouCompleteMe', { 'do' : './install.py --clang-completer --system-libclang' }
    " for file tree
    Plug 'scrooloose/nerdtree'
    " for commenting
    Plug 'scrooloose/nerdcommenter'
    " for line-style indent
    Plug 'Yggdroot/indentLine'
  • 默认配色为solarized+aireline
  • 定义了少数使用较频繁的快捷键
" 用jk代替esc
inoremap jk <Esc>
" 窗口切换
nnoremap nw <C-w><C-w>
" 关闭当前窗口
nnoremap ww <C-W>q
" 在新窗口中打开光标下文件
nnoremap Gf <C-w>gf
" 自动补全
imap <A-j> <C-x><C-o>
"复制并粘贴本段
noremap cp yap<S-}>p
"格式化本段
noremap ;a =ip
"开/关粘贴模式(解决粘贴时自动添加注释的问题)
set pastetoggle=;z
" use qq to recode, q to stop and Q to apply
nnoremap Q @q
vnoremap Q :norm @q<cr>
"复制到剪切板
vnoremap ;x "*y
"从剪切板粘贴
nmap ;p "*p
"F5一键编译python/C++
au FileType python map <buffer>  <F5> :Autopep8<cr> :w<cr> :call RunPythonOrC()<cr>
au FileType cpp map <buffer>  <F5> :w<cr> :call RunPythonOrC()<cr>
" F4 注释python
au FileType python map <buffer> <F4> <leader>ci <cr>
" }}}

脚本源码

将下面的代码另存为vim-python.sh, 然后执行bash vim-python.sh即可自动安装.

#!/usr/bin/bash
# Color constants
BLACK='\033[0;30m'
RED='\033[0;31m'
GREEN='\033[0;32m'
ORANGE='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
LGRAY='\033[0;37m'
DGRAY='\033[1;30m'
LRED='\033[1;31m'
NC='\033[0m'

#Backup path
echo -e "${ORANGE}Backup${NC}: Save path to ~/.path"
if [ -f ~/.path ]; then
  echo -e "${ORANGE}Warning${NC}: ~/.path already exits!"
else
  echo $PATH > ~/.path
fi
if ! [ -f ~/.bash_aliases ]; then
  echo 'export PATH=/usr/local/bin:/usr/bin:.' > ~/.bash_aliases
fi
#Check apt-cyg: commandline installer for cygwin
if ! [ -x "$(command -v apt-cyg)" ]; then
  echo -e >&2 "${RED}Error${NC}: apt-cyg not installed. Aborting!"
  exit 1
fi
#Install curl,wget,git,vim,ctags
echo -e "${GREEN}Install${NC}: curl, wget, git, vim, ctags..."
sleep 1
apt-cyg install curl wget git vim ctags
#For python
echo -e "${GREEN}Install${NC}: python3-devel...\n\tFor python development environment"
sleep 1
apt-cyg install python3-devel 
if ! [ -x "$(command -v pip3)" ]; then
  echo -e "${GREEN}Intall${NC}: pip..."
  sleep 1
  python3 -m ensurepip
  #solve /usr/bin/env ptthon not found
  ln -sf /usr/bin/python3 /usr/bin/python
fi
# for c-compile environments
echo -e "${GREEN}Install${NC}: gcc-g++, make, cmake, libclang-devel-static...\n\tFor Vim plugin YouCompleteMe"
sleep 1
apt-cyg install gcc-g++ make cmake  libclang-devel-static

if ! [ -x "$(command -v autopep8)" ]; then
  echo -e "${GREEN}Intall${NC}: autopep8..."
  sleep 1
  pip3 install --upgrade autopep8
fi

#Configurations
#0. for shell, use vi mode: ~/.inputrc
if [ -f ~/.inputrc ]; then
  echo "set editing-mode vi\n" >> ~/.inputrc
fi
#1. for term: ~/.minttyrc
read -d '' TTYC << EOM
X=0
Y=0
Columns=100
Rows=29
BellType=0
Scrollbar=none
Transparency=low
OpaqueWhenFocused=yes
CursorBlinks=yes

#Solarized for mintty
# from mavnn/mintty-colors-solarized
ForegroundColour=131,148,150
BackgroundColour=0,43,54
CursorColour=220,50,47

Black=7,54,66
BoldBlack=0,43,54
Red=220,50,47
BoldRed=203,75,22
Green=133,153,0
BoldGreen=88,110,117
Yellow=181,137,0
BoldYellow=101,123,131
Blue=38,139,210
BoldBlue=131,148,150
Magenta=211,54,130
BoldMagenta=108,113,196
Cyan=42,161,152
BoldCyan=147,161,161
White=238,232,213
BoldWhite=253,246,227
BoldAsFont=-1
FontHeight=12
CursorType=block
Term=xterm-256color
Language=
Locale=
Charset=UTF-8
Font=DejaVu Sans Mono for Powerline
EOM

if ! [ -f ~/.minttyrc ]; then
  echo "$TTYC" > ~/.minttyrc
fi
#2. for vim: ~/.vim/vimrc
#   Check vim-plug installed or not
if ! [ -f ~/.vim/autoload/plug.vim ]; then
  curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
fi
# The vimrc
read -d '' VIMC << EOF
" vim: fdm=marker fdl=0 fdls=0
" Check the operating system {{{
if !exists( 'g:os' )
  if has( 'win32' ) || has( 'win64' )
    let g:os  = 'Windows'
  elseif has( 'win32unix' )
    let g:os = 'Cygwin'
  else
    let g:os  = substitute( system( 'uname' ), '\\\\n', '', '')
    "g:os = Windows,Cygwin,Darwin,Linux
  endif
endif
" }}}
" USER Variable {{{
let \$VIMHOME=expand( \$HOME . '/.vim/' )
let \$USRVIMD=expand( \$VIMHOME . 'myvim/' )
let \$USRPLGD=expand( \$USRVIMD . 'plugged/' )
let \$USRSECD=expand( \$USRVIMD.'sessions' )
let \$USRTEMPD=expand( \$USRVIMD . 'vimtemp/' )
if has( 'gui_running' )
  let \$USRLWKDIR  =expand( \$USRSECD.'/lastworkdirg' )
else
  let \$USRLWKDIR  =expand( \$USRSECD.'/lastworkdir' )
endif
" }}}
" User functions {{{
" Echo highlight functions {{{
if !exists( "*ColorEcho" )
  fu! ColorEcho( msg )
    let s:index = 0
    for item in split( a:msg, '|' )
      if !(s:index % 2)
        if item == ''
          let item = 'None'
        endif
        silent! exec 'echohl ' item
      else
        echon item
      endif
      let s:index +=1
    endfor
  endf
en
" }}}
" Save working dir {{{
if !exists( '*Saveworkdir' )
  fu Saveworkdir()
    if g:os == 'Windows'
      silent! exec "!cd > " \$USRLWKDIR
    else
      silent! exec "! pwd > " \$USRLWKDIR
    endif
  endf
endif
" }}}
" lcd to last working directory {{{
if !exists( '*Gotoworkdir' )
  fu Gotoworkdir()
    if ( !empty(glob( \$USRLWKDIR )) )
      if g:os != 'Windows'
        lcd \`=system( 'cat ' . \$USRLWKDIR )\`
      else
        lcd \`=system( 'type ' . \$USRLWKDIR )\`
      endif
    endif
  endf
endif
" }}}
" RunPythonOrC {{{
if !exists( '*RunPythonOrC' )
fu RunPythonOrC()
  let mp = &makeprg
  let ef = &errorformat
  let exeFile = expand("%:t")
  if ( &ft =~ 'python')
    setlocal makeprg=python3\\\\ -u
  elseif ( &ft =~'cpp' )
    setlocal makeprg=g++\\\\ 
  endif
  set efm=%C\\\\ %.%#,%A\\\\ \\\\ File\\\\ \\\\"%f\\\\"\\\\\\\\,\\\\ line\\\\ %l%.%#,%Z%[%^\\\\ ]%\\\\\\\\@=%m
  silent make %
  copen
  let &makeprg = mp
  let &errorformat = ef
  redraw!
endf
endif
" }}}
" }}}
" General configuration {{{
" Vim settings {{{
" Not for vi {{{
set nocp
" }}}
" Line number {{{
set nu
" }}}
" Auto change to the current directory {{{
set acd
" }}}
" Auto complete of vim command-line {{{
set wmnu
" }}}
" Increase search {{{
set incsearch
" }}}
" Show position of cursor at status line {{{
set ruler
" }}}
" Syntex highlighting {{{
syntax on
" }}}
" Autochdir {{{
set autochdir
" }}}
" Allow backspace in insert mode {{{
set backspace=2
" }}}
" No beep {{{
set vb
" }}}
" Shorter spaces {{{
set shiftwidth=2 tabstop=2
" }}}
" Auto indent {{{
if has('autocmd')
  filetype plugin indent on
endif
" }}}
" Copy indent {{{
set autoindent
" }}}
" Smart indent {{{
set smartindent
" }}}
" Smart table {{{
set smarttab
" }}}
" Use space for tab {{{
set expandtab
" }}}
" Set wrap, list disables line break {{{
set wrap lbr tw=0 wm=0 nolist
" }}}
" }}}
" Fold fill char {{{
set fillchars=vert:\\\\|,fold:-
" }}}
" Encodings {{{
" Encoding for file {{{
set fenc=utf-8
" }}}
" Encoding for file's content {{{
"   If you want gvim under windws prompt
"   callback of shell command correctly
"   you need the following settings:
"   set enc=chinese
set enc=utf-8
scriptencoding utf-8
" }}}
" Encoding for term {{{
set termencoding=utf-8
" }}}
" Supported encoding {{{
set fencs=usc-bom,
      \\\\utf-8,
      \\\\chinese,
      \\\\cp936,
      \\\\gb18030,
      \\\\big5,
      \\\\euc-jp,
      \\\\euc-kr,
      \\\\latin1
" }}}
" Supported filefomart {{{
" auto detect mac,unix,dos
set ffs=mac,unix,dos
" }}}
" Vim message encoding {{{
language messages en_US.utf-8
" }}}
" set swap directory {{{
if !isdirectory( \$USRTEMPD )
  if g:os == 'Windows'
    silent! exec '!mkdir ' \$USRTEMPD
  else
    silent! exec '!mkdir -p ' \$USRTEMPD
  endif
endif
set backupdir =\$USRTEMPD
set directory =\$USRTEMPD
set undodir =\$USRTEMPD
" }}}
" }}}
" }}}
" Better help {{{
" Press K to show help of keyword under cursor {{{
set keywordprg=:help
" }}}
" Open help window vertically {{{
augroup vertichelp
  au!
  au FileType help
        \\\\ wincmd L |
        \\\\ vertical res 80
augroup END
" }}}
" }}}
" Plugin admin {{{
" vim-plug https://github.com/junegunn/vim-plug
if !empty( glob( expand( \$VIMHOME . 'autoload/plug.vim' ) ) )
  " Add Plug owner/projname then run PlugInstall
  " The root of plug is \$USRPLGD
  call plug#begin( \$USRPLGD )
    " for fold
    Plug 'Konfekt/FastFold'
    " for ctags
    Plug 'ludovicchabant/vim-gutentags'
    " for powerline
    Plug 'vim-airline/vim-airline'
    Plug 'vim-airline/vim-airline-themes'
    Plug 'powerline/fonts', { 'do' : './install.sh'}
    " for session
    Plug 'thaerkh/vim-workspace'
    " for grammar check
    "Plug 'vim-syntastic/syntastic'
    " for soloarlized
    Plug 'altercation/vim-colors-solarized'
    " solarized for cygwin
    Plug 'mavnn/mintty-colors-solarized'
    " for python formatting
    Plug 'tell-k/vim-autopep8'
    " for autocomplete
    Plug 'Valloric/YouCompleteMe', { 'do' : './install.py --clang-completer --system-libclang' }
    " for file tree
    Plug 'scrooloose/nerdtree'
    " for commenting
    Plug 'scrooloose/nerdcommenter'
    " for line-style indent
    Plug 'Yggdroot/indentLine'
  call plug#end()
endif
" }}}
" Color theme {{{
" Solarized
if isdirectory( \$USRPLGD . 'vim-colors-solarized' )
  let g:solarized_termcolors=256
  let g:solarized_termtrans=1
  set t_Co=256
  syntax enable
  if has('gui_running')
    set bg=light
  else
    set bg=dark
  endif
  colo solarized
endif
" }}}
" Vim-workspace configuration {{{
if isdirectory( \$USRPLGD . 'vim-workspace' )
  "Auto create session
  let g:workspace_autocreate =1
  " Disable autosave
  let g:workspace_autosave = 0
  let g:workspace_undodir=\$USRTEMPD . 'undodir'
  " Compatibility with vim and gvim {{{
  if has( 'gui_running' )
    let g:workspace_session_name = 'gsession.vim'
  else
    let g:workspace_session_name = 'session.vim'
  endif
  augroup workdir
    au!
    au VimEnter * call Gotoworkdir()
    au VimLeave * call Saveworkdir()
  augroup END
  " }}}
endif
" }}}
" Airline configuration {{{
let g:airline_powerline_fonts = 1
let g:airline#extensions#tabline#enabled = 1
"let g:airline_theme='powerlineish'
"let g:Powerline_symbols= 'fancy'
"
if !exists('g:airline_symbols')
  let g:airline_symbols = {}
endif
" unicode symbols
let g:airline_symbols.crypt = '??'
let g:airline_symbols.linenr = ''
let g:airline_symbols.maxlinenr = '??'
let g:airline_symbols.branch = '??'
let g:airline_symbols.paste = ''
let g:airline_symbols.readonly = '??'
let g:airline_symbols.spell = 'SPELL'
let g:airline_symbols.notexists = ''
let g:airline_symbols.whitespace = '??'
" }}}
" Syntastic configuration{{{
if isdirectory( \$USRPLGD . 'syntastic')
  let g:syntastic_tex_checkers = ['chktex' ]
  let g:syntastic_text_checkers = ['language_check']
  let g:syntastic_aggregate_errors = 1
  let g:syntastic_text_language_check_args = '--language=en-US'
  let g:syntastic_always_populate_loc_list = 1
  let g:syntastic_auto_loc_list = 1
  let g:syntastic_check_on_open = 1
  let g:syntastic_check_on_wq = 0
endif
" }}}
" YouCompleteMe configuration {{{
" default config path
"let g:ycm_global_ycm_extra_conf = '~/.vim/myvim/plugged/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'
"let g:ycm_confirm_extra_conf=0
set completeopt=longest,menu
"python interpreter path"
let g:ycm_path_to_python_interpreter='python3'
"syntax complete"
let g:ycm_seed_identifiers_with_syntax=1
"complete in comments
let g:ycm_complete_in_comments=1
let g:ycm_collect_identifiers_from_comments_and_strings = 0
"complete in string
let g:ycm_complete_in_strings = 1
"number of char for active complete
let g:ycm_min_num_of_chars_for_completion=2
"auto close complete window
let g:ycm_autoclose_preview_window_after_completion=1
augroup complete
  au!
  au InsertLeave * if pumvisible() == 0|pclose|endif
augroup END
"no cache for complete functions
let g:ycm_cache_omnifunc=0
"use enter for slection
inoremap <expr> <CR>       pumvisible() ? '<C-y>' : '\<CR>'     
" }}}
" NERDTree configuration {{{
map <F2> :NERDTreeToggle<cr>
let NERDTreeChDirMode =1
"Show bookmark
let NERDTreeShowBookmarks =1
"Ingnore filetypes
let NERDTreeIgnore =['\\\\~\$', '\\\\.pyc\$', '\\\\.swp$']
"window size
let NERDTreeWinSize =25
" }}}
" Autopep8 configuration {{{
let g:autopep8_disable_show_diff=1
" }}}
" User maps {{{
" Escape {{{
inoremap jk <Esc>
" }}}
" Switch window {{{
nnoremap nw <C-w><C-w>
" }}}
" Close current window {{{
nnoremap ww <C-W>q
" }}}
" gf to new tab {{{
nnoremap Gf <C-w>gf
" }}}
" Omni completion {{{
imap <A-j> <C-x><C-o>
" }}}
" Copy and paste a paragraph {{{
noremap cp yap<S-}>p
" }}}
" Align current paragraph {{{
noremap ;a =ip
" }}}
" Toggle paste mode {{{
set pastetoggle=;z
" }}}
" Apply macro {{{
" use qq to recode, q to stop and Q to apply
nnoremap Q @q
vnoremap Q :norm @q<cr>
" }}}
" Copy to clipboard {{{
vnoremap ;x "*y
" }}}
" Paste from clopboard {{{
nmap ;p "*p
" }}}
" Vim-easy-align maps {{{
xmap ga <Plug>(EasyAlign)
nmap ga <Plug>(EasyAlign)
" }}}
" F5 run python {{{
au FileType python map <buffer>  <F5> :Autopep8<cr> :w<cr> :call RunPythonOrC()<cr>
au FileType cpp map <buffer>  <F5> :w<cr> :call RunPythonOrC()<cr>
" }}}
" F4 for command python
au FileType python map <buffer> <F4> <leader>ci <cr>
" }}}
" Auto load vimrc when write {{{
augroup myvimrc
  au!
  au BufWritePost .vimrc,_vimrc,vimrc,.gvimrc,_gvimrc,gvimrc so \$MYVIMRC | if has('gui_runing') | so \$MYGVIMRC | endif
augroup END
" }}}
EOF
# Auto install vim plugin
if ! [ -f ~/.vim/vimrc ]; then
  echo "$VIMC" > ~/.vim/vimrc   
  echo -e "${GREEN}Install${NC}: VIM plugin..."
  sleep 3
  vim +PlugInstall +qall
fi

Vimrc截图

安装好后的vimrc如下图


vimrc.png

一个python测试文件

# -*- coding: utf-8 -*-
def capitalize(name):
    return name.capitalize()


def showlist(lists):
    for elem in lists:
        print("%s" % elem)


lis = ["VAN Abel", "John SmiTH"]
showlist(lis)
for name in lis:
    print("Hello %s" % capitalize(name))

按F5, 运行效果如下:


Python测试

注意事项

由于默认是全新安装, 故会检测相应的文件是否存在, 如果无效, 请将涉及的文件(~/.minttyrc,~/.bash_aliases,~/.vim/vimrc)移动到备份。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容