Related
I thought I'd post these code snippets for others who may find themselves trying to make ADODB calls from a PowerShell script. I inherited this convoluted mess, and had to make some changes to it.
We're using PlanetPress as part of a Docuware Document Imaging system. A PP workflow called a vbscript which in turn launched a PowerShell script. The PowerShell did the work to make two database queries. One was an update, and the other was a select. I'm not that great with PowerShell, and there may be a cmdlet out there to simplify this. But the code was creating ADODB.Connection, ADODB.Command, and ADODB.Resultset objects directly. The problem is there are no good resources for the syntax required to use these objects. Hopefully these code snippets will help some poor soul in a similar situation.
Using ADODB.Command:
$oConnection = New-Object -comobject "ADODB.Connection"
# Use correct ODBC driver
if ([Environment]::Is64BitProcess) {
$oConnection.Open("DSN=DW64")
} else {
$oConnection.Open("DSN=DW")
}
if ($oConnection.State -eq $adStateClosed) {
Write-Output "Connection not established"
Write-Output $oConnection
}
$UpdQuery = "Update dwdata.Purchasing `
set Status='Processing' `
WHERE DOCUMENT_TYPE = 'Check' `
AND STATUS in ('Approved')"
$ra=-1
$oCommand = New-Object -comobject "ADODB.Command"
$oCommand.ActiveConnection = $oConnection
$oCommand.CommandText = $UpdQuery
$oCommand.CommandType = $adCmdText
$rs=$oCommand.Execute([ref]$ra)
Write-Output ("Count of Row[s] updated: " + $ra)
Using ADODB.Resultset:
$oRS = New-Object -comobject "ADODB.Recordset"
$query = "SELECT DWDOCID, DOCUMENT_DATE, CHECK_NUMBER, PAYEE_NAME, CHECK_AMOUNT, STATUS `
FROM dwdata.Purchasing `
WHERE DOCUMENT_TYPE = 'Check' `
AND STATUS = 'Processing' `
ORDER BY CHECK_NUMBER;"
# $oConnection object created in ADODB.Command snippet above
$oConnection.CursorLocation = $adUseClient
$oRS.Open($query, $oConnection, $adOpenStatic, $adLockOptimistic)
$reccount = "Number of queried records: " + $oRS.RecordCount
write-output $reccount
If (-not ($oRS.EOF)) {
# Move to the first record returned, and loop
$oRS.MoveFirst()
$reccount = "Number of loop records: " + $oRS.RecordCount
write-output $reccount
do {
$outString = '"' + $oRS.Fields.Item("DOCUMENT_DATE").Value.ToString("MM/dd/yyyy") + '"' + ','
$outString += '"' + $oRS.Fields.Item("CHECK_NUMBER").Value + '"' + ','
$outString += '"' + $oRS.Fields.Item("PAYEE_NAME").Value + '"' + ','
$outString += '"' + $oRS.Fields.Item("CHECK_AMOUNT").Value + '"' + ','
$outString | Out-File $bankfile -Append -Encoding ASCII
$oRS.MoveNext()
} until
($oRS.EOF -eq $True)
} Else{
Write-Output "No records returned from database query."
}
$oRS.Close()
$oConnection.Close()
Some of this code is ugly (using do instead of while), but the idea is to help you get the right syntax for $oCommand.Execute and how to get a record count from the Recordset. $oRS.MoveFirst() needs to be called before the record count is available.
ss64.com and other resources usually give vbscript snippets. In vbscript variables are not preceeded with a $, and when or if you need to use parenthesis is unclear. This code does run and work.
I'm using Vim 8.1 and NeoVim 0.4.3. When I'm editing Django template html files neither could correctly detect the file type and hence no color or syntax highlighting at all. I'm pretty sure filetype on because this is the output:
filetype dection:ON plugin:ON indent:ON
I followed this issue and forcing the filetype to htmldjango (at the bottom of the .vimrc file I post down below) did work, but I don't think it's ideal. Could anybody please help me with this?
My .vimrc:
" macOS version
set rtp+=/usr/local/opt/fzf
call plug#begin('~/.vim/plugged')
Plug 'junegunn/vim-easy-align'
" tmux
Plug 'christoomey/vim-tmux-navigator'
Plug 'tmux-plugins/vim-tmux'
Plug 'benmills/vimux'
" Coc
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'tpope/vim-fugitive'
" fzf
Plug '/usr/local/opt/fzf'
Plug 'junegunn/fzf.vim'
" Ack search tool
Plug 'mileszs/ack.vim'
" Indentation
Plug 'Yggdroot/indentLine'
" Python autoformat
Plug 'psf/black'
" Django HTML
Plug 'tweekmonster/django-plus.vim'
" comment
Plug 'scrooloose/nerdcommenter'
Plug 'tpope/vim-sensible'
Plug 'tpope/vim-sleuth'
" gitgutter
Plug 'airblade/vim-gitgutter'
" emmet
Plug 'mattn/emmet-vim'
" Ale
Plug 'w0rp/ale'
" lightline
Plug 'itchyny/lightline.vim'
" Eslint
Plug 'vim-syntastic/syntastic'
" EcmaScript and JSX
Plug 'pangloss/vim-javascript'
Plug 'maxmellon/vim-jsx-pretty'
" TypeScript
Plug 'leafgarland/typescript-vim'
Plug 'Quramy/tsuquyomi'
Plug 'Shougo/vimproc.vim'
" Elm
Plug 'elmcast/elm-vim'
" Go format
Plug 'fatih/vim-go'
" NERDTree
Plug 'scrooloose/nerdtree' ", {'on': 'NERDTreeToggle'}
Plug 'Xuyuanp/nerdtree-git-plugin'
" Colorscheme
Plug 'morhetz/gruvbox'
Plug 'octol/vim-cpp-enhanced-highlight'
Plug 'nanotech/jellybeans.vim'
" markdown
Plug 'godlygeek/tabular'
Plug 'plasticboy/vim-markdown'
Plug 'prettier/vim-prettier', {
\ 'do': 'yarn install',
\ 'branch': 'release/1.x',
\ 'for': [
\ 'javascript',
\ 'typescript',
\ 'css',
\ 'less',
\ 'scss',
\ 'json',
\ 'graphql',
\ 'markdown',
\ 'vue',
\ 'lua',
\ 'swift' ] }
" plugin from http://vim-scripts.org/vim/scripts.html
" Git plugin not hosted on GitHub
Plug 'git://git.wincent.com/command-t.git'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
Plug 'rstacruz/sparkup', {'rtp': 'vim/'}
" All of your Plugins must be added before the following line
call plug#end() " required
" To ignore plugin indent changes, instead use:
" Put your non-Plugin stuff after this line
set mouse=a
set hidden
set cmdheight=2
set nobackup
set nowritebackup
" don't give |ins-completion-menu| messages.
set shortmess+=c
" always show signcolumns
set signcolumn=yes
" Use tab for trigger completion with characters ahead and navigate.
" Use command ':verbose imap <tab>' to make sure tab is not mapped by other plugin.
" use <tab> for trigger completion and navigate to the next complete item
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~ '\s'
endfunction
inoremap <silent><expr> <TAB>
\ pumvisible() ? "\<C-n>" :
\ <SID>check_back_space() ? "\<TAB>" :
\ coc#refresh()
inoremap <expr> <TAB> pumvisible() ? "\<C-n>" : "\<TAB>"
inoremap <expr> <S-TAB> pumvisible() ? "\<C-p>" : "\<S-TAB>"
augroup mygroup
autocmd!
" Setup formatexpr specified filetype(s).
autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
" Update signature help on jump placeholder
autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end
" Use K to show documentation in preview window
nnoremap <silent> K :call <SID>show_documentation()<CR>
function! s:show_documentation()
if (index(['vim','help'], &filetype) >= 0)
execute 'h '.expand('<cword>')
else
call CocAction('doHover')
endif
endfunction
set updatetime=100
set timeout timeoutlen=3000 ttimeoutlen=100
set number
set tabstop=4
set smarttab
set softtabstop=4
set expandtab
set textwidth=80
set colorcolumn=81
set wrapmargin=0
set formatoptions=croqlt12
set wrap
set shiftwidth=2
set autoindent
set smartindent
set showcmd
set cursorline
set wildmenu
set lazyredraw
set showmatch
set incsearch
set hlsearch
set foldenable
set cindent
set shell=/bin/bash
set viminfo='100,<1000,s100,h
colorscheme gruvbox
set background=dark
let g:gruvbox_contrast_dark='hard'
set foldlevelstart=99
set foldnestmax=10
nnoremap <space> za
" new line without insert mode
nmap <S-Enter> O<Esc>j
nmap <CR> o<Esc>k
set foldmethod=indent
inoremap ( ()<Esc>i
inoremap (<CR> (<CR>)<C-o>O
inoremap [ []<Esc>i
inoremap [<CR> [<CR>]<C-o>O
"inoremap < <><Esc>i
inoremap { {}<Esc>i
inoremap ` ``<Esc>i
inoremap {<CR> {<CR>}<C-o>O
inoremap `<CR> `<CR>`<C-o>O
"inoremap <C-Return> <CR><CR><C-o>k<Tab>
inoremap " ""<Esc>i
inoremap ' ''<Esc>i
" navigation
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>
set splitbelow
set splitright
" fugitive
autocmd QuickFixCmdPost *grep* cwindow
set diffopt+=vertical
" Vimux
" Prompt for a command to run
map <Leader>vp :VimuxPromptCommand<CR>
" Run last command executed by VimuxRunCommand
map <Leader>vl :VimuxRunLastCommand<CR>
" Coc config
set completeopt+=preview
set completeopt+=menuone
set completeopt+=noselect
autocmd CursorHold * silent call CocActionAsync('highlight')
autocmd FileType json syntax match Comment +\/\/.\+$+
let g:ale_linters = {
\ 'sh': ['language_server'],
\ }
autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
" gitgutter
let g:gitgutter_max_signs = 999
" NERD Commenter
" Add spaces after comment delimiters by default
let g:NERDSpaceDelims = 1
" Use compact syntax for prettified multi-line comments
let g:NERDCompactSexyComs = 1
" Align line-wise comment delimiters flush left instead of following code indentation
let g:NERDDefaultAlign = 'left'
" Set a language to use its alternate delimiters by default
let g:NERDAltDelims_java = 1
" Add your own custom formats or override the defaults
let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }
" Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDCommentEmptyLines = 1
" Enable trimming of trailing whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1
" Enable NERDCommenterToggle to check all selected lines is commented or not
let g:NERDToggleCheckAllLines = 1
function! Formatonsave()
let l:formatdiff = 1
pyf ~/clang-format.py
endfunction
" lightline colorscheme
function! CocCurrentFunction()
return get(b:, 'coc_current_function', '')
endfunction
let g:lightline = {
\ 'colorscheme': 'one',
\ 'active': {
\ 'left': [ [ 'mode', 'paste' ],
\ [ 'cocstatus', 'currentfunction', 'readonly', 'filename', 'modified' ] ]
\ },
\ 'component_function': {
\ 'cocstatus': 'coc#status',
\ 'currentfunction': 'CocCurrentFunction'
\ },
\ }
" fzf search
" Default fzf layout
" - down / up / left / right
let g:fzf_layout = { 'down': '~30%' }
" In Neovim, you can set up fzf window using a Vim command
" let g:fzf_layout = { 'window': 'enew' }
" let g:fzf_layout = { 'window': '-tabnew' }
" let g:fzf_layout = { 'window': '10split' }
let g:fzf_action = {
\ 'ctrl-t': 'tab split',
\ 'ctrl-i': 'split',
\ 'ctrl-s': 'vsplit' }
autocmd! FileType fzf set laststatus=0 noshowmode noruler
\| autocmd BufLeave <buffer> set laststatus=2 showmode ruler
command! -bang -nargs=* Rg
\ call fzf#vim#grep(
\ 'rg --hidden --column --line-number --no-heading --color=always --smart-case '.shellescape(<q-args>), 1,
\ <bang>0 ? fzf#vim#with_preview('up:60%')
\ : fzf#vim#with_preview('right:50%:hidden', '?'),
\ <bang>0)
nnoremap <C-g> :Rg<Cr>
" Global line completion (not just open buffers. ripgrep required.)
inoremap <expr> <c-x><c-l> fzf#vim#complete(fzf#wrap({
\ 'prefix': '^.*$',
\ 'source': 'rg -n ^ --color always',
\ 'options': '--ansi --delimiter : --nth 3..',
\ 'reducer': { lines -> join(split(lines[0], ':\zs')[2:], '') }}))
" [Buffers] Jump to the existing window if possible
" let g:fzf_buffers_jump = 1
nnoremap <silent> <Leader>s :call fzf#run({
\ 'down': '40%',
\ 'sink': 'botright split' })<CR>
" Open files in vertical horizontal split
nnoremap <silent> <Leader>v :call fzf#run({
\ 'right': winwidth('.') / 2,
\ 'sink': 'vertical botright split' })<CR>
let g:ackprg = 'rg --vimgrep --no-heading'
cnoreabbrev ag Ack
cnoreabbrev aG Ack
cnoreabbrev Ag Ack
cnoreabbrev AG Ack
let g:vim_jsx_pretty_colorful_config = 1
let g:typescript_indent_disable = 0
let g:typescript_ignore_browserwords = 0
autocmd BufWritePre *.h,*.cc,*.c,*.cpp call Formatonsave()
map <C-K> :pyf ~/clang-format.py<cr>
imap <C-K> <c-o>:pyf ~/clang-format.py<cr>
let g:autopep8_aggressive=1
let g:autopep8_disable_show_diff=1
let g:autopep8_on_save=1
let g:autopep8_max_line_length=120
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%{coc#status()}
set statusline+=%*
let g:syntastic_python_checkers = ['pylint']
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 = 1
let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_exe = 'npm run lint --'
let g:elm_syntastic_show_warnings = 1
" NERDTree
let g:NERDTreeWinSize = 27
" autocmd vimenter * NERDTree
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
map <C-n> :NERDTreeToggle<CR>
" start vim/nvim with $vim or $nvim, NOT $vim . or $nvim .
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | endif
" Please customize this:
let g:NERDTreeIndicatorMapCustom = {
\ "Modified" : "✹",
\ "Staged" : "✚",
\ "Untracked" : "✭",
\ "Renamed" : "➜",
\ "Unmerged" : "═",
\ "Deleted" : "✖",
\ "Dirty" : "✗",
\ "Clean" : "✔︎",
\ 'Ignored' : '☒',
\ "Unknown" : "?"
\ }
let g:prettier#config#print_width = 80
let g:prettier#config#html_whitespace_sensitivity = 'css'
let g:prettier#config#trailing_comma = 'all'
let g:prettier#config#semi = 'true'
let g:prettier#exec_cmd_async=1
let g:prettier#autoformat = 0
autocmd BufWritePre *.js,*.jsx,*.mjs,*.ts,*.tsx,*.css,*.less,*.scss,*.json,*.graphql,*.md,*.vue,*.yaml PrettierAsync
" Auto-format Go
autocmd BufWritePre *.go :call CocAction('runCommand', 'editor.action.organizeImport')
" Python Black
let g:black_linelength = 120
let g:black_skip_string_normalization = 1
" Auto run Black
autocmd BufWritePre *.py execute ':Black'
" djangohtml
au BufNewFile,BufRead *.html set filetype=htmldjango
Turned out it's the vim-prettier plugin causing the conflict. Disabling that plugin solved the issue.
First of all thank you in advance. I am trying to retrieve the following values from the JSON string below using PowerShell but am having issues.
ScheduleTitle,
Title,
Environment and Title
Resolution,
Width,
Height
JSON:
{"Id":"d52fb00e-8736-448c-a496-96db6bc2eb43","ScheduleId":"275726dc-09f2-4869-b1a0-54c71ef6a093","ScheduleTitle":"Resolution Testing","RunType":"RunNow","Timestamp":"2017-08-01T04:52:19.2039685","AutomationRunItems":[{"Id":"f7b731fb-cd96-4003-b95c-ef1594f1c86e","AutomationRunId":"d52fb00e-8736-448c-a496-96db6bc2eb43","Status":"Done","Case":{"Id":"c8a0b939-54ba-4b98-8ca9-101093aec26f","Title":"Resolution Test"},"Environment":{"Id":"e1783fb5-4001-45d0-9971-b49c31b374ab","Title":"Se Chrome"},"Keyframes":[{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00","Level":"Info","Status":"Connecting","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Connecting to Se Chrome: Selenium Grid (localhost:5559) on Chrome with size 1280x1024"},{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00.0000003","Level":"Info","Status":"Connected","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Connected"},{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00.0000015","Level":"Info","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Running"},{"Timestamp":"2017-08-01T04:52:03.0695642","Elapsed":"00:00:00.0003729","Level":"Trace","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:03.5713896","Elapsed":"00:00:00.5020154","Level":"Trace","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:03.5713896","Elapsed":"00:00:00.5021370","Level":"Trace","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:06.9793063","Elapsed":"00:00:03.9107459","Level":"Info","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Chrome was successfully started"},{"Timestamp":"2017-08-01T04:52:09.4641639","Elapsed":"00:00:06.3955903","Level":"Info","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Chrome loaded url https://dev.bamapplication.com/app/starke/npr/3BF6DA09C1/wizard"},{"Timestamp":"2017-08-01T04:52:09.7604882","Elapsed":"00:00:06.6925088","Level":"Trace","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:09.7604882","Elapsed":"00:00:06.6926471","Level":"Trace","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:10.4639126","Elapsed":"00:00:07.3954580","Level":"Warning","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Web screenshot is saved"},{"Timestamp":"2017-08-01T04:52:10.7666916","Elapsed":"00:00:07.6982198","Level":"Trace","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:10.7666916","Elapsed":"00:00:07.6983727","Level":"Trace","Status":"Running","BlockId":"161e621f-bb7a-4f42-a5f1-67e07d1432f4","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:11.7677637","Elapsed":"00:00:08.6992111","Level":"Info","Status":"Done","BlockId":"161e621f-bb7a-4f42-a5f1-67e07d1432f4","LogMessage":"Case is stopped."}],"Resolution":{"Width":1280,"Height":1024},"Elapsed":"00:00:08.6992111","CreatedAt":"2017-08-01T04:52:19.2039685","ModifiedAt":"2017-08-01T04:52:19.2039685"}],"ProjectId":"275726dc-09f2-4869-b1a0-54c71ef6a093","ExecutionTotalTime":"00:00:08.6992111","FailedCount":0,"PassedCount":0,"DoneCount":1,"CreatedAt":"2017-08-01T04:52:03.0685609"}
Code:
Param( [string]$result, [string]$rootPath )
try{
$json = $result
$parsed = $json | ConvertFrom-Json
$output= ''
foreach ($line in $parsed | Get-Member) {
Write-Output $parsed.$($line.Resolution).property1
Write-Output $parsed.$($line.Resolution).property2
$output += $parsed.$($line.Resolution).property1 + " " + $parsed.$($line.Resolution).property1
}
}
With your $parsed data you can extract all the information you need.
For example to extract the width:
echo $parsed.AutomationRunItems.Resolution.Width
should print: 1280
I think these are all the fields you need extracted. Note, since you did not specify the output precisely I have simply used comma-delimited strings:
$output= ''
$output = $output + $parsed.ScheduleTitle + ','
$output = $output + $parsed.AutomationRunItems.Case.Title + ','
$output = $output + $parsed.AutomationRunItems.Environment.Title + ','
$output = $output + $parsed.AutomationRunItems.Resolution.Width + ','
$output = $output + $parsed.AutomationRunItems.Resolution.Height
Should Print: Resolution Testing,Resolution Test,Se Chrome,1280,1024
I want to try out vim, but have a little trouble with the config file. I have installed gvim here C:\Program Files (x86)\Vim\vim73 and added a file called C:\Program Files (x86)\Vim\vim73\.vimrc, but when I try different configurations it does not seem to change anything.
I tried this one for example
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Maintainer: amix the lucky stiff
" http://amix.dk - amix#amix.dk
"
" Version: 3.6 - 25/08/10 14:40:30
"
" Blog_post:
" http://amix.dk/blog/post/19486#The-ultimate-vim-configuration-vimrc
" Syntax_highlighted:
" http://amix.dk/vim/vimrc.html
" Raw_version:
" http://amix.dk/vim/vimrc.txt
"
" How_to_Install_on_Unix:
" $ mkdir ~/.vim_runtime
" $ svn co svn://orangoo.com/vim ~/.vim_runtime
" $ cat ~/.vim_runtime/install.sh
" $ sh ~/.vim_runtime/install.sh <system>
" <sytem> can be `mac`, `linux` or `windows`
"
" How_to_Upgrade:
" $ svn update ~/.vim_runtime
"
" Sections:
" -> General
" -> VIM user interface
" -> Colors and Fonts
" -> Files and backups
" -> Text, tab and indent related
" -> Visual mode related
" -> Command mode related
" -> Moving around, tabs and buffers
" -> Statusline
" -> Parenthesis/bracket expanding
" -> General Abbrevs
" -> Editing mappings
"
" -> Cope
" -> Minibuffer plugin
" -> Omni complete functions
" -> Python section
" -> JavaScript section
"
"
" Plugins_Included:
" > minibufexpl.vim - http://www.vim.org/scripts/script.php?script_id=159
" Makes it easy to get an overview of buffers:
" info -> :e ~/.vim_runtime/plugin/minibufexpl.vim
"
" > bufexplorer - http://www.vim.org/scripts/script.php?script_id=42
" Makes it easy to switch between buffers:
" info -> :help bufExplorer
"
" > yankring.vim - http://www.vim.org/scripts/script.php?script_id=1234
" Emacs's killring, useful when using the clipboard:
" info -> :help yankring
"
" > surround.vim - http://www.vim.org/scripts/script.php?script_id=1697
" Makes it easy to work with surrounding text:
" info -> :help surround
"
" > snipMate.vim - http://www.vim.org/scripts/script.php?script_id=2540
" Snippets for many languages (similar to TextMate's):
" info -> :help snipMate
"
" > mru.vim - http://www.vim.org/scripts/script.php?script_id=521
" Plugin to manage Most Recently Used (MRU) files:
" info -> :e ~/.vim_runtime/plugin/mru.vim
"
" > Command-T - http://www.vim.org/scripts/script.php?script_id=3025
" Command-T plug-in provides an extremely fast, intuitive mechanism for opening filesa:
" info -> :help CommandT
" screencast and web-help -> http://amix.dk/blog/post/19501
"
"
" Revisions:
" > 3.6: Added lots of stuff (colors, Command-T, Vim 7.3 persistent undo etc.)
" > 3.5: Paste mode is now shown in status line if you are in paste mode
" > 3.4: Added mru.vim
" > 3.3: Added syntax highlighting for Mako mako.vim
" > 3.2: Turned on python_highlight_all for better syntax
" highlighting for Python
" > 3.1: Added revisions ;) and bufexplorer.vim
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=700
" Enable filetype plugin
filetype plugin on
filetype indent on
" Set to auto read when a file is changed from the outside
set autoread
" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","
let g:mapleader = ","
" Fast saving
nmap <leader>w :w!<cr>
" Fast editing of the .vimrc
map <leader>e :e! ~/.vim_runtime/vimrc<cr>
" When vimrc is edited, reload it
autocmd! bufwritepost vimrc source ~/.vim_runtime/vimrc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the curors - when moving vertical..
set so=7
set wildmenu "Turn on WiLd menu
set ruler "Always show current position
set cmdheight=2 "The commandbar height
set hid "Change buffer - without saving
" Set backspace config
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
set ignorecase "Ignore case when searching
set smartcase
set hlsearch "Highlight search things
set incsearch "Make search act like search in modern browsers
set nolazyredraw "Don't redraw while executing macros
set magic "Set magic on, for regular expressions
set showmatch "Show matching bracets when text indicator is over them
set mat=2 "How many tenths of a second to blink
" No sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
syntax enable "Enable syntax hl
" Set font according to system
if MySys() == "mac"
set gfn=Menlo:h14
set shell=/bin/bash
elseif MySys() == "windows"
set gfn=Bitstream\ Vera\ Sans\ Mono:h10
elseif MySys() == "linux"
set gfn=Monospace\ 10
set shell=/bin/bash
endif
if has("gui_running")
set guioptions-=T
set t_Co=256
set background=dark
colorscheme peaksea
set nonu
else
colorscheme zellner
set background=dark
set nonu
endif
set encoding=utf8
try
lang en_US
catch
endtry
set ffs=unix,dos,mac "Default file types
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git anyway...
set nobackup
set nowb
set noswapfile
"Persistent undo
try
if MySys() == "windows"
set undodir=C:\Windows\Temp
else
set undodir=~/.vim_runtime/undodir
endif
set undofile
catch
endtry
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set expandtab
set shiftwidth=4
set tabstop=4
set smarttab
set lbr
set tw=500
set ai "Auto indent
set si "Smart indet
set wrap "Wrap lines
""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Really useful!
" In visual mode when you press * or # to search for the current selection
vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>
" When you press gv you vimgrep after the selected text
vnoremap <silent> gv :call VisualSearch('gv')<CR>
map <leader>g :vimgrep // **/*.<left><left><left><left><left><left><left>
function! CmdLine(str)
exe "menu Foo.Bar :" . a:str
emenu Foo.Bar
unmenu Foo
endfunction
" From an idea by Michael Naumann
function! VisualSearch(direction) range
let l:saved_reg = #"
execute "normal! vgvy"
let l:pattern = escape(#", '\\/.*$^~[]')
let l:pattern = substitute(l:pattern, "\n$", "", "")
if a:direction == 'b'
execute "normal ?" . l:pattern . "^M"
elseif a:direction == 'gv'
call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.')
elseif a:direction == 'f'
execute "normal /" . l:pattern . "^M"
endif
let #/ = l:pattern
let #" = l:saved_reg
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Command mode related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Smart mappings on the command line
cno $h e ~/
cno $d e ~/Desktop/
cno $j e ./
cno $c e <C-\>eCurrentFileDir("e")<cr>
" $q is super useful when browsing on the command line
cno $q <C-\>eDeleteTillSlash()<cr>
" Bash like keys for the command line
cnoremap <C-A> <Home>
cnoremap <C-E> <End>
cnoremap <C-K> <C-U>
cnoremap <C-P> <Up>
cnoremap <C-N> <Down>
" Useful on some European keyboards
map ½ $
imap ½ $
vmap ½ $
cmap ½ $
func! Cwd()
let cwd = getcwd()
return "e " . cwd
endfunc
func! DeleteTillSlash()
let g:cmd = getcmdline()
if MySys() == "linux" || MySys() == "mac"
let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*", "\\1", "")
else
let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\]\\).*", "\\1", "")
endif
if g:cmd == g:cmd_edited
if MySys() == "linux" || MySys() == "mac"
let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*/", "\\1", "")
else
let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\\]\\).*\[\\\\\]", "\\1", "")
endif
endif
return g:cmd_edited
endfunc
func! CurrentFileDir(cmd)
return a:cmd . " " . expand("%:p:h") . "/"
endfunc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Map space to / (search) and c-space to ? (backgwards search)
map <space> /
map <c-space> ?
map <silent> <leader><cr> :noh<cr>
" Smart way to move btw. windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Close the current buffer
map <leader>bd :Bclose<cr>
" Close all the buffers
map <leader>ba :1,300 bd!<cr>
" Use the arrows to something usefull
map <right> :bn<cr>
map <left> :bp<cr>
" Tab configuration
map <leader>tn :tabnew<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove
" When pressing <leader>cd switch to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif
if bufnr("%") == l:currentBufNum
new
endif
if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction
" Specify the behavior when switching between buffers
try
set switchbuf=usetab
set stal=2
catch
endtry
""""""""""""""""""""""""""""""
" => Statusline
""""""""""""""""""""""""""""""
" Always hide the statusline
set laststatus=2
" Format the statusline
set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{CurDir()}%h\ \ \ Line:\ %l/%L:%c
function! CurDir()
let curdir = substitute(getcwd(), '/Users/amir/', "~/", "g")
return curdir
endfunction
function! HasPaste()
if &paste
return 'PASTE MODE '
else
return ''
endif
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Parenthesis/bracket expanding
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
vnoremap $1 <esc>`>a)<esc>`<i(<esc>
vnoremap $2 <esc>`>a]<esc>`<i[<esc>
vnoremap $3 <esc>`>a}<esc>`<i{<esc>
vnoremap $$ <esc>`>a"<esc>`<i"<esc>
vnoremap $q <esc>`>a'<esc>`<i'<esc>
vnoremap $e <esc>`>a"<esc>`<i"<esc>
" Map auto complete of (, ", ', [
inoremap $1 ()<esc>i
inoremap $2 []<esc>i
inoremap $3 {}<esc>i
inoremap $4 {<esc>o}<esc>O
inoremap $q ''<esc>i
inoremap $e ""<esc>i
inoremap $t <><esc>i
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General Abbrevs
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
iab xdate <c-r>=strftime("%d/%m/%y %H:%M:%S")<cr>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Remap VIM 0
map 0 ^
"Move a line of text using ALT+[jk] or Comamnd+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z
if MySys() == "mac"
nmap <D-j> <M-j>
nmap <D-k> <M-k>
vmap <D-j> <M-j>
vmap <D-k> <M-k>
endif
"Delete trailing white space, useful for Python ;)
func! DeleteTrailingWS()
exe "normal mz"
%s/\s\+$//ge
exe "normal `z"
endfunc
autocmd BufWrite *.py :call DeleteTrailingWS()
set guitablabel=%t
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Cope
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Do :help cope if you are unsure what cope is. It's super useful!
map <leader>cc :botright cope<cr>
map <leader>n :cn<cr>
map <leader>p :cp<cr>
""""""""""""""""""""""""""""""
" => bufExplorer plugin
""""""""""""""""""""""""""""""
let g:bufExplorerDefaultHelp=0
let g:bufExplorerShowRelativePath=1
map <leader>o :BufExplorer<cr>
""""""""""""""""""""""""""""""
" => Minibuffer plugin
""""""""""""""""""""""""""""""
let g:miniBufExplModSelTarget = 1
let g:miniBufExplorerMoreThanOne = 2
let g:miniBufExplModSelTarget = 0
let g:miniBufExplUseSingleClick = 1
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplVSplit = 25
let g:miniBufExplSplitBelow=1
let g:bufExplorerSortBy = "name"
autocmd BufRead,BufNew :call UMiniBufExplorer
map <leader>u :TMiniBufExplorer<cr>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Omni complete functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Spell checking
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>
"Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=
""""""""""""""""""""""""""""""
" => Python section
""""""""""""""""""""""""""""""
let python_highlight_all = 1
au FileType python syn keyword pythonDecorator True None False self
au BufNewFile,BufRead *.jinja set syntax=htmljinja
au BufNewFile,BufRead *.mako set ft=mako
au FileType python inoremap <buffer> $r return
au FileType python inoremap <buffer> $i import
au FileType python inoremap <buffer> $p print
au FileType python inoremap <buffer> $f #--- PH ----------------------------------------------<esc>FP2xi
au FileType python map <buffer> <leader>1 /class
au FileType python map <buffer> <leader>2 /def
au FileType python map <buffer> <leader>C ?class
au FileType python map <buffer> <leader>D ?def
""""""""""""""""""""""""""""""
" => JavaScript section
"""""""""""""""""""""""""""""""
au FileType javascript call JavaScriptFold()
au FileType javascript setl fen
au FileType javascript setl nocindent
au FileType javascript imap <c-t> AJS.log();<esc>hi
au FileType javascript imap <c-a> alert();<esc>hi
au FileType javascript inoremap <buffer> $r return
au FileType javascript inoremap <buffer> $f //--- PH ----------------------------------------------<esc>FP2xi
function! JavaScriptFold()
setl foldmethod=syntax
setl foldlevelstart=1
syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend
function! FoldText()
return substitute(getline(v:foldstart), '{.*', '{...}', '')
endfunction
setl foldtext=FoldText()
endfunction
""""""""""""""""""""""""""""""
" => MRU plugin
""""""""""""""""""""""""""""""
let MRU_Max_Entries = 400
map <leader>f :MRU<CR>
""""""""""""""""""""""""""""""
" => Command-T
""""""""""""""""""""""""""""""
let g:CommandTMaxHeight = 15
set wildignore+=*.o,*.obj,.git,*.pyc
noremap <leader>j :CommandT<cr>
noremap <leader>y :CommandTFlush<cr>
""""""""""""""""""""""""""""""
" => Vim grep
""""""""""""""""""""""""""""""
let Grep_Skip_Dirs = 'RCS CVS SCCS .svn generated'
set grepprg=/bin/grep\ -nH
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => MISC
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
"Quickly open a buffer for scripbble
map <leader>q :e ~/buffer<cr>
au BufRead,BufNewFile ~/buffer iab <buffer> xh1 ===========================================
map <leader>pp :setlocal paste!<cr>
map <leader>bb :cd ..<cr>
From my understanding this should change from the default colors to peaksea, but this does not work...
if has("gui_running")
set guioptions-=T
set t_Co=256
set background=dark
colorscheme peaksea
set nonu
else
colorscheme zellner
set background=dark
set nonu
endif
to
I have peaksea installed and working, but I would like it to start up as default. I would also like to have another font by default than fixedsys also (who decided to have that as default?!)
Put the following line in either your .vimrc or .gvimrc (GVIM) file.
set colorscheme peaksea
If the file does not exist, you can just create it first via
touch ~/.vimrc
This question already has an answer here:
Closed 12 years ago.
Possible Duplicate:
configure gvim setting color and font
Hi. I have just installed vim and want to set some default settings. I have installed gvim here:
C:\Program Files (x86)\Vim\vim73
I have my config file here:
C:\Program Files (x86)\Vim\vim73\.vimrc
I just tried a config file I found. Here is the content of my current .vimrc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Maintainer: amix the lucky stiff
" http://amix.dk - amix#amix.dk
"
" Version: 3.6 - 25/08/10 14:40:30
"
" Blog_post:
" http://amix.dk/blog/post/19486#The-ultimate-vim-configuration-vimrc
" Syntax_highlighted:
" http://amix.dk/vim/vimrc.html
" Raw_version:
" http://amix.dk/vim/vimrc.txt
"
" How_to_Install_on_Unix:
" $ mkdir ~/.vim_runtime
" $ svn co svn://orangoo.com/vim ~/.vim_runtime
" $ cat ~/.vim_runtime/install.sh
" $ sh ~/.vim_runtime/install.sh <system>
" <sytem> can be `mac`, `linux` or `windows`
"
" How_to_Upgrade:
" $ svn update ~/.vim_runtime
"
" Sections:
" -> General
" -> VIM user interface
" -> Colors and Fonts
" -> Files and backups
" -> Text, tab and indent related
" -> Visual mode related
" -> Command mode related
" -> Moving around, tabs and buffers
" -> Statusline
" -> Parenthesis/bracket expanding
" -> General Abbrevs
" -> Editing mappings
"
" -> Cope
" -> Minibuffer plugin
" -> Omni complete functions
" -> Python section
" -> JavaScript section
"
"
" Plugins_Included:
" > minibufexpl.vim - http://www.vim.org/scripts/script.php?script_id=159
" Makes it easy to get an overview of buffers:
" info -> :e ~/.vim_runtime/plugin/minibufexpl.vim
"
" > bufexplorer - http://www.vim.org/scripts/script.php?script_id=42
" Makes it easy to switch between buffers:
" info -> :help bufExplorer
"
" > yankring.vim - http://www.vim.org/scripts/script.php?script_id=1234
" Emacs's killring, useful when using the clipboard:
" info -> :help yankring
"
" > surround.vim - http://www.vim.org/scripts/script.php?script_id=1697
" Makes it easy to work with surrounding text:
" info -> :help surround
"
" > snipMate.vim - http://www.vim.org/scripts/script.php?script_id=2540
" Snippets for many languages (similar to TextMate's):
" info -> :help snipMate
"
" > mru.vim - http://www.vim.org/scripts/script.php?script_id=521
" Plugin to manage Most Recently Used (MRU) files:
" info -> :e ~/.vim_runtime/plugin/mru.vim
"
" > Command-T - http://www.vim.org/scripts/script.php?script_id=3025
" Command-T plug-in provides an extremely fast, intuitive mechanism for opening filesa:
" info -> :help CommandT
" screencast and web-help -> http://amix.dk/blog/post/19501
"
"
" Revisions:
" > 3.6: Added lots of stuff (colors, Command-T, Vim 7.3 persistent undo etc.)
" > 3.5: Paste mode is now shown in status line if you are in paste mode
" > 3.4: Added mru.vim
" > 3.3: Added syntax highlighting for Mako mako.vim
" > 3.2: Turned on python_highlight_all for better syntax
" highlighting for Python
" > 3.1: Added revisions ;) and bufexplorer.vim
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=700
" Enable filetype plugin
filetype plugin on
filetype indent on
" Set to auto read when a file is changed from the outside
set autoread
" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","
let g:mapleader = ","
" Fast saving
nmap <leader>w :w!<cr>
" Fast editing of the .vimrc
map <leader>e :e! ~/.vim_runtime/vimrc<cr>
" When vimrc is edited, reload it
autocmd! bufwritepost vimrc source ~/.vim_runtime/vimrc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 7 lines to the curors - when moving vertical..
set so=7
set wildmenu "Turn on WiLd menu
set ruler "Always show current position
set cmdheight=2 "The commandbar height
set hid "Change buffer - without saving
" Set backspace config
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
set ignorecase "Ignore case when searching
set smartcase
set hlsearch "Highlight search things
set incsearch "Make search act like search in modern browsers
set nolazyredraw "Don't redraw while executing macros
set magic "Set magic on, for regular expressions
set showmatch "Show matching bracets when text indicator is over them
set mat=2 "How many tenths of a second to blink
" No sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
syntax enable "Enable syntax hl
" Set font according to system
if MySys() == "mac"
set gfn=Menlo:h14
set shell=/bin/bash
elseif MySys() == "windows"
set gfn=Bitstream\ Vera\ Sans\ Mono:h10
elseif MySys() == "linux"
set gfn=Monospace\ 10
set shell=/bin/bash
endif
if has("gui_running")
set guioptions-=T
set t_Co=256
set background=dark
colorscheme peaksea
set nonu
else
colorscheme zellner
set background=dark
set nonu
endif
set encoding=utf8
try
lang en_US
catch
endtry
set ffs=unix,dos,mac "Default file types
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git anyway...
set nobackup
set nowb
set noswapfile
"Persistent undo
try
if MySys() == "windows"
set undodir=C:\Windows\Temp
else
set undodir=~/.vim_runtime/undodir
endif
set undofile
catch
endtry
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set expandtab
set shiftwidth=4
set tabstop=4
set smarttab
set lbr
set tw=500
set ai "Auto indent
set si "Smart indet
set wrap "Wrap lines
""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Really useful!
" In visual mode when you press * or # to search for the current selection
vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>
" When you press gv you vimgrep after the selected text
vnoremap <silent> gv :call VisualSearch('gv')<CR>
map <leader>g :vimgrep // **/*.<left><left><left><left><left><left><left>
function! CmdLine(str)
exe "menu Foo.Bar :" . a:str
emenu Foo.Bar
unmenu Foo
endfunction
" From an idea by Michael Naumann
function! VisualSearch(direction) range
let l:saved_reg = #"
execute "normal! vgvy"
let l:pattern = escape(#", '\\/.*$^~[]')
let l:pattern = substitute(l:pattern, "\n$", "", "")
if a:direction == 'b'
execute "normal ?" . l:pattern . "^M"
elseif a:direction == 'gv'
call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.')
elseif a:direction == 'f'
execute "normal /" . l:pattern . "^M"
endif
let #/ = l:pattern
let #" = l:saved_reg
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Command mode related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Smart mappings on the command line
cno $h e ~/
cno $d e ~/Desktop/
cno $j e ./
cno $c e <C-\>eCurrentFileDir("e")<cr>
" $q is super useful when browsing on the command line
cno $q <C-\>eDeleteTillSlash()<cr>
" Bash like keys for the command line
cnoremap <C-A> <Home>
cnoremap <C-E> <End>
cnoremap <C-K> <C-U>
cnoremap <C-P> <Up>
cnoremap <C-N> <Down>
" Useful on some European keyboards
map ½ $
imap ½ $
vmap ½ $
cmap ½ $
func! Cwd()
let cwd = getcwd()
return "e " . cwd
endfunc
func! DeleteTillSlash()
let g:cmd = getcmdline()
if MySys() == "linux" || MySys() == "mac"
let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*", "\\1", "")
else
let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\]\\).*", "\\1", "")
endif
if g:cmd == g:cmd_edited
if MySys() == "linux" || MySys() == "mac"
let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*/", "\\1", "")
else
let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\\]\\).*\[\\\\\]", "\\1", "")
endif
endif
return g:cmd_edited
endfunc
func! CurrentFileDir(cmd)
return a:cmd . " " . expand("%:p:h") . "/"
endfunc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Map space to / (search) and c-space to ? (backgwards search)
map <space> /
map <c-space> ?
map <silent> <leader><cr> :noh<cr>
" Smart way to move btw. windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Close the current buffer
map <leader>bd :Bclose<cr>
" Close all the buffers
map <leader>ba :1,300 bd!<cr>
" Use the arrows to something usefull
map <right> :bn<cr>
map <left> :bp<cr>
" Tab configuration
map <leader>tn :tabnew<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove
" When pressing <leader>cd switch to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif
if bufnr("%") == l:currentBufNum
new
endif
if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction
" Specify the behavior when switching between buffers
try
set switchbuf=usetab
set stal=2
catch
endtry
""""""""""""""""""""""""""""""
" => Statusline
""""""""""""""""""""""""""""""
" Always hide the statusline
set laststatus=2
" Format the statusline
set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{CurDir()}%h\ \ \ Line:\ %l/%L:%c
function! CurDir()
let curdir = substitute(getcwd(), '/Users/amir/', "~/", "g")
return curdir
endfunction
function! HasPaste()
if &paste
return 'PASTE MODE '
else
return ''
endif
endfunction
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Parenthesis/bracket expanding
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
vnoremap $1 <esc>`>a)<esc>`<i(<esc>
vnoremap $2 <esc>`>a]<esc>`<i[<esc>
vnoremap $3 <esc>`>a}<esc>`<i{<esc>
vnoremap $$ <esc>`>a"<esc>`<i"<esc>
vnoremap $q <esc>`>a'<esc>`<i'<esc>
vnoremap $e <esc>`>a"<esc>`<i"<esc>
" Map auto complete of (, ", ', [
inoremap $1 ()<esc>i
inoremap $2 []<esc>i
inoremap $3 {}<esc>i
inoremap $4 {<esc>o}<esc>O
inoremap $q ''<esc>i
inoremap $e ""<esc>i
inoremap $t <><esc>i
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General Abbrevs
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
iab xdate <c-r>=strftime("%d/%m/%y %H:%M:%S")<cr>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Remap VIM 0
map 0 ^
"Move a line of text using ALT+[jk] or Comamnd+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z
if MySys() == "mac"
nmap <D-j> <M-j>
nmap <D-k> <M-k>
vmap <D-j> <M-j>
vmap <D-k> <M-k>
endif
"Delete trailing white space, useful for Python ;)
func! DeleteTrailingWS()
exe "normal mz"
%s/\s\+$//ge
exe "normal `z"
endfunc
autocmd BufWrite *.py :call DeleteTrailingWS()
set guitablabel=%t
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Cope
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Do :help cope if you are unsure what cope is. It's super useful!
map <leader>cc :botright cope<cr>
map <leader>n :cn<cr>
map <leader>p :cp<cr>
""""""""""""""""""""""""""""""
" => bufExplorer plugin
""""""""""""""""""""""""""""""
let g:bufExplorerDefaultHelp=0
let g:bufExplorerShowRelativePath=1
map <leader>o :BufExplorer<cr>
""""""""""""""""""""""""""""""
" => Minibuffer plugin
""""""""""""""""""""""""""""""
let g:miniBufExplModSelTarget = 1
let g:miniBufExplorerMoreThanOne = 2
let g:miniBufExplModSelTarget = 0
let g:miniBufExplUseSingleClick = 1
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplVSplit = 25
let g:miniBufExplSplitBelow=1
let g:bufExplorerSortBy = "name"
autocmd BufRead,BufNew :call UMiniBufExplorer
map <leader>u :TMiniBufExplorer<cr>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Omni complete functions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Spell checking
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>
"Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=
""""""""""""""""""""""""""""""
" => Python section
""""""""""""""""""""""""""""""
let python_highlight_all = 1
au FileType python syn keyword pythonDecorator True None False self
au BufNewFile,BufRead *.jinja set syntax=htmljinja
au BufNewFile,BufRead *.mako set ft=mako
au FileType python inoremap <buffer> $r return
au FileType python inoremap <buffer> $i import
au FileType python inoremap <buffer> $p print
au FileType python inoremap <buffer> $f #--- PH ----------------------------------------------<esc>FP2xi
au FileType python map <buffer> <leader>1 /class
au FileType python map <buffer> <leader>2 /def
au FileType python map <buffer> <leader>C ?class
au FileType python map <buffer> <leader>D ?def
""""""""""""""""""""""""""""""
" => JavaScript section
"""""""""""""""""""""""""""""""
au FileType javascript call JavaScriptFold()
au FileType javascript setl fen
au FileType javascript setl nocindent
au FileType javascript imap <c-t> AJS.log();<esc>hi
au FileType javascript imap <c-a> alert();<esc>hi
au FileType javascript inoremap <buffer> $r return
au FileType javascript inoremap <buffer> $f //--- PH ----------------------------------------------<esc>FP2xi
function! JavaScriptFold()
setl foldmethod=syntax
setl foldlevelstart=1
syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend
function! FoldText()
return substitute(getline(v:foldstart), '{.*', '{...}', '')
endfunction
setl foldtext=FoldText()
endfunction
""""""""""""""""""""""""""""""
" => MRU plugin
""""""""""""""""""""""""""""""
let MRU_Max_Entries = 400
map <leader>f :MRU<CR>
""""""""""""""""""""""""""""""
" => Command-T
""""""""""""""""""""""""""""""
let g:CommandTMaxHeight = 15
set wildignore+=*.o,*.obj,.git,*.pyc
noremap <leader>j :CommandT<cr>
noremap <leader>y :CommandTFlush<cr>
""""""""""""""""""""""""""""""
" => Vim grep
""""""""""""""""""""""""""""""
let Grep_Skip_Dirs = 'RCS CVS SCCS .svn generated'
set grepprg=/bin/grep\ -nH
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => MISC
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
"Quickly open a buffer for scripbble
map <leader>q :e ~/buffer<cr>
au BufRead,BufNewFile ~/buffer iab <buffer> xh1 ===========================================
map <leader>pp :setlocal paste!<cr>
map <leader>bb :cd ..<cr>
From what I understand this should change the default colors
if has("gui_running")
set guioptions-=T
set t_Co=256
set background=dark
colorscheme peaksea
set nonu
else
colorscheme zellner
set background=dark
set nonu
endif
I have added peaksea and it works when I manually change the colors, but I want this to happen automatically. Clearly this does not happen... What have I done wrong?
As a first advise: since you're a starter with VIM, don't go and copy a .vimrc you find anywhere on the net. They could change the behavior of VIM in a way where nobody can help you if you experience any problems (and don't understand what's going on in your .vimrc).
In general, the settings specific for a GUI version (i.e. GVim) are stored in a separate file called _gvimrc. The default locations for _vimrc (yes, with underscore, not a dot under Win32) and _gvimrc is C:/Documents and Settings/your_home_folder. Plugins and colorschemes and any other stuff you install should go to a folder called vimfiles on the same location.
Using _vimrc for general settings and _gvimrc for GUI related settings, you avoid the
if has("gui_running")
something
else
something else
endif
blocks cluttering up your _vimrc. The _vimrc is getting sourced every time a new instance of Vim is started, afterwards, the _gvimrc gets sourced if it's a GVim.
Use :version command to find the path of vimrc files.