在ubuntu下使用Vim学习C++

  之前就买过java,c++的书,可是由于懒惰,一直没看,丢在那里5年了。(以上废话)。

  现在linux下还没有好的C++ IDE。网络上的朋友都推荐eclipse和 code::block。粗略的看了下code::block,建工程,管理工程,功能很多,准备以后学习下。 学习C++,目前还是用Vim比较好,轻量。各种丰富的插件支持。

  开发环境:

  系统:ubuntu 14.04LTS。

  工具:Vim7.4

  编译,链接,运行:g++

  现在贴上Vim的配置:(这是这篇随笔的主要内容,也是为了个人保存配置。层次低,希望看官不要笑话。)

  

set nocompatible              " be iMproved
filetype off                  " required!

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" let Vundle manage Vundle
" required! 
Bundle 'gmarik/vundle'

" My bundles here:
"
" original repos on GitHub
Plugin 'SirVer/ultisnips'
Plugin 'honza/vim-snippets'

Bundle 'tpope/vim-fugitive'
Bundle 'Lokaltog/vim-easymotion'
Bundle 'rstacruz/sparkup', {'rtp': 'vim/'}
Bundle 'tpope/vim-rails.git'
" vim-scripts repos
Bundle 'L9'
Bundle 'FuzzyFinder'
" non-GitHub repos
Bundle 'git://git.wincent.com/command-t.git'
Bundle 'https://github.com/scrooloose/nerdtree'
Bundle 'https://github.com/majutsushi/tagbar'
Bundle 'https://github.com/tpope/vim-commentary'
Bundle 'https://github.com/scrooloose/syntastic'
Bundle 'https://github.com/altercation/vim-colors-solarized'
Bundle 'https://github.com/kien/ctrlp.vim'
Bundle 'https://github.com/Raimondi/delimitMate'
Bundle 'https://github.com/tpope/vim-surround'
Bundle 'https://github.com/vim-scripts/bufexplorer.zip'
Bundle 'https://github.com/Valloric/YouCompleteMe' 
Bundle 'https://github.com/scrooloose/nerdcommenter'


Plugin 'exvim/ex-tagbar' 

" Git repos on your local machine (i.e. when working on your own plugin)
" Bundle 'file:///Users/gmarik/path/to/plugin'
" ...

filetype plugin indent on     " required!
"
" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or wiki for FAQ
" NOTE: comments after Bundle commands are not allowed.



""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" 
" GVIM自身的设置
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
language messages zh_CN.utf-8   " 解决consle输出乱码
syntax enable
set background=dark
colorscheme solarized
"colorscheme blue              " 灰褐色主题
"colorscheme delek
"colorscheme evening
"colorscheme murphy
"colorscheme slate
"colorscheme darkblue
"colorscheme desert
"colorscheme koehler
"colorscheme pablo
"colorscheme anotherdark
"colorscheme elflord
"colorscheme asmanian2
"colorscheme Dark
"colorscheme peachpuff
"colorscheme torte
"colorscheme bensday
"colorscheme zellner
"colorscheme morning
"colorscheme ron
"colorscheme corn
"colorscheme shine

set guioptions-=T        " 隐躲工具栏
"set guifont=DejaVu\ Sans\ mono\ 11        " 字体 && 字号
if has("gui_gtk2")
    set guifont=Bitstream\ Vera\ Sans\ Mono\ 12,Fixed\ 12
    set guifontwide=Microsoft\ Yahei\ 12,WenQuanYi\ Zen\ Hei\ 12
endif 


set noerrorbells        " 封闭错误提示音
set nobackup            " 不要备份文件
set linespace=0            " 字符间插进的像素行数目
set shortmess=atI        " 启动的时候不显示那个援助索马里儿童的提示
set novisualbell        " 不要闪烁 
set scrolloff=3            " 光标移动到buffer的顶部和底部时保持3行间隔
set mouse=a             " 可以在buffer的任何地方 ->
set selection=exclusive         " 使用鼠标(类似office中 ->
set selectmode=mouse,key        " 在工作区双击鼠标定位)
set cursorline                  " 突出显示当前行
set nu   " 显示行号
set whichwrap+=<,>,h,l        " 答应backspace和光标键跨越行边界 
set completeopt=longest,menu    "按Ctrl+N进行代码补全

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" 
" 文本格式和排版 
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" 
set list                        " 显示Tab符,->
set listchars=tab:\|\ ,         " 使用一高亮竖线代替
set tabstop=4            " 制表符为4
set autoindent            " 自动对齐(继续前一行的缩进方式)
set smartindent            " 智能自动缩进(以c程序的方式)
set softtabstop=4 
set shiftwidth=4        " 换行时行间交错使用4个空格
set noexpandtab            " 不要用空格代替制表符
set cindent            " 使用C样式的缩进
set smarttab            " 在行和段开始处使用制表符
set nowrap            " 不要换行显示一行 

 
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 状态行(命令行)的显示
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set cmdheight=2             " 命令行(在状态行下)的高度,默以为1,这里是2
set ruler                 " 右下角显示光标位置的状态行
set laststatus=2         " 开启状态栏信息 
set wildmenu             " 增强模式中的命令行自动完成操纵 


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 文件相关
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set fenc=utf-8
set encoding=utf-8        " 设置vim的工作编码为utf-8,假如源文件不是此编码,vim会进行转换后显示
set fileencoding=utf-8        " 让vim新建文件和保存文件使用utf-8编码
set fileencodings=utf-8,gbk,cp936,latin-1
filetype on                     " 侦测文件类型
filetype indent on                 " 针对不同的文件类型采用不同的缩进格式
filetype plugin on                 " 针对不同的文件类型加载对应的插件

syntax on                     " 语法高亮
filetype plugin indent on    " 启用自动补全


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 查找
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set hlsearch                 " 开启高亮显示结果
set nowrapscan               " 搜索到文件两端时不重新搜索
set incsearch                " 开启实时搜索功能

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 实用功能
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" 设置NerdTree
map <F3> :NERDTreeMirror<CR>
map <F3> :NERDTreeToggle<CR>


"clang-complete
let g:clang_complete_copen=1
let g:clang_periodic_quickfix=1
let g:clang_snippets=1
let g:clang_close_preview=1
let g:clang_use_library=1"let g:clang_user_options='-stdlib=libc++ -std=c++11 -I /usr/include/c++/4.9.2'
let g:clang_user_options='-fexceptions -I /usr/include -I /usr/local/include' let g:neocomplcache_enable_at_startup
= 1 """"""""""""YCM"""""""""""""""""""" let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/.ycm_extra_conf.py' let g:ycm_collect_identifiers_from_tags_files = 1 let g:ycm_seed_identifiers_with_syntax = 1 let g:ycm_confirm_extra_conf = 0 let g:ycm_cache_omnifunc=0 let g:ycm_complete_in_comments=1 let g:ycm_min_num_of_chars_for_completion=1 let g:ycm_use_ultisnips_completer=0 let g:ycm_key_invoke_completion = '<S-Space>' "设置跳转的快捷键,可以跳转到definition和declaration nnoremap <leader>gc :YcmCompleter GoToDeclaration<CR> nnoremap <leader>gf :YcmCompleter GoToDefinition<CR> nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR> "nmap <F4> :YcmDiags<CR> """""""""""""NERDCommenter"""""""""""""""""" let mapleader = "," " NERD_commenter.vim " http://www.vim.org/scripts/script.php?script_id=1218 " Toggle单行注释/“性感”注释/注释到行尾/取消注释 map <leader>cc ,c<space> map <leader>cs ,cs map <leader>c$ ,c$ map <leader>cu ,cu " UltiSnips 的 tab 键与 YCM 冲突,重新设定 let g:UltiSnipsExpandTrigger="<leader><tab>" let g:UltiSnipsJumpForwardTrigger="<leader><tab>" let g:UltiSnipsJumpBackwardTrigger="<leader><s-tab>" """"""""""""""""""tagbar"""""""""""""""""""""""""""" nmap <F4> :TagbarToggle<CR> """""""""""""""""""编译和运行"""""""""""""""""""""""""""""""" " <F5> 编译和运行C map <F5> :call CompileRunGcc()<CR> func! CompileRunGcc() exec "w" exec "!gcc % -o %<" exec "! ./%<" endfunc "< F6> 编译和运行C++ map <F6> :call CompileRunGpp()<CR> func! CompileRunGpp() exec "w" exec "!g++ % -o %<" exec "! ./%<" endfunc """""""""""""""""""代码块"""""""""""""""""""""""""""""""" " Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe. let g:UltiSnipsSnippetsDir = '~/.vim/bundle/vim-snippets/UltiSnips' let g:UltiSnipsSnippetDirectories = ['UltiSnips'] let g:UltiSnipsExpandTrigger="<c-j>" let g:UltiSnipsJumpForwardTrigger="<c-b>" let g:UltiSnipsJumpBackwardTrigger="<c-z>" "let g:UltiSnipsEditSplit="vertical"

  ycm的配置文件: 

# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>

import os
import ycm_core

# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
# You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM
# source code needs it.
'-DUSE_CLANG_COMPLETER',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++11',
'-stdlib=libc++',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-isystem',
'../BoostParts',
'-isystem',
# This path will only work on OS X, but extra paths that don't exist are not
# harmful
'/System/Library/Frameworks/Python.framework/Headers',
'-isystem',
'../llvm/include',
'-isystem',
'../llvm/tools/clang/include',
'-I',
'.',
'-I',
'./ClangCompleter',
'-isystem',
'./tests/gmock/gtest',
'-isystem',
'./tests/gmock/gtest/include',
'-isystem',
'./tests/gmock',
'-isystem',
'./tests/gmock/include',
'-isystem',
'/usr/include',
'-isystem',
'/usr/include/c++/4.9.2',
]


# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# You can get CMake to generate this file for you by adding:
#   set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''

if os.path.exists( compilation_database_folder ):
  database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
  database = None

SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]

def DirectoryOfThisScript():
  return os.path.dirname( os.path.abspath( __file__ ) )


def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
  if not working_directory:
    return list( flags )
  new_flags = []
  make_next_absolute = False
  path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
  for flag in flags:
    new_flag = flag

    if make_next_absolute:
      make_next_absolute = False
      if not flag.startswith( '/' ):
        new_flag = os.path.join( working_directory, flag )

    for path_flag in path_flags:
      if flag == path_flag:
        make_next_absolute = True
        break

      if flag.startswith( path_flag ):
        path = flag[ len( path_flag ): ]
        new_flag = path_flag + os.path.join( working_directory, path )
        break

    if new_flag:
      new_flags.append( new_flag )
  return new_flags


def IsHeaderFile( filename ):
  extension = os.path.splitext( filename )[ 1 ]
  return extension in [ '.h', '.hxx', '.hpp', '.hh' ]


def GetCompilationInfoForFile( filename ):
  # The compilation_commands.json file generated by CMake does not have entries
  # for header files. So we do our best by asking the db for flags for a
  # corresponding source file, if any. If one exists, the flags for that file
  # should be good enough.
  if IsHeaderFile( filename ):
    basename = os.path.splitext( filename )[ 0 ]
    for extension in SOURCE_EXTENSIONS:
      replacement_file = basename + extension
      if os.path.exists( replacement_file ):
        compilation_info = database.GetCompilationInfoForFile(
          replacement_file )
        if compilation_info.compiler_flags_:
          return compilation_info
    return None
  return database.GetCompilationInfoForFile( filename )


def FlagsForFile( filename, **kwargs ):
  if database:
    # Bear in mind that compilation_info.compiler_flags_ does NOT return a
    # python list, but a "list-like" StringVec object
    compilation_info = GetCompilationInfoForFile( filename )
    if not compilation_info:
      return None

    final_flags = MakeRelativePathsInFlagsAbsolute(
      compilation_info.compiler_flags_,
      compilation_info.compiler_working_dir_ )

    # NOTE: This is just for YouCompleteMe; it's highly likely that your project
    # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
    # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
#    try:
#      final_flags.remove( '-stdlib=libc++' )
#    except ValueError:
#      pass
  else:
    relative_to = DirectoryOfThisScript()
    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )

  return {
    'flags': final_flags,
    'do_cache': True
  }

 

  开发中,代码补全和快速插入代码块,这两个是必用的。谁也不想把时间花费在敲一些垃圾代码上。配置中使用YCM来补全代码,

UltiSnips来快速插入代码块。以后插件会慢慢加入。
  人人都说Vim是神器。可我用起来非常艰难。经常装了个插件各种问题,处理插件的问题,耗费大量的时间。我经常在怀疑是否自己选对了编辑器。我喜欢Vim的快捷键来编辑代码。可由于年代久远,各种插件多而不全。我觉得Vim只适合用于学习C++的开发,让它来建立工程什么的。。。。还是不要想了。老老实实用Eclipse和CB了。
  插入一段代码,来开始我的C++之路:

开发路上,你我同行。。。
posted @ 2015-04-06 21:16  xclidongbo  阅读(2667)  评论(0编辑  收藏  举报