Friday, June 29, 2012

vim tips: folding fun



本文參考自 : https://www.linux.com/learn/tutorials/442438-vim-tips-folding-fun


介紹 vim 的 folding 技巧,也就是如何乾淨的把 code 折疊起來





首先,vim folding 指令都是由 z 開頭,我的記法是 zip the code

z 開頭的指令 zt zz zb 這三個很好用,順便提一下

功能是把游標目前所在的行捲到螢幕的 top / center / bottom


這在臨時上下捲動頁面半頁或是要邊寫 function 時很好用

vim 底下:h z 可以看到 folding 相關的指令 (這邊把其他不相干的刪減掉了)

BTW,最完整的教學在 :h fold.txt 裏面可以看到


zA              zA                 open a closed fold or close an open fold     
                                   recursively                                  
zC              zC                 close folds recursively                      
zD              zD                 delete folds recursively                     
zE              zE                 eliminate all folds                          
zF              zF                 create a fold for N lines                    
zO              zO                 open folds recursively                       
za              za                 open a closed fold, close an open fold       
zc              zc                 close a fold                                 
zd              zd                 delete a fold                               
zf              zf{motion}         create a fold for Nmove text                 
zj              zj              1  move to the start of the next fold           
zk              zk              1  move to the end of the previous fold         


看的懂英文應該基本上就知道這幾個要怎麼用了XD

最常用的是 zf + {motion} 

像是 zf2j 可以向下折疊兩行 (zip folding 2 j),就跟你用 2j 在 vim 裏面往下移動兩行一樣

另外一種方法是在 normal mode 下 :N, M fold ,N M 是行數,把  N, M 行之間的 code 折起來

再來一種是 {Visual}zf 也就是用 visual 模式下選取要 folding 的區域,然後再用 zf 幫你折起來

zf 的 motion 也可以搭配 vim 的 text object 來使用,像是 zfa} 或是 zfa{ 可以向下或向上折疊一段落

當然,也可以搭配 searching 來找,zf/pattern 就是折疊到第一個你找到的 pattern


接下來是使用 folding 的方法

zo / zc 則是拿來 open/close folding 的

zO / zC 可以 打開/關閉 底下的子 folding

當然,za zA 可以把 folding 當成電燈開關一樣,打開 folded 的區塊, fold 被打開的區塊

zr / zm 是將 fold level 開啟和關閉一層

zR / zM 是對所有的 fold level 作,也就是打開 / 關閉整個檔案裡所以的 folding

在被 folded 的 code 間移動有很快的作法, zj / zk ,如同你所想的,移動到 上 / 下個 folded 的 code


zd delete 掉游標所在的 folding

zE delete 所有的 folding


最後, vim 在處理被 folding 起來的區塊時,會把他當成像是一行文一樣,也就是說,可以對他做一行的操作,像是 dd 和 yy


Wednesday, June 27, 2012

The Best Career Advice I Ever Heard

我聽過最好的職涯建議

出自

http://www.forbes.com/sites/deborahljacobs/2012/06/25/the-best-career-advice-i-ever-heard-dream-big-dont-fret-about-things-you-cant-change-and-18-other-gems/


Lisa McMurtrie, educational consultant/tutor (Baltimore, MD):
1. “People break down into two groups, motors and anchors. You always want to surround yourself by people who push you forward, not hold you down.”


Amy Less, recruiting manager, Jupiter Medical Center (West Palm Beach, Fla.):
2. “There are things in life that you can’t control. . .so don’t waste your time, energy or sanity on them. You can only control your reaction to them. . .so make your reaction worthy, smart and sane.”


Gala DeJong, administrative coordinator, ASI | Signage Innovations (Des Moines, Iowa):
3. “You have to work with your co-workers but you do not have to be best friends.”


Sherlynn Lauture Vernon, independent marketing representative (Tampa, Fla.):
4. “If you don’t build YOUR dream, someone will hire you to build THEIRS!”


Rosita Weller,  training and personal development manager (Corwen, Denbighshire, United Kingdom):
5. ” I was about to venture out of my comfort zone. I was offered a position as training officer in the company I worked for. I felt daunted by the offer. I doubted whether I could do this as I was not a good communicator and did not feel comfortable speaking with strangers. My husband’s advice to me was, ‘Just be your nutty self.’ I took him literally, and my confidence grew with each training session.”


Mary Barnes, vice president, business and operation, Userplane (Washington, D.C.):
6. “When I took on my first management role someone told me I would go through three phases: the honeymoon period, the test and how it’s actually going to be. I have kept that advice in mind over the years. It has helped frame many transition periods for me.”


Danielle Leone, administrative dispatch assistant, Publix (Sarasota, Fla.):
7. “You have two eyes, two ears, and one mouth. Observe and listen twice before speaking once.”


Lisa Selip, vice president of marketing, licensing and business development, Mighty Kids Media (Charlotte, N.C.): 
8. “Before you put somebody in their place, put yourself in their place.”


Jennifer Jones, opera singer (Phoenix):
9. “‘If you want something you have never had, you must be willing to do something you have never done.’ I do not have an author to credit this saying to but the person who wrote this has influenced my life in many wonderful ways.”


Kathy Simmers, executive, So Worth It (Raleigh-Durham, NC):
10. “I was promised a raise at my job if certain things happened. They happened, the raise didn’t. I walked out and I wasn’t sure if I was going back. A friend said to me, ‘Don’t let their lack of integrity choose the timing for you to leave. Choose your time, make your plan.’ I went back, put my plan in place. A few months later when the time was right, I left and started my own firm. It was just the advice I needed at the time. I have been successfully self-employed ever since.”


Elizabeth Kimmelman Schwartz, associate director, alumnae engagement, Bryn Mawr College (Bryn Mawr, PA):
11. “‘Don’t live on all of your salary, put a set amount aside automatically every month so you build up savings and know you can live on less. This will give you freedom to pursue what you want.’ A partner at a very prestigious corporate law firm told me that when I was a summer associate. I took it to heart and that philosophy is what allowed me to finally leave big law and work in higher education, despite the drastic pay cut. I’m now happy and very fulfilled – and I still live on less than what I bring home!”


Sheila Frances, publisher/author, FranJeff Publishing (Delray Beach, Fla.):
12. “I am the only one who places limitations on what I can do or on what I can become. Reach for the moon and you will catch a STAR! Never stop climbing!”


Molly K. McPherson, masters candidate, international trade and investment policy (Washington, D.C.):
13. “Carefully phrased questions can help move a discussion along and resolve a conflict better than the best-made point. . . This has helped me immensely in developing relationships with difficult executives who were not interested in hearing my (or anyone else’s) opinion.”


Lisa Sayers, self-employed entrepreneur (Erie, PA):
14. “It’s not who we are that keeps us from where we want to be–it’s who we THINK we are.”


Lori Koopmann, vice president, finance, Barcom Electronics (St. Louis, MO):
15. “From a very wise man who taught me a lot about business and people in general: ‘If you take care of the customer, the money will come. If you chase the money, the customer will run.’”


Nancy Miller, professor of marketing (Atlanta, GA): 
16. “From Ms. Frizzle [the teacher in The Magic School Bus books], ‘Take chances, make mistakes, get messy.’”


Kimberly McHale, director, marketing communications, Coastal Medical Management (Providence, R.I.):
17. “Smile openly at every person you see! It can literally change not only their day, but yours as well.”


Carrie Krier, recruiting manager, Wells Fargo (Des Moines, Iowa):
18. “A former bank president wisely advised, ‘Don’t look back, we’re not going that way!’”


Eileen Becker, lawyer, Loughlin FitzGerald (New York):
19. “The piece of advice I tend to fall back on quite often is a quote from Eleanor Roosevelt that I have posted on my office wall: ‘You must do the thing you think you cannot do.’”


Sherry Nouraini, consultant, Comprendia (San Diego, Calif.):
20. “Don’t be the best kept secret!”


Thursday, June 7, 2012

Editing remote files via scp in vim

之前看到有人在 plurl 上分享這則 vim tips

http://vim.wikia.com/wiki/Editing_remote_files_via_scp_in_vim

用法   vim scp://user@機器/絕對路徑




$ vim scp://remoteuser@server.tld//path/to/document



# 透過 ~/ 到 home 的相對路徑

$ vim scp://xatier@mydomain/~/foo.pl


# 同樣的也可以寫成這樣
$ vim scp://xatier@mydomain//home/xatier/foo.pl





其原理是透過先 scp 到本地 /tmp 後再用 vim 打開,存檔時會再 scp 回去


觀察信息可以看到

:!scp -q 'remote file' '/tmp/vRSFC24/0.pl'

:!scp -q '/tmp/vRSFC24/0' 'remotefile'


Wednesday, June 6, 2012

100 Vim commands every programmer should know

100 Vim commands every programmer should know
一百個 programmer 應該知道的 vim 指令

http://www.catswhocode.com/blog/100-vim-commands-every-programmer-should-know




Since the 70′s, Vi is one of the programmer’s best friend. Nevermind you’re new to Vi or not, here’s a big list of 100 useful commands, organized by topic, which will make your coder life better.






原文錯誤很多 Orz

我做了翻譯和更正

感謝 darkgerm 學長用心挑錯

====================================================


Basics  基本
:e filename     打開編輯(e) filename
:w              存檔
:q              離開
:q!             離開但不存檔


Search  搜尋
/word           由上而下搜尋 word
?word           由下而上搜尋 word
/jo[ha]n        搜尋 john 或 joan
/\<the         搜尋以 the 開頭的字
/the\>          搜尋以 the 結尾的字
/\<the\>       搜尋 the 這個字
/\<....\>       找所有四個字母組成的字
/\<fred\>       找 fred 但不是 alfred 或 frederick
/fred\|joe      找 fred 或 joe
/\<\d\d\d\d\>   找四個數字 (長度為 4 的數字 )
/^\n\{\3\}        三個空行,有一個 magic 的寫法是 /\v^\n{3}     (*)
:bufdo /searchstr/  搜尋所有開啟的檔案


Replace  取代
:%s/old/new/g       在本檔案(%) 取代(s) 所有(g) old 改成 new
:%s/old/new/gc      取代所有時確認一下 c(Confirm)
:2,35s/old/new/g    第 2 到第 35 行之間取代
:5,$s/old/new/g     第五行到檔案結尾 (EOF) 之間取代
:%s/^/hello/g       把每一行的開頭取代成 hello
:%s/$/Harry/g       把每一行的結尾取代成 Harry
:%s/onward/forward/gi   取代 onward 成 forward ,不管大小寫(i)
:%s/ *$//g          刪除所有"trailing space"
:g/string/d         刪除所有包含 string 的行
:v/string/d         刪除所有不包含 string 的行
:s/Bill/Steve/      取代本行第一個 Bill 成 Steve
:s/Bill/Steve/g     取代本行所有(g) Bill 成 Steve
:%s/Bill/Steve/g    取代本檔案(%) 所有(g) Bill 成 Steve
:%s/\r//g           刪除 DOS 換行 (^M)
:%s/\r/\n/g       把 DOS 換行改成一般換行     (*)
:%s#<[^>]\+>##g     刪除 HTML 標籤但保留文字           (*)
:%s/^\(.*\)\n\1$/\1/    刪除重複兩次的行
Ctrl+a              游標所在的數字加一
Ctrl+x              游標所在的數字減一
ggVGg?              全文選取(ggVG) Rot13 加密 (g?)


Case  大小寫
Vu              整行選取(V)改小寫
VU              整行選取(V)改大寫
g~~             整行大小寫轉換
vEU             把字改成大寫
vE~             字的大小寫轉換
ggguG           全文改小寫
:set ignorecase 設定搜尋時忽略大小寫
:set smartcase  設定搜尋時忽略大小寫除非有使用大寫字
:%s/\<./\u&/g   每一個字的第一個字母改大寫
:%s/\<./\l&/g   每一個字的第一個字母改小寫
:%s/.*/\u&      每一行的第一個字母改大寫
:%s/.*/\l&      每一行的第一個字母改小寫


Read/Write files  讀寫檔案
:1,10 w outfile     在 outfile 存 1 到 10 行
:1,10 w >> outfile  附加 1 到 10 行去 outfile
:r infile           插入 infile 的內容
:23r infile         在 23 行插入 infile 的內容


File explorer  檔案瀏覽
:e .            打開檔案瀏覽器
:Sex            水平分割視窗並打開檔案瀏覽器  Sexplore (Split&Explore)    (*)

:browse e       指定的目錄裏打開瀏覽器並編輯選擇的文件 {only in Win32, Athena, Motif, GTK and Mac GUI}
:ls             列出現在的 buffer
:cd ..          回到上一層資料夾
:args           列出參數 (正在編輯的檔案列表)
:args *.php     php 檔
:grep expression *.php      回傳一個所有包含 expressoin2 的 .php 檔之列表
gf              開啟游標現在指向的檔案


Interact with Unix  跟 Unix 互動
:!pwd   執行 pwd unix 指令,然後回到 vi
!!pwd   執行 pwd unix 指令,把結果插入到檔案
:sh     暫時開一個 shell
$exit   (在剛剛開的 shell 裡) 用 exit 指令回到 vim (其實用 Ctrl-D 也可以)


Alignment  對齊
:%!fmt  對齊所有行 (外部指令)
!}fmt   對齊所有在 {} 內的行
5!!fmt  對齊下五行


Tabs  分頁
:tabnew     開新分頁
gt          下一個分頁
gT          上一個分頁
:tabfirst   第一個分頁
:tablast    最後一個分頁
:tabm n     tabmove 把當前分頁移到 n 的位置
:tabdo %s/foo/bar/g 在所有分頁執行指令
:tab ball   把所有有開的檔案放在一個 tab 裡


Window spliting  分割視窗
:e filename         在目前視窗編輯 filename
:split filename     分割視窗並開啟 filename
ctrl-w k     游標移到上面的視窗
ctrl-w ctrl-w       游標移到下一個視窗
ctrl-w_             視窗最大化
ctrl-w=             視窗大小均等
10 ctrl-w+          增加十行的大小
:vsplit file        垂直分割視窗
:sview file         分割視窗 (唯讀)
:hide               關閉目前視窗
:­only              關閉其他所有視窗
:b 2                打開 buffer 2


Auto-completion  自動補完
Ctrl+n Ctrl+p (在 insert mode)  補完字
Ctrl+x Ctrl+l                   補完行
:set dictionary=dict            將 dict 設成字典
Ctrl+x Ctrl+k                   字典補完


Marks  標記
mk      將目前位置標記為 k
`k      把游標移動 k 標記
d'k     刪除所有 k 標記之前的東西


Abbreviations  縮寫
:ab mail mail@provider.org  定義 mail 是 mail@provider.org 的縮寫


Text indent  文字縮排
:set autoindent     設定自動縮排
:set smartindent    設定聰明縮排
:set shiftwidth=4   以四個 space 當作縮排大小
ctrl-t, ctrl-d      縮排/反縮排 (在 insert mode 下)
>>  縮排
<<  反縮排


Syntax highlighting  語法上色
:syntax on          打開語法上色
:syntax off         關閉語法上色
:set syntax=perl    設定特定語法





==================================================
**註**

Use of "\v" means that in the pattern after it all ASCII characters except
'0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning.  "very magic"


把 早期的 MAC 換行換成 windows 換行
windows 換行是 \r\n    *nix 是 \n   早期的 MAC 是 \r
現在 MAC 底層是 BSD 所以也是 \n
有 dos2unix 可以轉


對這行 s/#/\//g XD
這個作法其實會有很多問題,例如如果 tag 中有換行就失效了
或是文字有 < > 也會出問題
引用 irc://irc.freenode.net/regex 的 title     Do NOT use RegEx to parse HTML!
比較好的做法是用程式去 parse


Sexplore (Split&Explore)
還有 Vex 我覺的比較好用





Learn to speak vim


看到了一篇蠻有趣的文章

http://yanpritzker.com/2011/12/16/learn-to-speak-vim-verbs-nouns-and-modifiers/

節錄如下

Using vim is like talking to your editor in ‘verb modifier object’ sentences, turned into acronyms

 learn some verbs: v (visual), c (change), d (delete), y (yank/copy). these are the most important. there are others
 learn some modifiers: i (inside), a (around), t (till..finds a character), f (find..like till except including the char), / (search..find a string/regex)
 learn some text objects: w (word), s (sentence) p (paragraph) b (block/parentheses), t (tag, works for html/xml) there are others

To move efficiently in vim, don’t try to do anything by pressing keys many times, instead speak to the editor in sentences

 delete the current word: diw (delete inside word)
 change current sentence: cis (change inside sentence)
 change a string inside quotes: ci” (change inside quote)
 change until next occurrence of ‘foo’: c/foo (change search foo)
 change everything from here to the letter X: ctX
 visually select this paragraph: vap (visual around paragraph)

If you nderstand the verbs and objects you’re dealing with, you will soon realize that adding a new plugin and learning a new verb or noun exponentially increases your productivity, as you can now apply it in all the sentences you already know. It’s just like learning a language.

Friday, June 1, 2012

my vimrc


今天在噗浪上看到有人分享 github 上的這份 The Ultimate vimrc

順手又在我的 vimrc 添增幾筆有用的 settings

我的 vimrc 也是到處看別人的撇步和技巧

順便推一下 vgod 學長的 vgod'vimrc XD



以下分享我的 vimrc 設定



" All system-wide defaults are set in $VIMRUNTIME/debian.vim (usually just
" /usr/share/vim/vimcurrent/debian.vim) and sourced by the call to :runtime
" you can find below.  If you wish to change any of those settings, you should
" do it in this file (/etc/vim/vimrc), since debian.vim will be overwritten
" everytime an upgrade of the vim packages is performed.  It is recommended to
" make changes after sourcing debian.vim since it alters the value of the
" 'compatible' option.

" This line should not be removed as it ensures that various options are
" properly set to work with the Vim-related packages available in Debian.
runtime! debian.vim

" Uncomment the next line to make Vim more Vi-compatible
" NOTE: debian.vim sets 'nocompatible'.  Setting 'compatible' changes numerous
" options, so any other options should be set AFTER setting 'compatible'.
"set compatible

" Vim5 and later versions support syntax highlighting. Uncommenting the
" following enables syntax highlighting by default.
if has("syntax")
  syntax on
endif

" If using a dark background within the editing area and syntax highlighting
" turn on this option as well
"set background=dark

" Uncomment the following to have Vim jump to the last position when
" reopening a file
"if has("autocmd")
"  au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
"endif

" Uncomment the following to have Vim load indentation rules and plugins
" according to the detected filetype.
"if has("autocmd")
"  filetype plugin on
" indent on
"endif

" The following are commented out as they cause vim to behave a lot
" differently from regular Vi. They are highly recommended though.
"set showcmd        " Show (partial) command in status line.
"set showmatch        " Show matching brackets.
"set ignorecase        " Do case insensitive matching
"set smartcase        " Do smart case matching
"set incsearch        " Incremental search
"set autowrite        " Automatically save before commands like :next and :make
"set hidden             " Hide buffers when they are abandoned
"set mouse=a        " Enable mouse usage (all modes)

" Source a global configuration file if available
if filereadable("/etc/vim/vimrc.local")
  source /etc/vim/vimrc.local
endif


" -- extend settings of vim ------------------------------------------------



"###########################################################################
" multi-encoding setting
"###########################################################################

if has("multi_byte")
"set bomb
set fileencodings=ucs-bom,utf-8,cp936,big5,euc-jp,euc-kr,latin1
" CJK environment detection and corresponding setting
if v:lang =~ "^zh_CN"
" Use cp936 to support GBK, euc-cn == gb2312
set encoding=cp936
set termencoding=cp936
set fileencoding=cp936
elseif v:lang =~ "^zh_TW"
" cp950, big5 or euc-tw
" Are they equal to each other?
set encoding=big5
set termencoding=big5
set fileencoding=big5
elseif v:lang =~ "^ko"
" Copied from someone's dotfile, untested
set encoding=euc-kr
set termencoding=euc-kr
set fileencoding=euc-kr
elseif v:lang =~ "^ja_JP"
" Copied from someone's dotfile, untested
set encoding=euc-jp
set termencoding=euc-jp
set fileencoding=euc-jp
endif
" Detect UTF-8 locale, and replace CJK setting if needed
if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
set encoding=utf-8
set termencoding=utf-8
set fileencoding=utf-8
endif
else
echoerr "Sorry, this version of (g)vim was not compiled with multi_byte"
endif




"###########################################################################
" Gerneral settings
"###########################################################################

" syntax highlighting
syntax on


" line number
"set number


" make tab = four spaces
set expandtab
set tabstop=4
set shiftwidth=4


" highlight search results and ignore case
set hlsearch
set ic


" make < and  > as a pair, useful in C++
set matchpairs+=<:>


" don't do auto indent while pasting
"set paste


" automatically read the file again when it changed outside vim
set autoread


" always show current position (replace this with statusline)
set ruler


set showmode


filetype plugin on
filetype indent on





"###########################################################################
" color settings
"###########################################################################

" colorscheme
colo pablo
" using ':colo [tab]' to change colorscheme



" number of colors 256
set t_Co=256


" change line (?)
set colorcolumn=80
hi ColorColumn ctermbg=red

set bg=dark






"###########################################################################
" statusline
"###########################################################################

set laststatus=2
set statusline=\ %F%m%r%h%w%=[%l,%3v]\ --%p%%--\ \  
hi  statusline ctermbg=darkblue








"###########################################################################
" key mappings
"###########################################################################

" F7 to close syntax high-lighting
map <F7> :if exists("syntax_on") <BAR>
\ syntax off <BAR><CR>
\ else <BAR>
\ syntax enable <BAR>
\ endif <CR>

" F9 to compile C/C++ files
au FileType cpp map <F9> :!g++ -std=c++0x -Wall -Wextra -pedantic -Ofast % -lm -o %:r<CR>
au FileType c map <F9> :!gcc -std=c99 -Wall -Wextra -pedantic -Ofast % -lm -o %:r<CR>

" K to lookup current word in perldoc
au FileType perl nmap K :!perldoc <cword> <bar><bar> perldoc -f <cword><CR><CR>

" F8 to run the program (without file type)
map <F8> :!./%:r<CR>

" F5 to run a script
map <F5> :!./%<CR>