[手册] terminal 工作环境配置

vim 篇

~/.vimrc 配置

set nocompatible              " 去除VI一致性,必须
set backspace=indent,eol,start  " 允许退行
set fileformat=unix            " 会显示 dos 下的 \r\n 为 ^M
set shiftwidth=4 | set expandtab " 把 tab 键的输入变成空格,并且是 4 个
syntax on                          " 开启语法高亮

" 配置 vundle 开始
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'Valloric/YouCompleteMe'
Plugin 'dpelle/vim-LanguageTool'
Plugin 'scrooloose/nerdtree'
Plugin 'SirVer/ultisnips'
Plugin 'honza/vim-snippets'
Plugin 'posva/vim-vue'
call vundle#end()
filetype plugin indent on    " 自动检测文件类型并加载插件
" 配置 vundle 结束

au BufRead,BufNewFile *.vue set filetype=vue

" 配置格式化 clang-format 开始 
map <C-K> :pyf ~/.vim/prebuild/clang/llvm/share/clang/clang-format.py<cr>
" 配置格式化 clang-format 结束

" 配置补全 you_complete_me 开始
let g:ycm_global_ycm_extra_conf = '~/.vim/.ycm_extra_conf.py'  " 启用默认配置
let g:ycm_confirm_extra_conf = 0  " 关闭重复打开提醒
let g:ycm_python_binary_path = 'python3'  " 使用 python3 作为 python interpreter 
nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR>
" 配置补全 you_complete_me 结束
" Trigger configuration. Do not use <tab> if you use
" https://github.com/Valloric/YouCompleteMe.
let g:UltiSnipsExpandTrigger="<c-h>"
let g:UltiSnipsEditSplit="vertical"

set backupdir-=.
set backupdir^=~/tmp,/tmp

安装 vundle,启动插件安装

git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
vim +PluginInstall +qall

安装 you_complete_me

sudo apt-get install build-essential cmake3
sudo apt-get install python-dev python3-dev
cd ~/.vim/bundle/YouCompleteMe
git submodule update --init --recursive
./install.py --clang-completer

安装 clang-format

mkdir -p ~/.vim/prebuild/clang
curl http://releases.llvm.org/5.0.1/clang+llvm-5.0.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz -o ~/.vim/prebuild/clang/llvm.tar.xz # 或者到 http://releases.llvm.org/download.html 下载对应版本 prebuilds
pushd ~/.vim/prebuild/clang
mkdir llvm
tar -xvf llvm.tar.xz -C llvm --strip-components 1
echo "export PATH=~/.vim/prebuild/clang/llvm/bin:\$PATH" >> ~/.bash_profile
source ~/.bash_profile
popd

安装 vim 用的 py

sudo apt-get install vim-nox-py2
sudo update-alternatives --config vim # 更换vim

安装 autojump

sudo apt-get install autojump
echo "source /usr/share/autojump/autojump.sh" >> ~/.bash_profile

常用 vim 操作

  • normal 模式下输入 Q 可以连续输入命令
  • set paste 设置外部粘贴时不乱格式化

ycm 篇

全局 ycm 配置 ~/.vim/.ycm_extra_conf.py

# 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
import glob
import subprocess 

def generate(conditions):
  result = []
  for item in conditions:
    folder = item["dir"]
    filters = item["filters"]
    for filter in filters:
       value = subprocess.check_output(["find", folder, "-name", filter]).strip()
       if len(value) > 0 :
          value = value.split("\n")
          for entry in value:
             result.append("-I"+entry.strip())
  return result

# 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',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
'-std=c++14',
# ...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++",
'-I', ".",
] + [
'-I/usr/local/opt/openssl/include',
] + generate([
{'dir': os.path.dirname(os.path.abspath(__file__)), 'filters': ['include', 'src', 'impl']},
{'dir': os.getcwd(), 'filters': ['include', 'src', 'impl']}, 
])  #可以进行拓展,包含指定目录下递归搜索的目录


# 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 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 not database:
    return {
      'flags': flags,
      'include_paths_relative_to_dir': DirectoryOfThisScript()
    }

  compilation_info = GetCompilationInfoForFile( filename )
  if not compilation_info:
    return None

  # Bear in mind that compilation_info.compiler_flags_ does NOT return a
  # python list, but a "list-like" StringVec object.
  final_flags = list( compilation_info.compiler_flags_ )

  # 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

  return {
    'flags': final_flags,
    'include_paths_relative_to_dir': compilation_info.compiler_working_dir_
  }

zsh 篇

安装 zsh

sudo apt-get install zsh
chsh zsh

使用 oh-my-zsh

sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

配置 promt

vim ~/.oh-my-zsh/themes/robbyrussell.zsh-theme # 修改 %c 为 %~

安装 zsh-autosuggestions

tmux 篇

配置 ~/.tmux.conf

set-window-option -g mode-keys vi
bind-key -T copy-mode-vi 'v' send-keys -X begin-selection
bind-key -T copy-mode-vi 'y' send-keys -X copy-selection
# use following key binding before tmux 2.6
# bind-key -t vi-copy 'v' begin-selection   
# bind-key -t vi-copy 'y' copy-selection

# set status bar
set -g status-bg black
set -g status-fg white
set -g status-right '#[fg=yellow]%a|%b%e|%H:%M:%S|#H'
set -g status-interval 1
set -g status-justify centre

# highlight active window
setw -g window-status-current-bg red
setw -g automatic-rename on

# mouse options
set -g mouse on

# Copy tmux paste buffer to CLIPBOARD
bind y run-shell "tmux show-buffer | xclip -i -selection clipboard"

set -g @plugin 'tmux-plugins/tpm' 
set -g @plugin 'tmux-plugins/tmux-sensible'
set -g @plugin 'tmux-plugins/tmux-resurrect'
run -b '~/.tmux/plugins/tpm/tpm'

常用操作,下列均要带 ctl+b 为前缀
c 创建窗口, & 关闭窗口,p 前一个窗口,n 下一个窗口

tmux 管理插件

git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
tmux source ~/.tmux.conf

ctrl-b + I 进行安装

git 篇

formatter

#!/usr/bin/env python 

import os
import subprocess
import argparse

def error(msg=""):
  print "error: %s" % msg
  exit(1)

def get_root_path(anchor=".clang-format"):
  path = os.path.abspath(__file__)
  while True:
    path = os.path.dirname(path)
    if (os.path.exists(path + "/" + anchor)):
      return path
    if (path == "/"):
      error("%s not found" % anchor)

def run():
  file_types = ["*.cpp", "*.c", "*.hpp", "*.h"]
  sub_folders = ["src", "include", "test"]
  format_file = ".clang-format"
  root = get_root_path(format_file)
  print "format in [%s] with [%s]" % (", ".join(sub_folders), ", ".join(file_types))
  for folder in sub_folders:
    for file_type in file_types:
      cmd = "find %s/%s -name %s | xargs clang-format -i 2>/dev/null" %(
              root, folder, file_type)
      os.system(cmd)

def check():
  file_types = ["*.cpp", "*.c", "*.hpp", "*.h"]
  sub_folders = ["src", "include", "test"]
  format_file = ".clang-format"
  root = get_root_path(format_file)
  print "check in [%s] with [%s]" % (", ".join(sub_folders), ", ".join(file_types))
  for folder in sub_folders:
    for file_type in file_types:
      try:
         cmd = "find %s/%s -name %s | xargs clang-format -output-replacements-xml | grep -c '<replacement '" %(
              root, folder, file_type)
         result = subprocess.check_output(cmd, shell=True)
         error("not all %s in %s/%s is formatted" % (file_type, root, folder))
      except Exception, e:
         continue

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

推荐阅读更多精彩内容