美文网首页linux.toolsvin
一键完成Python开发环境搭建: Cygwin+Vim

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

作者: 破旧的大卡车 | 来源:发表于2017-11-03 20:39 被阅读2782次

    准备工作

    首先安装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)移动到备份。

    相关文章

      网友评论

        本文标题:一键完成Python开发环境搭建: Cygwin+Vim

        本文链接:https://www.haomeiwen.com/subject/qphopxtx.html