phoenix-powerこの投稿はzsh Advent Calendar 2014の3日目の記事です。

はじめに

zshで個人的に使用頻度が高いものを紹介していきたいと思います。

ここで、まずは、前提としての基本的な説明を簡単に行います。

zsh は、shellの一種です。そして、 shell とは、kernelという核に命令を送り、または受け取る役割を担います。

kernel 及び、 UNIX の思想はとても単純で、1つのことを上手くやるプログラムの集合で出来上がっています。もちろん、例外はありますが、基本的には、あらゆるアプリがこの思想に基づいて構築されており、 shell に関しても同様です。

shell には、 bash, zsh, sh などがあります。

zsh では、~/.zshrcの設定ファイルが読み込まれ、任意に読み込むときは、source ~/.zshrcコマンドを実行します。再起動は、exec zshです。

また、いくつかの環境変数が設定されており、例えば、ホームディレクトリは$HOME、デフォルトシェルは$SHELLなどです。

詳しくは、man zshparamを見てください。

キーバインドは、bindkeyコマンドを実行しましょう。

また、プラグインなどをインストールする場所は、~/dotfiles/.zsh/pluginとします。

設定

一応、最初に全部入りのものを示します。その後、解説に移ります。

必要なもの

$ git clone https://github.com/rupa/z ~/dotfiles/.zsh/plugin/z

$ git clone https://github.com/zsh-users/zaw ~/dotfiles/.zsh/plugin/zaw

$ brew install go
$ pacman -S go

$ go get github.com/peco/peco/cmd/peco

設定ファイル

zshの設定ファイル、サンプル、.zshrc - Qiita

~/.zshrcLINK
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
# os : archlinux
# terminal : lilyterm
# font : ttf-dejavu
# source : https://gist.github.com/3feec5b12fcf07c6b64e

### export {{{
PATH=$PATH:$HOME/.rvm/bin
HISTFILE=~/.zsh_history
HISTSIZE=20000
SAVEHIST=20000
fpath=(~/.zsh/functions/ $fpath)
fpath=($HOME/.zsh/functions $fpath)
e_normal=`echo -e "¥033[0;30m"`
e_RED=`echo -e "¥033[1;31m"`
e_BLUE=`echo -e "¥033[1;36m"`

unset LSCOLORS
export EDITOR=/Applications/MacVim.app/Contents/MacOS/Vim
export BROWSER=w3m
export PATH=/usr/local/bin:$PATH
export LANG=ja_JP.UTF-8
export LESSCHARSET=utf-8
export EDITOR=vim
export PATH=$PATH:$HOME/local/bin:/usr/local/git/bin
export PATH=$PATH:$HOME/dotfiles/bin
export PATH=$PATH:/sbin:/usr/local/bin
export MANPATH=$MANPATH:/opt/local/man:/usr/local/share/man
export PATH="$PATH:$HOME/.rvm/bin"

[[ -s "$HOME/.pythonbrew/etc/bashrc" ]] && source "$HOME/.pythonbrew/etc/bashrc"

case "${OSTYPE}" in
    darwin*)
        export PATH=$PATH:/opt/local/bin:/opt/local/sbin
        export PATH=$PATH:/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources
        ;;
    freebsd*)
        case ${UID} in
            0)
                updateports()
                {
                    if [ -f /usr/ports/.portsnap.INDEX ]
                    then
                        portsnap fetch update
                    else
                        portsnap fetch extract update
                    fi
                    (cd /usr/ports/; make index)

                    portversion -v -l \<
                }
                alias appsupgrade='pkgdb -F && BATCH=YES NO_CHECKSUM=YES portupgrade -a'
                ;;
        esac
        ;;
esac
### }}}

### setopt {{{
setopt auto_cd
setopt auto_list
setopt auto_menu
setopt auto_param_keys
setopt auto_param_slash
setopt auto_pushd
setopt autopushd
setopt brace_ccl
setopt chase_links
setopt complete_aliases
setopt correct_all
setopt extended_glob
setopt globdots
setopt hist_ignore_all_dups
setopt hist_no_store
setopt hist_reduce_blanks
setopt inc_append_history
setopt list_packed
setopt list_types
setopt magic_equal_subst
setopt multios
setopt no_clobber
setopt noautoremoveslash
setopt nolistbeep
setopt path_dirs
setopt pushd_ignore_dups
setopt share_history
### }}}

### cdr {{{
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
zstyle ':completion:*:*:cdr:*:*' menu selection
zstyle ':completion:*' recent-dirs-insert both
zstyle ':chpwd:*' recent-dirs-max 500
zstyle ':chpwd:*' recent-dirs-default true
zstyle ':chpwd:*' recent-dirs-pushd true
### }}}

### color {{{
zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin
zstyle ':completion:*' list-colors di=34 fi=0
case "${TERM}" in
    xterm)
        export TERM=xterm-color

        ;;
    kterm)
        export TERM=kterm-color
        stty erase
        ;;

    cons25)
        unset LANG
        export LSCOLORS=ExFxCxdxBxegedabagacad

        export LS_COLORS='di=01;32:ln=01;35:so=01;32:ex=01;31:bd=46;34:cd=43;34:su=41;30:sg=46;30'
        zstyle ':completion:*' list-colors \
            'di=;36;1' 'ln=;35;1' 'so=;32;1' 'ex=31;1' 'bd=46;34' 'cd=43;34'
        ;;

    kterm*|xterm*)
        export CLICOLOR=1
        export LSCOLORS=ExFxCxDxBxegedabagacad

        zstyle ':completion:*' list-colors \
            'di=36' 'ln=35' 'so=32' 'ex=31' 'bd=46;34' 'cd=43;34'
        ;;

    dumb)
        echo "Welcome Emacs Shell"
        ;;
esac

autoload colors
colors
LS_COLORS="di=34:ln=35:so=32:pi=33:ex=31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30"
export LS_COLORS

if [ -f ~/.dircolors ]; then
    if type dircolors > /dev/null 2>&1; then
        eval $(dircolors ~/.dircolors)
    elif type gdircolors > /dev/null 2>&1; then
        eval $(gdircolors ~/.dircolors)
    fi
fi

### }}}

### autoload, zstyle {{{
#HELPDIR=/usr/local/share/zsh/helpfiles
#alias run-help >/dev/null 2>&1 && unalias run-help
autoload -Uz run-help
autoload -Uz run-help-git
autoload -Uz run-help-svn
autoload -Uz run-help-svk
autoload -Uz run-help-openssl
autoload -Uz run-help-p4
autoload -Uz run-help-sudo
autoload zed
autoload predict-on
autoload history-search-end
autoload -Uz select-word-style
select-word-style default
autoload -Uz zmv
autoload -U url-quote-magic
autoload -U compinit
compinit
zstyle ':zle:*' word-chars " _-./;@"
zstyle ':zle:*' word-style unspecified
zstyle ':completion:*:default' menu select=1
zstyle ':completion:history-words:*' list no
zstyle ':completion:history-words:*' menu yes
zstyle ':completion:history-words:*' remove-all-dups yes
bindkey "\e/" _history-complete-older
bindkey "\e," _history-complete-newer

zstyle ':filter-select' max-lines $(($LINES / 2))
zstyle ':completion:*' verbose yes
zstyle ':completion:*' completer _expand _complete _match _prefix _approximate _list _history
zstyle ':completion:*:messages' format '%F{YELLOW}%d'$DEFAULT
zstyle ':completion:*:warnings' format '%F{RED}No matches for:''%F{YELLOW} %d'$DEFAULT
zstyle ':completion:*:descriptions' format '%F{YELLOW}completing %B%d%b'$DEFAULT
zstyle ':completion:*:options' description 'yes'
zstyle ':completion:*' group-name ''
zstyle ':completion:*' use-cache true
zstyle ':completion:*' list-separator '-->'
zstyle ':completion:*:manuals' separate-sections true
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
if [ -n "$LS_COLORS" ]; then
    zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
fi
### }}}

### magick {{{
typeset -A abbreviations
abbreviations=(
"L"    "| $PAGER"
"G"    "| grep"

"HEAD^"     "HEAD\\^"
"HEAD^^"    "HEAD\\^\\^"
"HEAD^^^"   "HEAD\\^\\^\\^"
"HEAD^^^^"  "HEAD\\^\\^\\^\\^\\^"
"HEAD^^^^^" "HEAD\\^\\^\\^\\^\\^"
)

magic-abbrev-expand () {
    local MATCH
    LBUFFER=${LBUFFER%%(#m)[-_a-zA-Z0-9^]#}
    LBUFFER+=${abbreviations[$MATCH]:-$MATCH}
}

magic-abbrev-expand-and-insert () {
    magic-abbrev-expand
    zle self-insert
}

magic-abbrev-expand-and-accept () {
    magic-abbrev-expand
    zle accept-line
}

no-magic-abbrev-expand () {
    LBUFFER+=' '
}

zle -N magic-abbrev-expand
zle -N magic-abbrev-expand-and-insert
zle -N magic-abbrev-expand-and-accept
zle -N no-magic-abbrev-expand
bindkey "\r"  magic-abbrev-expand-and-accept
bindkey "^J"  accept-line
bindkey " "   magic-abbrev-expand-and-insert
bindkey "."   magic-abbrev-expand-and-insert
bindkey "^x " no-magic-abbrev-expand

function rmf(){
for file in $*
do
    __rm_single_file $file
done
}

function __rm_single_file(){
if ! [ -d ~/.Trash/ ]
then
    command /bin/mkdir ~/.Trash
fi

if ! [ $# -eq 1 ]
then
    echo "__rm_single_file: 1 argument required but $# passed."
    exit
fi

if [ -e $1 ]
then
    BASENAME=`basename $1`
    NAME=$BASENAME
    COUNT=0
    while [ -e ~/.Trash/$NAME ]
    do
        COUNT=$(($COUNT+1))
        NAME="$BASENAME.$COUNT"
    done

    command /bin/mv $1 ~/.Trash/$NAME
else
    echo "No such file or directory: $file"
fi
}

zle -N self-insert url-quote-magic
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end

# }}}

### directory {{{

function chpwd() { ls -aCFG }

function mkcd() {
if [[ -d $1 ]]; then
    echo "It already exsits! Cd to the directory."
    cd $1
else
    echo "Created the directory and cd to it."
    mkdir -p $1 && cd $1
fi
}

function cdup_dir() {
if [[ -z "$BUFFER" ]]; then
    echo
    cd ..
    ls -aF
    zle reset-prompt
else
    zle self-insert 'k'
fi
 }
 zle -N cdup_dir
 bindkey '^k' cdup_dir

 function cddown_dir(){
 com='$SHELL -c "ls -AF . | grep / "'
 while [ $? = 0 ]
 do
     cdir=`eval $com | peco`
     if [ $? = 0 ];then
         cd $cdir
         eval $com
     else
         break
     fi
 done
 zle reset-prompt
}
zle -N cddown_dir
bindkey '^j' cddown_dir

### }}}

### stack {{{

local p_buffer_stack=""
local -a buffer_stack_arr

function make_p_buffer_stack()
{
    if [[ ! $#buffer_stack_arr > 0 ]]; then
        p_buffer_stack=""
        return
    fi
    p_buffer_stack="%F{black} $buffer_stack_arr %f"
}


show_buffer_stack() {
    POSTDISPLAY="
    stack: $LBUFFER"
    zle push-line-or-edit
}
zle -N show_buffer_stack
setopt noflowcontrol
bindkey '^Q' show_buffer_stack
### }}}

### golang {{{

if [ -x "`which go`" ]; then
  export GOPATH=$HOME/go
  export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
fi

### }}}

### clipboard {{{
## pbcopy
case ${OSTYPE} in
  linux*)
    if [ ! -f /usr/bin/xsel ];then
      sudo pacman -S xsel
    fi
    alias pbcopy='xsel --clipboard --input'
    ;;
  cygwin*)
    alias pbcopy='putclip'
    ;;
esac

## buffer
pbcopy-buffer(){
  case ${OSTYPE} in
    freebsd*|darwin*)
      print -rn $BUFFER | pbcopy
      ;;
    linux*)
      print -rn $BUFFER | xclip -i -selection clipboard
      ;;
    cygwin*)
      print -rn $BUFFER | putclip
      ;;
  esac
  zle -M "copy : ${BUFFER}"
}
zle -N pbcopy-buffer
bindkey '^p^p' pbcopy-buffer

## alias
if which pbcopy >/dev/null 2>&1 ; then
  # Mac
  alias -g C='| pbcopy'
elif which xclip >/dev/null 2>&1 ; then
  # Linux
  alias -g C='| xclip --input --clipboard'
elif which putclip >/dev/null 2>&1 ; then
  # Cygwin
  alias -g C='| putclip'
fi

## bindkey
# bindkey -s '^b' " | pbcopy"

## clipboard-history
function clipboard-history (){
case $OSTYPE in
  linux*)
    if [ ! -f /usr/bin/anamnesis ];then
      sudo yaourt -S anamnesis
    fi
    anamnesis -l 100 | sed -n '3,100p' | peco | cut -d u -f 2- | head -c -3 | tail -c +2  | xclip -i -selection clipboard
    ;;
  freebsd*|darwin*)
    plutil -convert xml1 ~/Library/Application\ Support/ClipMenu/clips.data -o - | parsrx.sh | grep '/plist/dict/array/string ' | sed '1,2d' | sed 's/\/plist\/dict\/array\/string//g' | peco | pbcopy
    ;;
esac
}
zle -N clipboard-history
bindkey '^[c' clipboard-history
### }}}

### stack {{{
function show_buffer_stack() {
POSTDISPLAY="
stack: $LBUFFER"
zle push-line-or-edit
}
zle -N show_buffer_stack
setopt noflowcontrol
bindkey '^Q' show_buffer_stack
### }}}

### open {{{
function openapp() {
case ${OSTYPE} in
  freebsd*|darwin*)
    BUFFER="open -a "
    ;;
  linux*)
    BUFFER="xdg-open "
    #BUFFER="gnome-open "
    ;;
  cygwin*)
    BUFFER="cygstart "
    ;;
esac
CURSOR=$#BUFFER
}
zle -N openapp
bindkey '^o' openapp
# bindkey -s '^o' "open -a "
### }}}

### history {{{
case $OSTYPE in
    linux*)
        function peco-select-history() {
        local tac
        if which tac > /dev/null; then
            tac="tac"
        else
            tac="tail -r"
        fi
        BUFFER=$(\history -rn 1 | \
            eval $tac | \
            peco --query "$LBUFFER")
        CURSOR=$#BUFFER
        zle clear-screen
    }
    ;;
darwin*)
    function peco-select-history() {
    BUFFER=`history -rn 1 | peco`
    CURSOR=$#BUFFER
    zle clear-screen
}
;;
esac
zle -N peco-select-history
bindkey '^h^j' peco-select-history
### }}}

### markdown {{{
function markdown_preview(){
if [ $# -ne 1 ]
then
    echo "error: invalid arguments"
    echo "usage: $0 markdown_file"
    return 1
fi

if [ ! -f "$1" ]
then
    echo "error: $1 dose not exists"
    return 2
fi

(echo '<html><head><meta charset="UTF-8" /></head><body>';
markdown $1; echo '</body></html>')\
    | w3m -T text/html -dump

if [ $STY ]
then
    sleep 0.2
    screen -X redisplay
fi
}
### }}}

### virtualbox {{{
function vm (){
#zsh -c "ls -A ~/VirtualBox\ VMs/" | peco
vbi=`zsh -c "ls -A ~/VirtualBox\ VMs/ | tr ' ' '\n'"`
case $1 in
    [aA]rch*|[mM]ac*)
        echo $vbi | grep $1
        VBoxManage startvm `echo $vbi | grep $1`
        ;;
    "")
        echo $vbi | grep win
        echo win
        VBoxManage startvm `echo $vbi | grep win`
        ;;
    -a)
        echo $vbi | tr '\n' ' '
        VBoxManage startvm `echo $vbi | tr '\n' ' '`
    ;;
    *)
        VBoxManage startvm `echo "$vbi" | peco`
        ;;
esac
}

function vm-window (){
osascript << EOF

--tell application "System Events"
--  tell process "VirtualBoxVM"
--    every UI element
--  end tell
--end tell

tell app "VirtualBoxVM"
activate
end tell
EOF
}

### }}}

### tmux {{{

## auto-start
case $OSTYPE in
    darwin*)
        if [ -z "$SSH_CONNECTION" -a ${UID} -ne 0 -a -z "$TMUX" -a -z "$STY" ]; then
            if type tmux >/dev/null 2>&1; then
                tmux
            elif type tmux >/dev/null 2>&1; then
                if tmux has-session && tmux list-sessions | egrep -q '.*]$'; then
                    tmux attach && echo "tmux attached session "
                else
                    tmux new-session && echo "tmux created new session"
                fi
            elif type screen >/dev/null 2>&1; then
                screen -rx || screen -D -RR
            fi
        fi
        ;;
    linux*)
        if [ -z "$TMUX" -a -z "$STY" ]; then
            if type tmux >/dev/null 2>&1; then
                if tmux has-session && tmux list-sessions | /usr/bin/grep -qE '.*]$'; then
                    tmux -2 attach && echo "tmux attached session "
                else
                    tmux -2 new-session && echo "tmux created new session"
                fi
            fi
        fi
        ;;
esac

##copy-mode
function tmux-copy-line () {
tmux copy-mode\; send-keys 2k0Vj Enter
}
zle -N tmux-copy-line
bindkey '^[n' tmux-copy-line

function tmux-copy-all () {
tmux copy-mode\; send-keys ggVG Enter
#tmux copy-mode\; send-keys Space\; send-keys '$'\; send-keys Enter
}
zle -N tmux-copy-all
bindkey '^[m' tmux-copy-all
### }}}

### alias {{{
alias lf="ls -F"
alias ll="ls -l"
alias 'ps?'='pgrep -l -f'
alias pk='pkill -f'
alias du="du -h"
alias duh="du -h ./ --max-depth=1"
alias su="su -l"
alias 'src'='exec zsh'
alias -g V="| vim -"
alias -g EV="| xargs --verbose sh -c 'vim \"\$@\" < /dev/tty'"
alias -g RET="RAILS_ENV=test"
alias -g RED="RAILS_ENV=development"
alias -g REP="RAILS_ENV=production"
alias raket='RAILS_ENV=test rake'
alias raked='RAILS_ENV=development rake'
alias rakep='RAILS_ENV=production rake'
alias ccat='pygmentize -O style=vim -f console256 -g'
alias less='less -r'
alias df='df -h'
alias free='free -m'
alias 'gr'='grep --color=auto -ERUIn'
alias 'm'='make'
alias 'mn'='make native-code'
alias 'mc'='make clean'
alias sc='screen -S main'
alias sn='screen'
alias sl='screen -ls'
alias sr='screen -r main'
alias srr='screen -U -D -RR'
alias tma='tmux attach'
alias tma0='tmux attach -t 0'
alias tma1='tmux attach -t 1'
alias tma2='tmux attach -t 2'
alias tml='tmux list-sessions'
alias pon='predict-on'
alias poff='predict-off'
alias cp='nocorrect cp -irp'
alias refe='nocorrect refe'
alias g='git'
alias gi='git'
alias oppai='git'
alias gs='git status -s -b'
alias gst='git status -s -b'
alias gc='git commit'
alias gci='git commit -a'
alias java='nocorrect java'
alias erl='nocorrect erl'
alias sbcl='nocorrect sbcl'
alias gosh='nocorrect gosh'
alias node='nocorrect node'
alias scala='scala -deprecation -unchecked -explaintypes'
alias scc='scalac -deprecation -unchecked -explaintypes'
alias sci='scala -deprecation -unchecked -explaintypes -cp $SCALA_CLASSPATH -i ~/import.scala'
alias sce='scala'
alias ex='extract'
alias be='bundle exec'
alias grv='grepvim'
alias dircolors="gdircolors"
alias zmv='noglob zmv -W'
alias ls="ls -a"
alias msf='cd /opt/msf/ && ./msfconsole'
alias p="qlmanage -p "$@" >& /dev/null"
alias gotr="altr"
alias trash="sudo rm -rf ~/.Trash/"
alias qm='qlmanage -p "$@" >& /dev/null'
alias st='/Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl'
alias qrank="w3m http://qrank.wbsrv.net/"
alias color-terminal='for c in {000..255}; do echo -n "\e[38;5;${c}m $c" ; [ $(($c%16)) -eq 15 ] && echo;done;echo'
alias ds.store="sudo find ./ -name '.DS_Store' -delete"
alias rgen="rake generate && rake preview"
alias where="command -v"
alias remem='du -sx / &> /dev/null & sleep 5 && kill $!'
alias mf='sudo purge'
alias vs='vim ~/.vimrc'
alias zs='vim ~/.zshrc'
alias ts='vim ~/.tmux.conf'
alias zr='source ~/.zshrc && exec $SHELL'
alias zd='vim ~/dotfiles/.zshrc'
alias vim-trans='vim -c "ExciteTranslate"'
alias gistvim='vim * -c "bufdo %s/foo/bar/g | Gist"'
alias f='vim +VimFiler'
alias w3mjman='W3MMAN_MAN=jman w3mman'
alias w3h='rm ~/.w3m/history && w3m -N'
alias gd='dirs -v; echo -n "select number: "; read newdir; cd +"$newdir"'

case $OSTYPE in
    darwin*)
        #/Applications/VLC.app/Contents/MacOS/VLC -I rc
        # interface:ncurses, speed:2
        alias sy='open -a "system preferences"'
        alias vlc0='/Applications/VLC.app/Contents/MacOS/VLC --rate=2 && sleep 3;reset'
        alias vlc1='killall -KILL VLC'
        alias ctags="`brew --prefix`/usr/local/bin/ctags"
        alias up="brew update && brew upgrade"
        alias ll='gls -slhAF --color'
        alias gls='gls -lAFh --color=auto'
        eval `dircolors ~/dotfiles/dircolors-solarized/dircolors.ansi-dark`
        ;;
    linux*)
        alias up="sudo pacman -Syu && sudo yaourt -Syu"
        alias vim="/usr/bin/vim"
        ;;
esac

        if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi

### }}}

### download {{{

export DOTFILE=$HOME/dotfiles
export PLUGIN=$DOTFILE/.zsh/plugin

## completion
if [ ! -d $PLUGIN/zsh-completions ];then
    git clone git://github.com/zsh-users/zsh-completions $PLUGIN/zsh-completions
fi
fpath=($PLUGIN/zsh-completions/src $fpath)

## powerline {{{
if [ ! -f $PLUGIN/powerline.zsh ];then
    curl https://gist.githubusercontent.com/syui/e3fad84e3dba8a3f667b/raw/powerline.zsh -o $PLUGIN/powerline.zsh
fi

if [ ! -d $PLUGIN/powerline-bash ];then
    git clone https://github.com/milkbikis/powerline-bash $PLUGIN/powerline-bash
fi

#ln -s $PLUGIN/powerline-bash/powerline-bash.py ~/powerline-bash.py
#
#function powerline_precmd() {
#export PS1="$(~/powerline-bash.py $? --shell zsh)"
#        }
#
#        function install_powerline_precmd() {
#        for s in "${precmd_functions[@]}"; do
#            if [ "$s" = "powerline_precmd" ]; then
#                return
#            fi
#        done
#        precmd_functions+=(powerline_precmd)
#    }
#
#    install_powerline_precmd
## }}}

## tmux-powerline
# iTerm : Treat ambiguous-width characters as double width
case $OSTYPE in
    darwin*)
        if ! type tmux > /dev/null 2>&1;then
            brew tap waltarix/homebrew-customs
            brew update
            brew install waltarix/customs/tmux
        fi
    ;;
esac

if type tmux > /dev/null 2>&1;then
    if [ ! -d $DOTFILE/.tmux/tmux-powerline ];then
        git clone https://github.com/erikw/tmux-powerline $DOTFILE/.tmux/tmux-powerline
    fi
    if [ ! -d $DOTFILE/.tmux/tmux-colors-solarized ];then
        git clone https://github.com/seebi/tmux-colors-solarized $DOTFILE/.tmux/tmux-colors-solarized
    fi
fi

if [ ! -f $DOTFILE/.tmux/tmux-powerline/segments/used-mem ];then
    curl https://raw.githubusercontent.com/yonchu/used-mem/master/used-mem -o $DOTFILE/.tmux/tmux-powerline/segments/used-mem
    chmod +x $DOTFILE/.tmux/tmux-powerline/segments/used-mem
fi

if [ ! -f $DOTFILE/.tmux/tmux-powerline/segments/mplayer_tmux.sh ];then
    curl https://raw.githubusercontent.com/syui/mplayer_script/master/mplayer_tmux.sh -o $DOTFILE/.tmux/tmux-powerline/segments/mplayer_tmux.sh
    chmod +x $DOTFILE/.tmux/tmux-powerline/segments/mplayer_tmux.sh
fi

if [ ! -f $DOTFILE/.tmux/.tmux.conf.mac ];then
    curl https://gist.githubusercontent.com/syui/5c49d1296c992d8af737/raw/.tmux.conf.mac -o $DOTFILE/.tmux/.tmux.conf.mac
fi

## vim
if [ ! -d ~/.vim/bundle/neobundle.vim ];then
    curl https://raw.githubusercontent.com/Shougo/neobundle.vim/master/bin/install.sh | sh
fi

## oh-my-zsh
if [ ! -d $PLUGIN/oh-my-zsh ];then
    git clone https://github.com/robbyrussell/oh-my-zsh $PLUGIN/oh-my-zsh
fi

## cheat-sheet
if [ -f $PLUGIN/oh-my-zsh/templates/zshrc.zsh-template ];then
    cheat-sheet () { zle -M "`cat ~/dotfiles/.zsh/cheat-sheet`" }
    zle -N cheat-sheet
    # bindkey "^[^h" cheat-sheet
fi

## golang
if [ ! -f ~/dotfiles/.zsh/plugin/golang-crosscompile/crosscompile.bash ];then
  git clone https://github.com/davecheney/golang-crosscompile ~/dotfiles/.zsh/plugin/golang-crosscompile
fi

## growl
if [ ! -f ~/dotfiles/.zsh/plugin/growl.zsh ];then
       curl https://raw.githubusercontent.com/patbenatar/dotfiles/master/zsh/growl.zsh -o $HOME/dotfiles/.zsh/plugin/growl.zsh
  chmod +x ~/dotfiles/.zsh/plugin/growl.zsh
fi

## rupa/z
case $OSTYPE in
  drawin*)
    if [ -f `brew --prefix`/etc/profile.d/z.sh ];then
      brew install z
    fi
    . `brew --prefix`/etc/profile.d/z.sh
    ;;
  linux*)
    if [ ! -d ~/dotfiles/.zsh/plugin/z ];then
      git clone https://github.com/rupa/z ~/dotfiles/.zsh/plugin/z
    fi
    . ~/dotfiles/.zsh/plugin/z/z.sh
    ;;
esac

## _z  {{{
if ! type _z > /dev/null 2>&1;then
_z () {
  local datafile="${_Z_DATA:-$HOME/.z}"
  [ -z "$_Z_OWNER" -a -f "$datafile" -a ! -O "$datafile" ] && return
  if [ "$1" = "--add" ]
  then
    shift
    [ "$*" = "$HOME" ] && return
    local exclude
    for exclude in "${_Z_EXCLUDE_DIRS[@]}"
    do
      [ "$*" = "$exclude" ] && return
    done
    local tempfile="$datafile.$RANDOM"
    while read line
    do
      [ -d "${line%%\|*}" ] && echo $line
    done < "$datafile" | awk -v path="$*" -v now="$(date +%s)" -F"|" '
            BEGIN {
                rank[path] = 1
                time[path] = now
            }
            $2 >= 1 {
                # drop ranks below 1
                if( $1 == path ) {
                    rank[$1] = $2 + 1
                    time[$1] = now
                } else {
                    rank[$1] = $2
                    time[$1] = $3
                }
                count += $2
            }
            END {
                if( count > 9000 ) {
                    # aging
                    for( x in rank ) print x "|" 0.99*rank[x] "|" time[x]
                } else for( x in rank ) print x "|" rank[x] "|" time[x]
            }
        ' 2> /dev/null >| "$tempfile"
    if [ $? -ne 0 -a -f "$datafile" ]
    then
      env rm -f "$tempfile"
    else
      [ "$_Z_OWNER" ] && chown $_Z_OWNER:$(id -ng $_Z_OWNER) "$tempfile"
      env mv -f "$tempfile" "$datafile" || env rm -f "$tempfile"
    fi
  elif [ "$1" = "--complete" -a -s "$datafile" ]
  then
    while read line
    do
      [ -d "${line%%\|*}" ] && echo $line
    done < "$datafile" | awk -v q="$2" -F"|" '
            BEGIN {
                if( q == tolower(q) ) imatch = 1
                q = substr(q, 3)
                gsub(" ", ".*", q)
            }
            {
                if( imatch ) {
                    if( tolower($1) ~ tolower(q) ) print $1
                } else if( $1 ~ q ) print $1
            }
        ' 2> /dev/null
  else
    while [ "$1" ]
    do
      case "$1" in
        (--) while [ "$1" ]
          do
            shift
            local fnd="$fnd${fnd:+ }$1"
          done ;;
        (-*) local opt=${1:1}
          while [ "$opt" ]
          do
            case ${opt:0:1} in
              (c) local fnd="^$PWD $fnd" ;;
              (h) echo "${_Z_CMD:-z} [-chlrtx] args" >&2
                return ;;
              (x) sed -i -e "\:^${PWD}|.*:d" "$datafile" ;;
              (l) local list=1 ;;
              (r) local typ="rank" ;;
              (t) local typ="recent" ;;
            esac
            opt=${opt:1}
          done ;;
        (*) local fnd="$fnd${fnd:+ }$1" ;;
      esac
      local last=$1
      shift
    done
    [ "$fnd" -a "$fnd" != "^$PWD " ] || local list=1
    case "$last" in
      (/*) [ -z "$list" -a -d "$last" ] && cd "$last" && return ;;
    esac
    [ -f "$datafile" ] || return
    local cd
    cd="$(while read line; do
            [ -d "${line%%\|*}" ] && echo $line
        done < "$datafile" | awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
            function frecent(rank, time) {
                # relate frequency and time
                dx = t - time
                if( dx < 3600 ) return rank * 4
                if( dx < 86400 ) return rank * 2
                if( dx < 604800 ) return rank / 2
                return rank / 4
            }
            function output(files, out, common) {
                # list or return the desired directory
                if( list ) {
                    cmd = "sort -n >&2"
                    for( x in files ) {
                        if( files[x] ) printf "%-10s %s\n", files[x], x | cmd
                    }
                    if( common ) {
                        printf "%-10s %s\n", "common:", common > "/dev/stderr"
                    }
                } else {
                    if( common ) out = common
                    print out
                }
            }
            function common(matches) {
                # find the common root of a list of matches, if it exists
                for( x in matches ) {
                    if( matches[x] && (!short || length(x) < length(short)) ) {
                        short = x
                    }
                }
                if( short == "/" ) return
                # use a copy to escape special characters, as we want to return
                # the original. yeah, this escaping is awful.
                clean_short = short
                gsub(/[\(\)\[\]\|]/, "\\\\&", clean_short)
                for( x in matches ) if( matches[x] && x !~ clean_short ) return
                return short
            }
            BEGIN {
                gsub(" ", ".*", q)
                hi_rank = ihi_rank = -9999999999
            }
            {
                if( typ == "rank" ) {
                    rank = $2
                } else if( typ == "recent" ) {
                    rank = $3 - t
                } else rank = frecent($2, $3)
                if( $1 ~ q ) {
                    matches[$1] = rank
                } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
                if( matches[$1] && matches[$1] > hi_rank ) {
                    best_match = $1
                    hi_rank = matches[$1]
                } else if( imatches[$1] && imatches[$1] > ihi_rank ) {
                    ibest_match = $1
                    ihi_rank = imatches[$1]
                }
            }
            END {
                # prefer case sensitive
                if( best_match ) {
                    output(matches, best_match, common(matches))
                } else if( ibest_match ) {
                    output(imatches, ibest_match, common(imatches))
                }
            }
        ')"
    [ $? -gt 0 ] && return
    [ "$cd" ] && cd "$cd"
  fi
}
fi
### }}}

compctl -U -K _z_zsh_tab_completion ${_Z_CMD:-z}


## zaw/zaw
if [ ! -d ~/dotfiles/.zsh/plugin/zaw ];then
  git clone https://github.com/zsh-users/zaw ~/dotfiles/.zsh/plugin/zaw
fi
if [ ! -f ~/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh ];then
  curl https://raw.githubusercontent.com/lovingly/dotfiles/master/zsh.d/zaw/zaw-z.zsh -o $HOME/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh
  chmod +x $HOME/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh
fi

## syui/airchrome.zsh
if [ ! -f $PLUGIN/airchrome.zsh/airchrome.zsh ];then
    git clone https://github.com/syui/airchrome.zsh $PLUGIN/airchrome.zsh
fi

## syntax-highlight
if [ ! -f $HOME/dotfiles/.zsh/plugin/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ];then
  git clone https://github.com/zsh-users/zsh-syntax-highlighting $HOME/dotfiles/.zsh/plugin/zsh-syntax-highlighting
fi
### }}}

### source {{{

#source $PLUGIN/oh-my-zsh

source ~/dotfiles/.zsh/plugin/golang-crosscompile/crosscompile.bash
source ~/dotfiles/.zsh/plugin/zaw/zaw.zsh
source $HOME/dotfiles/.zsh/plugin/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

[ -f ~/.zshrc.local ] && source ~/.zshrc.local

[ -s ${HOME}/.rvm/scripts/rvm ] && source ${HOME}/.rvm/scripts/rvm

case $OSTYPE in
    darwin*)
        source $PLUGIN/airchrome.zsh/airchrome.zsh
        source $PLUGIN/growl.zsh
    ;;
esac

unsetopt sh_word_split

### }}}

### bindkey {{{

bindkey -M viins 'jj' vi-cmd-mode
bindkey "^I" menu-complete
bindkey '^h^h' run-help
bindkey -s '^o^o' 'vim `zsh -c "ls -A" | peco`'
bindkey -s '^o' "open -a "
bindkey "^[u" undo
bindkey "^[r" redo
bindkey '^]'   vi-find-next-char
bindkey '^[^]' vi-find-prev-char
bindkey "^?" backward-delete-char
bindkey -a 'q' push-line
bindkey "^p" history-beginning-search-backward-end
bindkey "^n" history-beginning-search-forward-end
bindkey "\\ep" history-beginning-search-backward-end
bindkey "\\en" history-beginning-search-forward-end

bindkey '^[[7~' beginning-of-line
bindkey '^[[8~' end-of-line
bindkey '^[[2~' overwrite-mode
bindkey '^[[3~' delete-char
bindkey '^[[A'  up-line-or-history
bindkey '^[[B'  down-line-or-history
bindkey '^[[C'  forward-char
bindkey '^[[D'  backward-char
bindkey '^[[5~' history-beginning-search-backward
bindkey '^[[6~' history-beginning-search-forward

## zaw {{{
bindkey '^x' zaw
bindkey '^h' zaw-history
bindkey '^@' zaw-gitdir
bindkey '^r' zaw-open-file
bindkey '^j^j' zaw-cdr
bindkey '^j^k' zaw-z
### }}}

### }}}

### function {{{
ex() {
  if [ -f $1 ] ; then
    case $1 in
      *.tar.bz2)   tar xjf $1   ;;
      *.tar.gz)    tar xzf $1   ;;
      *.bz2)       bunzip2 $1   ;;
      *.rar)       unrar x $1     ;;
      *.gz)        gunzip $1    ;;
      *.tar)       tar xf $1    ;;
      *.tbz2)      tar xjf $1   ;;
      *.tgz)       tar xzf $1   ;;
      *.zip)       unzip $1     ;;
      *.Z)         uncompress $1;;
      *.7z)        7z x $1      ;;
      *)           echo "'$1' cannot be extracted via ex()" ;;
    esac
  else
    echo "'$1' is not a valid file"
  fi
}

grepvim() {
    XFS=`grep -ERUInl $* | uniq | xargs`
    if [ "$XFS" ] ; then
        vim `grep -ERUInl $* | uniq | xargs`
    fi
}

function gte() {
google_translate "$*" "en-ja"
}

function gtj() {
google_translate "$*" "ja-en"
}

function google_translate() {
local str opt cond

if [ $# != 0 ]; then
    str=`echo $1 | sed -e 's/  */+/g'` # 1文字以上の半角空白を+に変換
    cond=$2
    if [ $cond = "ja-en" ]; then
        # ja -> en 翻訳
        opt='?hl=ja&sl=ja&tl=en&ie=UTF-8&oe=UTF-8'
    else
        # en -> ja 翻訳
        opt='?hl=ja&sl=en&tl=ja&ie=UTF-8&oe=UTF-8'
    fi
else
    opt='?hl=ja&sl=en&tl=ja&ie=UTF-8&oe=UTF-8'
fi

opt="${opt}&text=${str}"
w3m +13 "http://translate.google.com/${opt}"
}
function make() {
LANG=C command make "$@" 2>&1 | sed -e "s@[Ee]rror:.*@$e_RED&$e_normal@g" -e "s@cannot¥sfind.*@$e_RED&$e_normal@g" -e "s@[Ww]arning:.*@$e_BLUE&$e_normal@g"
}
function cwaf() {
LANG=C command ./waf "$@" 2>&1 | sed -e "s@[Ee]rror:.*@$e_RED&$e_normal@g" -e "s@cannot¥sfind.*@$e_RED&$e_normal@g" -e "s@[Ww]arning:.*@$e_BLUE&$e_normal@g"
}

expand-to-home-or-insert () {
    if [ "$LBUFFER" = "" -o "$LBUFFER[-1]" = " " ]; then
        LBUFFER+="~/"
    else
        zle self-insert
    fi
}

function separate(){
echo -n $fg_bold[yellow]
for i in $(seq 1 $COLUMNS); do
    echo -n '~'
done
echo -n $reset_color
}

function vol(){
osascript -e "set Volume ${1}"
}
function manowar () {
mpc volume 100
amixer set PCM 100%
}
function torrent-search(){w3m "http://torrentz.eu/search?f=$1"}
function vmu(){VBoxManage storageattach $1 --storagectl ${1}sata1 --port 2 --type dvddrive --medium emptydrive}
function exdel(){exiftool -overwrite_original -all= $1}

function zman() {
PAGER="less -g -s '+/^       "$1"'" man zshall
}

function ccleaner(){
which ccleaner.scpt | xargs osascript &
open -a iterm2-f
}

function gif_make(){
gm convert *.png hoge.gif
rm *.png
}

function markpre(){
watchmedo shell-command -c "qlmanage -p $1" $HOME/blog/
}

function wifi(){
if networksetup -getairportnetwork en0 | grep off; then
    echo on
    networksetup -setairportpower en0 on
else
    echo off
    networksetup -setairportpower en0 off
fi
}

function aunpack-all(){for i in `ls *.$1`;do aunpack $i;done}

function twitter () {
osascript -e 'tell application "Twitter" to close window 1'
}

function unrar-all (){
for i in *.part1.rar
do
    unrar e -o+ $i
done
}

### git init {{{
#touch README.md
#git init
#git add README.md
#git commit -m "first commit"
#git remote add origin https://github.com/syui/syui.github.io.git
#git push -u origin master
### }}}

function gitinit(){
echo -n username:
user=`echo $USER`
repo=`echo $PWD:t`
repo_j={\"name\":\"$repo\"}
url="https://github.com/"$user/$repo.git
curl -u $user https://api.github.com/user/repos -d $repo_j
case $? in
    0)
        rm -rf .git
        rm -rf .DS_Store
        git init
        echo $url
        git remote add origin $url
        git add .
        git commit --allow-empty -m "noun"
        git push -u origin master
        ;;
esac
}

globalias() {
    if [[ $LBUFFER =~ ' [A-Z0-9]+$' ]]; then
        zle _expand_alias
        zle expand-word
    fi
    zle self-insert
}
zle -N globalias
bindkey " " globalias
bindkey "^ " magic-space           # control-space to bypass completion
bindkey -M isearch " " magic-space # normal space during searches


#function help-peco (){
#  s=`run-help | tail -n +2 | tr ' ' '\n' | sed '/^$/d' | peco`
#  man $s
#}
#zle -N help-peco

function au(){
case $1 in
    -o|*)
        SwitchAudioSource -a | grep output | cut -d '(' -f 1 | sed -e 's/ *$//' -e 's/$/"/g' -e 's/^/"/g' | peco | xargs -J % SwitchAudioSource -s %
        ;;
    -i)
        SwitchAudioSource -a | grep input | cut -d '(' -f 1 | sed -e 's/ *$//' -e 's/$/"/g' -e 's/^/"/g' | peco | xargs -J % SwitchAudioSource -t input -s %
        ;;
esac
#zle reset-prompt
}
zle -N au
bindkey '\^^' au

### }}}

### google {{{

function google-search() {
local str opt
if [ $ != 0 ]; then
    for i in $*; do
        str="$str+$i"
    done
    str=`echo $str | sed 's/^\+//'`
    opt='search?num=50&hl=ja&lr=lang_ja'
    opt="${opt}&q=${str}"
fi
w3m http://www.google.co.jp/$opt
}

function goy() {
local str opt
if [ $ != 0 ]; then
    for i in $*; do
        str="$str+$i"
    done
    str=`echo $str | sed 's/^\+//'`
    opt='search?num=50&hl=ja&lr=lang_ja'
    opt="${opt}&q=${str}"
    tbs='&tbs=qdr:y'
fi
w3m http://www.google.co.jp/$opt$tbs
}

function gom() {
local str opt
if [ $ != 0 ]; then
    for i in $*; do
        str="$str+$i"
    done
    str=`echo $str | sed 's/^\+//'`
    opt='search?num=50&hl=ja&lr=lang_ja'
    opt="${opt}&q=${str}"
    tbs='&tbs=qdr:m'
fi
w3m http://www.google.co.jp/$opt$tbs
}

# w3mでALC検索
function alc() {
if [ $ != 0 ]; then
    w3m "http://eow.alc.co.jp/$*/UTF-8/?ref=sa"
else
    w3m "http://www.alc.co.jp/"
fi
}



#>>>
function youtube-post(){
mkdir -p ~/Movies/youtube
google youtube post ~/Movies/youtube/*.mp4 --category People --tags "blog"
google youtube list --delimiter ','
}

functions mod(){
mkdir ~/Music/speed
cd ~/Music/speed && touch mylist.test && rm mylist* && mylist && mplayer -playlist mylist -speed 2 -af scaletempo,volnorm
}

# w3mでyoutube検索
function youtube-search() {
if [ $ != 0 ]; then
    w3m "http://www.youtube.com/results?search_query=$*&search_type=&aq=f"
else
    w3m "http://youtube.com/"
fi
}

# google booksの検索
function book-search() {
local str opt
if [ $ != 0 ]; then
    for i in $*; do
        str="$str+$i"
    done
    str=`echo $str | sed 's/^\+//'`
    opt='search?lr=lang_ja&hl=JA&tbo=p&tbm=bks&tbs=,bkv:p&num=10'
    opt="${opt}&q=${str}"
fi
w3m http://www.google.co.jp/$opt
}

function exmap (){
str=`exiftool -c "%.6f" -GPSPosition ${1} | sed -e 's/GPS Position//' -e 's/://' -e 's/E//'  -e 's/S//' -e 's/W//' -e 's/N//' -e 's/ //g'`
open -a Google\ Chrome "https://maps.google.co.jp/maps?q=$str"
}

function chrome() {
local str opt
if [ $ != 0 ]; then
    for i in $*; do
        str="$str+$i"
    done
    str=`echo $str | sed 's/^\+//'`
    opt='search?num=50&hl=ja&lr=lang_ja'
    opt="${opt}&q=${str}"
fi
open -a Google\ Chrome http://www.google.co.jp/$opt
}

function google_translate() {
local str opt arg

str=`pbpaste` # clipboard
arg=`echo ${@:2} | sed -e 's/  */+/g'` # argument
en_jp="?hl=ja&sl=en&tl=ja&ie=UTF-8&oe=UTF-8" # url

case "$1" in
    "-j") opt="?hl=ja&sl=ja&tl=en&ie=UTF-8&oe=UTF-8&text=${arg}";; # jp -> en translate
"-e") opt="${en_jp}&text=${arg}";; # en -> jp translate
        *) opt="${en_jp}&text=${str}";; # en -> jp translate
    esac

    w3m +20 "http://translate.google.com/${opt}"  # goto 20 line
}

# blogger
function bp(){
    TITLE="$(awk 'NR==1' $1)"
    TAG="$(awk 'NR==2' $1)"
    sed -ie 1,2d $1
    google blogger post --blog "MBA-HACK" --title "${TITLE}" --tags "${TAG}" $1
    url=`google blogger list url --title "${TITLE}" | cut -d , -f 2`
    open -a Google\ Chrome $url
}



function got(){
w3m "http://www.google.co.jp/search?num=50&hl=ja&lr=lang_ja&q=$2&tbs=qdr:${1}"
}

function img-search () {
dir=~/Downloads/pic
mkdir -p $dir
word=`echo $1 | ruby -r cgi -ne 'puts CGI.escape $_.chomp'`
echo $word
url=`curl "http://ajax.googleapis.com/ajax/services/search/images?q=$word&v=1.0&safe=active&imgsz=xxlarge&rsz=large" | jq -r '.responseData.results [] .url'`
cou=`echo $url | wc -l | tr -d ' '`

for (( i=1;i<$cou;i++ ))
do
    urlo=`echo $url | awk "NR==$i"`
    file=${urlo##*/}
    curl $urlo -o $dir/$file
done

qlmanage -p $dir/*
file=`zsh -c "ls -A $dir" | peco`
url=`echo $url | grep $file`
echo $url | pbcopy && pbpaste
rm -rf $dir

}



### }}}

### prompt {{{

source $PLUGIN/powerline.zsh

## default {{{

#case $OSTYPE in
#linux*)
#  TMUX_POWERLINE_SEPARATOR_LEFT_BOLD="◀"
#  TMUX_POWERLINE_SEPARATOR_LEFT_THIN="❮"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD="▶"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_THIN="❯"
#  TMUX_POWERLINE_GIT="ⓦ"
#;;
#darwin*)
#  TMUX_POWERLINE_SEPARATOR_LEFT_BOLD="⮂"
#  TMUX_POWERLINE_SEPARATOR_LEFT_THIN="⮃"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD="⮀"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_THIN="⮁"
#  TMUX_POWERLINE_GIT="⭠"
#;;
#esac
#setopt prompt_subst
#setopt prompt_percent
#setopt transient_rprompt
#
#color256()
#{
#  local red=$1; shift
#  local green=$2; shift
#  local blue=$3; shift
#
#  echo -n $[$red * 36 + $green * 6 + $blue + 16]
#}
#
#fg256()
#{
#  echo -n $'\e[38;5;'$(color256 "$@")"m"
#}
#
#bg256()
#{
#  echo -n $'\e[48;5;'$(color256 "$@")"m"
#}
#
#zstyle ':vcs_info:*' max-exports 3
#zstyle ':vcs_info:hg:*' get-revision true
#zstyle ':vcs_info:hg:*' use-simple true
#
#autoload -Uz is-at-least
#zstyle ':vcs_info:git:*' check-for-changes true
#zstyle ':vcs_info:git:*' stagedstr "-"
#zstyle ':vcs_info:git:*' unstagedstr "${TMUX_POWERLINE_GIT}"
#zstyle ':vcs_info:*' actionformats '[%b|%a]'
#
#zstyle ':vcs_info:git:*' formats '%{%k%f%}%F{black}%K{green}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%F{white}%K{green} %s %f%k%K{blue}%F{green}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%%F{white}%K{blue} %b %f%k%K{black}%F{blue}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%%F{white}%K{black} %c%u %f%k'
#
#autoload -Uz vcs_info
#
#prompt_bar_left_self="%{%F{white}%K{020}%} %n%{%k%f%}%{%F{white}%K{020}%}@%{%k%f%}%{%F{white}%K{020}%}%m %{%k%f%}%{%B%F{020}%K{020}%}%{%b%f%k%}%K{026}%F{blue}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%B%F{white}%K{026}%}  [%~]  %{%k%f%b%}%{%k%f%}%K{069}%F{026}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%(?.%F{white}%K{069}%}`w | grep user, | cut -d , -f 2` %k%f.%B%K{069}%F{red}%}`w | grep user, | cut -d , -f 2` %b%k%f)%{%K{045}%F{069}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%F{white}%K{045}%} %h  %{%k%f%}%K{black}%F{045}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f"
#
#prompt_bar_left="${prompt_bar_left_self} ${prompt_bar_left_status} ${prompt_bar_left_date}"
#prompt_left='%{%F{white}%K{black}%}  $SHELL  %{%k%f%}%{%K{white}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%B%F{black}%K{white}%} %# ${p_buffer_stack} %{%b%k%f%f%}%K{black}%F{white}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f >  '
#
#count_prompt_characters()
#{
#  print -n -P -- "$1" | sed -e $'s/\e\[[0-9;]*m//g' | wc -m | sed -e 's/ //g'
#}
#
#update_prompt()
#{
#  local bar_left_length=$(count_prompt_characters "$prompt_bar_left")
#  local bar_rest_length=$[COLUMNS - bar_left_length]
#  local stash
#  stash="stash "$(git stash list 2>/dev/null | wc -l | tr -d ' ')
#  local ahead
#  ahead="push "$(git rev-list origin/master..master 2>/dev/null \
#    | wc -l \
#    | tr -d ' ')
#  stash="%K{013}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%k%f%}%{%F{white}%K{013}%} $stash %{%k%f%}%F{013}%K{blue}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%k%f%}%{%F{white}%K{blue}%} $ahead %{%k%f%}%F{blue}%K{green}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}"
#  local stad
#  # stash を有効にする
#  #stad=$stash
#  local bar_left="$prompt_bar_left"$stad
#  local bar_right_without_path="${prompt_bar_right:s/%d//}"
#  local bar_right_without_path_length=$(count_prompt_characters "$bar_right_without_path")
#  bar_right=${prompt_bar_right:s/%d/%(C,%${max_path_length}<...<%d%<<,)/}
#  bar_right="%${bar_rest_length}<<${separator}${bar_right}%<<"
#  prompt_bar_left_2="%K{white}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%F{black}%K{white}%} %l %K{black}%F{white}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%k%f%}%{%F{white}%K{black}%}  $LANG  %{%k%f%}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}"
#
#  PROMPT="${bar_left}${bar_right}${prompt_bar_left_2}"$'\n'"${prompt_left}"
#
#  case "$TERM_PROGRAM" in
#    Apple_Terminal)
#      PROMPT="${PROMPT}"
#      ;;
#  esac
#
#  LANG=C vcs_info >&/dev/null
#  if [ -n "$vcs_info_msg_0_" ]; then
#    PROMPT="${bar_left}${bar_right}${vcs_info_msg_0_}${prompt_bar_left_2}"$'\n'"${prompt_left}"
#  fi
#}
#
#precmd_functions=($precmd_functions update_prompt)
#
## }}}

### vi-mode {{{
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if bindkey -lL main | cut -d ' ' -f 3 | grep emacs > /dev/null 2>&1;then
#    EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#    VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#    EMACS_INSERT="%K{black}%F{034}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{034}%F{011} % $EMACS_INSERT %k%f"
#    VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
##VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%%k%f"
#RPROMPT="$EMACS_INSERT$VIM_INSERT"
#function zle-keymap-select {
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if echo $EMACS_INSERT | grep emacs > /dev/null 2>&1;then
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#  EMACS_INSERT="%K{black}%F{034}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{034}%F{011} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{034}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
#RPROMPT="$EMACS_INSERT${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
#zle reset-prompt
#}
#zle -N zle-keymap-select

#function airchrome-bindmode-emacs () {
#bindkey -e
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if echo $EMACS_INSERT | grep emacs > /dev/null 2>&1;then
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
#RPS1="$EMACS_INSERT${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
#RPS2=$RPS1
#zle reset-prompt
#}
#zle -N airchrome-bindmode-emacs
#bindkey -v '^e' airchrome-bindmode-emacs
#bindkey -a '^e' airchrome-bindmode-emacs
#
#function airchrome-bindmode-vi () {
#bindkey -v
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if echo $EMACS_INSERT | grep emacs > /dev/null 2>&1;then
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#  EMACS_INSERT="%K{black}%F{034}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{034}%F{011} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{034}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
#RPS1="$EMACS_INSERT${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
#RPS2=$RPS1
#zle reset-prompt
#}
#zle -N airchrome-bindmode-vi
#bindkey -e '^v' airchrome-bindmode-vi
#### }}}
### }}}

### media {{{

case $OSTYPE in

darwin*)

function nico_mylist(){
url=`ls -A . | grep Nico | cut -d ':' -f 2 | sed -e 's/GINZA-//g' -e "s/\.[^.]*$//" | tr '\n' ' '`
data=`date +"%Y_%m_%d"`
echo "nico_mylist.py $data $url" | pbcopy && pbpaste
}

function nico_chrome(){
word1="GINZA-"
url=`zsh -c "ls -A . | grep Niconico | cut -d ':' -f 2"`
url=`echo $url | sed -e "s/$word1/http:\/\/www.nicovideo.jp\/watch\//g" -e "s/\.[^.]*$//"`
line=`echo $url | wc -l | tr -d ' '`
for (( i = $line; i > 0; i-- )) do
    murl=`echo $url | awk "NR==$i"`
    echo $murl
    open -a Google\ Chrome "$murl"
done
}

function picasa(){
    dirp=~/Pictures/picasa
    dirc=github
    qlmanage -p ${dirp}/*
    exiftool -overwrite_original -all= $dirp
    case $1 in
       "")
            #google picasa post -n "$dirc" ~/Pictures/picasa/*.png
            list=`google picasa list "$dirc" --delimiter " " --fields url-direct`
            numb=`bash -c "ls -A $dirp" | wc -l | tr -d ' '`
            echo "$list" | tail -n $numb | pbcopy && pbpaste
    ;;
    esac
    rm -rf $dirp > /dev/null 2>&1
    mkdir -p $dirp
}

function chrome_done_reload (){
osascript << EOF && osascript -e 'tell application "Google Chrome" to close first tab of window 1'
tell application "Google Chrome"
repeat while loading of active tab of window 1
delay 0.1
end repeat
activate
end tell
EOF

cat << EOF | osascript | tr ',' "\n"
tell application "Google Chrome"
set pageURI to get URL of tab of window 1
set pageTitle to get title of tab of window 1
return pageTitle & space & pageURI
end tell
EOF
}

function ffg (){
bas=`cat << EOF | peco | tr -d ' '
mp4 -> mp3
flv -> mp3
swf -> mp3
mp3 -> wav
flv -> wav
mov -> gif
jpg -> png
bmp -> png
EOF` > /dev/null 2>&1

inp=`echo $bas | cut -d '-' -f 1`
oup=`echo $bas | cut -d '>' -f 2`

case $inp in

    swf)
        for i in *.${inp}; do swfextract -m $i -o ${i%.swf}.mp3; done
    ;;

    mov)
        for i in *.${inp}; do ffmpeg -i *.mov -r 8 %04d.png && gm convert *.png ${i%.*}.gif && rm *.png; done
    ;;

    jpg)
        mogrify -format png -quality 100 *.jpg
    ;;

    bmp)
        mogrify -format png -quality 100 *.bmp
    ;;

    *)
        for i in *.${inp}; do ffmpeg -i $i -vn ${i%.*}.${oup}; done
    ;;

esac
}

alias mun='cd ~/Music/new && touch mylist.test && rm mylist* && mylist && mplayer -playlist mylist -novideo -loop 20 -quiet -msglevel all=0 -identify | grep FILE'

function ms (){
dir1=$HOME/Music
file=${0:a:t}
loop=20
speed=2

play=`ps | grep mplayer -s | wc -l | tr -d ' '`

case $play in
    ""|1)
        sea="ID_FILENAME"
        dir="$dir1/"`zsh -c "ls -A $dir1 | peco"`
        com="mplayer -speed $speed -af scaletempo,volnorm -novideo -loop $loop -quiet -msglevel all=0 -identify $dir/*"
        com="${com} | grep $sea"
        eval $com
    ;;
    *)
        pkill mplayer > /dev/null 2>&1
    ;;
esac
}

## twitter
function tweetvim (){
    case $1 in
        "")
            vim +TweetVimUserTimeline
        ;;
        t)
            vim +TweetVimSay
        ;;
        m)
            vim +TweetVimMentions +/@
        ;;
        l)
            vim -c "TweetVimListStatuses fav" +/http
        ;;
        $USER)
            vim -c "TweetVimUserTimeline syui__"
        ;;

    esac
}

alias qiita-line="curl -I 'https://qiita.com/api/v1/items.json'"
alias lingr="vim +J6uil +J6uilStartNotify"
alias iTunes='open -a iTunes'
alias youtube.py='~/youtube-cli/youtube.py'
alias html2text='python ~/html2text/html2text.py'
alias mylist='find `pwd` -maxdepth 1 -mindepth 1 | grep -v "\/\." > mylist'
alias ch="open -a Google\ Chrome --args --gpu-startup-dialog --disable-java --disable-background-mode --renderer-process-limit=2"
alias fu="~/dotfiles/fu/fu"
alias keepass="~/pull/airkeepass/airkeepass"
alias anime="~/script/anitube-cli/anitube-cli"
alias hatena="~/script/hatena-cli/hatena-cli"
alias nicovideo='nicovideo-dl -t -n'
;;

esac
### }}}

### os {{{
case $OSTYPE in
linux*)
        bindkey -v
        export CLICOLOR=1
        export LSCOLORS=ExFxCxDxBxegedabagacad
        export PATH
        # man path
        MANPATH=/usr/local/man:$MANPATH
        export MANPATH
        INFOPATH=/usr/local/info:$INFOPATH
        export INFOPATH

        # Java
        export JAVA_HOME=/usr/java/default
        export PATH=$JAVA_HOME/bin:$PATH

        # Maven2
        export MAVEN_HOME=/usr/local/apache-maven-2.2.1
        export PATH=$MAVEN_HOME/bin:$PATH
        export MAVEN_OPTS=-Xmx1024M

        #rvm
        if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi

        export PATH=$PATH:$HOME/.gem/ruby/1.8/bin

        #alias
        alias ls='ls -alh --color'
        alias vim="/usr/bin/vim"
        alias v="/usr/bin/vim"

        ;;

darwin*)
        zle -N expand-to-home-or-insert
        bindkey -v
        bindkey "@"  expand-to-home-or-insert
        export PATH=/usr/local/bin:/usr/local/sbin:$PATH
        export PATH=/opt/local/bin:/opt/local/sbin:~/bin:$PATH

        # osx alias
        alias pbc='pbcopy'
        alias vo='osascript -e "set Volume 0.00001"'
        # Terminal Colorの設定
        export CLICOLOR=1
        export LSCOLORS=ExFxCxDxBxegedabagacad

        ## vim
        export EDITOR=/Applications/MacVim.app/Contents/MacOS/Vim
        alias vi='/opt/local/bin/vim'
        alias vim='env LANG=ja_JP.UTF-8 /Applications/MacVim.app/Contents/MacOS/Vim "$@"'
        alias v='env LANG=ja_JP.UTF-8 /Applications/MacVim.app/Contents/MacOS/Vim "$@"'

        ##Java7
        export JAVA_HOME=/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
        # export JAVA_HOME=/Library/Java/Home
        export PATH=$JAVA_HOME/bin:$PATH
        # デフォルトエンコーディングSJISをUTF-8へ
        export _JAVA_OPTIONS="-Dfile.encoding=UTF-8"

        # haskell
        export PATH=/Users/ozaki/Library/Haskell/bin:$PATH

        # scala
        export SCALA_HOME=/Users/ozaki/.svm/current/rt
        PATH=$SCALA_HOME/bin:$PATH
        export SCALA_DOC_HOME=$SCALA_HOME/../devel-docs/api/
        export SCALA_CLASSPATH=~/sandbox/scala/yuroyoro/yuroyoro-util/target/yuroyoro-util-1.0.jar

        # Ant
        export ANT_VERSION=1.8.0
        export ANT_HOME=~/dev/Tools/apache-ant-${ANT_VERSION}
        export ANT_OPTS=-Xmx1g
        export PATH=$ANT_HOME/bin:$PATH

        # Maven2
        export MAVEN_VERSION=2.2.1
        export MAVEN_HOME=~/dev/Tools/apache-maven-${MAVEN_VERSION}
        export PATH=$MAVEN_HOME/bin:$PATH
        export MAVEN_OPTS=-Xmx1024M

        # man path
        MANPATH=/usr/local/man:$MANPATH
        export MANPATH
        INFOPATH=/usr/local/info:$INFOPATH
        export INFOPATH

        # Mysql
        export MYSQL_HOME=/usr/local/mysql
        export PATH=$MYSQL_HOME/bin:$PATH
        alias h2db='java -cp ~/.m2/repository/com/h2database/h2/1.1.112/h2-1.1.112.jar org.h2.tools.Server'

        # STAX SDK
        export STAX_HOME=~/dev/Project/sandbox/stax-sdk-0.2.11
        export PATH=$PATH:$STAX_HOME

        # Adobe AIR
        export AIR_HOME=~/dev/air
        export FLEX_HOME=~/dev/flex
        export PATH=$PATH:$AIR_HOME/bin:$FLEX_HOME/bin
        export GAE_SDK_VERSION=1.3.4
        GAE_SDK_INSTALLED_DIR=~/sandbox/GoogleAppEngine/sdk
        export GAE_HOME=$GAE_SDK_INSTALLED_DIR/$GAE_SDK_VERSION/google_appengine
        export PATH=$PATH:$GAE_HOME
        export GAEJ_SDK_VERSION=1.3.7
        GAEJ_SDK_INSTALLED_DIR=~/sandbox/GAEJava/sdk
        export GAEJ_HOME=$GAEJ_SDK_INSTALLED_DIR/appengine-java-sdk-$GAEJ_SDK_VERSION
        export PATH=$PATH:$GAEJ_HOME/bin
        export REFE_DATA_DIR=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/share/refe
        export GOROOT=$HOME/dev/go
        export GOOS=darwin
        export GOARCH=386
        export PATH=$PATH:$GOROOT/bin
        export NODE_PATH=/usr/local/lib/node:$PATH
        export PATH=/usr/local/share/npm/bin:$PATH
        export JRUBY_HOME=$HOME/sandbox/jruby/jruby-1.5.2
        export PATH=$PATH:$JRUBY_HOME/bin
        export MIRAH_HOME=$HOME/sandbox/mirah/mirah
        export PATH=$PATH:$MIRAH_HOME/bin
        alias tma='tmux attach'
        alias tml='tmux list-window'
        ;;
esac

### font {{{
case $OSTYPE in
    linux*)
        if ! fc-list | grep DejaVuSans > /dev/null 2>&1;then
            sudo pacman -S ttf-dejavu
        fi
    ;;
    darwin*)
        if ! ls ~/Library/Fonts/Ricty* > /dev/null 2>&1;then
            brew tap sanemat/font
            brew install ricty
            brew install fontforge
            cp -f /usr/local/opt/ricty/share/fonts/Ricty*.ttf ~/Library/Fonts/
            #fc-cache -vf
        fi
    ;;
esac
### }}}
### }}}

#{
#  "to-do" : {
#    "os" : [ "coreos", "docker", "vagrant", "awesome", "conky" ],
#    "terminal" : [ "cygwin", "powershell", "vim", "tmux", "git" ],
#    "tool" : [ "dwb", "spacefm", "growl", "ffmpeg", "imagemagick", "googlecl", "keepass", "jq", "canto", "nc", "ssh", "mosh", "nmap", "weechat", "metasploit", "wireshark" ],
#    "lang" : [ "c++", "python", "ruby", "lua", "go", "scala", "typescript", "perl", "sass", "slim", "node.js", "swift", "gauche" ]
#  }
#}

ヘルプ

以下を設定して、なんかのコマンドを入力後、C-h, C-hを押しましょう。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
### help {{{
#HELPDIR=/usr/local/share/zsh/helpfiles
alias run-help >/dev/null 2>&1 && unalias run-help
autoload -Uz run-help
autoload -Uz run-help-git
autoload -Uz run-help-svn
autoload -Uz run-help-svk
autoload -Uz run-help-openssl
autoload -Uz run-help-p4
autoload -Uz run-help-sudo
bindkey '^h^h' run-help
### }}}

ディレクトリ

上下の移動

この設定でC-kC-jで上下に移動できるようになります。使用頻度は結構高いです。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
### directory {{{

function chpwd() { ls -aCFG }

function mkcd() {
if [[ -d $1 ]]; then
    echo "It already exsits! Cd to the directory."
    cd $1
else
    echo "Created the directory and cd to it."
    mkdir -p $1 && cd $1
fi
}

function cdup_dir() {
if [[ -z "$BUFFER" ]]; then
    echo
    cd ..
    ls -aF
    zle reset-prompt
else
    zle self-insert 'k'
fi
 }
 zle -N cdup_dir
 bindkey '^k' cdup_dir

 function cddown_dir(){
 com='$SHELL -c "ls -AF . | grep / "'
 while [ $? = 0 ]
 do
     cdir=`eval $com | peco`
     if [ $? = 0 ];then
         cd $cdir
         eval $com
     else
         break
     fi
 done
 zle reset-prompt
}
zle -N cddown_dir
bindkey '^j' cddown_dir

### }}}

pecoを使いますので、インストールします。

1
2
3
4
5
6
7
8
9
10
11
12
$ brew install go

$ go get github.com/peco/peco/cmd/peco

$ cat << EOF >> ~/.zshrc
### golang {{{
if [ -x "`which go`" ]; then
  export GOPATH=$HOME/go
  export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
fi
### }}}
EOF

移動履歴を参照する移動

参照しそうなプラグインなどは、なければ自動でダウンロードするようにしています。

基本的には、zcdrの履歴を使いわけます。具体的には、C-j, C-kでよく使うディレクトリ、C-j, C-jでちょっと使うディレクトリにしています。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
### cdr {{{
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
zstyle ':completion:*:*:cdr:*:*' menu selection
zstyle ':completion:*' recent-dirs-insert both
zstyle ':chpwd:*' recent-dirs-max 500
zstyle ':chpwd:*' recent-dirs-default true
zstyle ':chpwd:*' recent-dirs-pushd true
### }}}

### download {{{

export DOTFILE=$HOME/dotfiles
export PLUGIN=$DOTFILE/.zsh/plugin

## completion
if [ ! -d $PLUGIN/zsh-completions ];then
    git clone git://github.com/zsh-users/zsh-completions $PLUGIN/zsh-completions
fi
fpath=($PLUGIN/zsh-completions/src $fpath)

## powerline {{{
if [ ! -f $PLUGIN/powerline.zsh ];then
    curl https://gist.githubusercontent.com/syui/e3fad84e3dba8a3f667b/raw/powerline.zsh -o $PLUGIN/powerline.zsh
fi

if [ ! -d $PLUGIN/powerline-bash ];then
    git clone https://github.com/milkbikis/powerline-bash $PLUGIN/powerline-bash
fi

#ln -s $PLUGIN/powerline-bash/powerline-bash.py ~/powerline-bash.py
#
#function powerline_precmd() {
#export PS1="$(~/powerline-bash.py $? --shell zsh)"
#        }
#
#        function install_powerline_precmd() {
#        for s in "${precmd_functions[@]}"; do
#            if [ "$s" = "powerline_precmd" ]; then
#                return
#            fi
#        done
#        precmd_functions+=(powerline_precmd)
#    }
#
#    install_powerline_precmd
## }}}

## tmux-powerline
# iTerm : Treat ambiguous-width characters as double width
case $OSTYPE in
    darwin*)
        if ! type tmux > /dev/null 2>&1;then
            brew tap waltarix/homebrew-customs
            brew update
            brew install waltarix/customs/tmux
        fi
    ;;
esac

if type tmux > /dev/null 2>&1;then
    if [ ! -d $DOTFILE/.tmux/tmux-powerline ];then
        git clone https://github.com/erikw/tmux-powerline $DOTFILE/.tmux/tmux-powerline
    fi
    if [ ! -d $DOTFILE/.tmux/tmux-colors-solarized ];then
        git clone https://github.com/seebi/tmux-colors-solarized $DOTFILE/.tmux/tmux-colors-solarized
    fi
fi

if [ ! -f $DOTFILE/.tmux/tmux-powerline/segments/used-mem ];then
    curl https://raw.githubusercontent.com/yonchu/used-mem/master/used-mem -o $DOTFILE/.tmux/tmux-powerline/segments/used-mem
    chmod +x $DOTFILE/.tmux/tmux-powerline/segments/used-mem
fi

if [ ! -f $DOTFILE/.tmux/tmux-powerline/segments/mplayer_tmux.sh ];then
    curl https://raw.githubusercontent.com/syui/mplayer_script/master/mplayer_tmux.sh -o $DOTFILE/.tmux/tmux-powerline/segments/mplayer_tmux.sh
    chmod +x $DOTFILE/.tmux/tmux-powerline/segments/mplayer_tmux.sh
fi

if [ ! -f $DOTFILE/.tmux/.tmux.conf.mac ];then
    curl https://gist.githubusercontent.com/syui/5c49d1296c992d8af737/raw/.tmux.conf.mac -o $DOTFILE/.tmux/.tmux.conf.mac
fi

## vim
if [ ! -d ~/.vim/bundle/neobundle.vim ];then
    curl https://raw.githubusercontent.com/Shougo/neobundle.vim/master/bin/install.sh | sh
fi

## oh-my-zsh
if [ ! -d $PLUGIN/oh-my-zsh ];then
    git clone https://github.com/robbyrussell/oh-my-zsh $PLUGIN/oh-my-zsh
fi

## cheat-sheet
if [ -f $PLUGIN/oh-my-zsh/templates/zshrc.zsh-template ];then
    cheat-sheet () { zle -M "`cat ~/dotfiles/.zsh/cheat-sheet`" }
    zle -N cheat-sheet
    # bindkey "^[^h" cheat-sheet
fi

## golang
if [ ! -f ~/dotfiles/.zsh/plugin/golang-crosscompile/crosscompile.bash ];then
  git clone https://github.com/davecheney/golang-crosscompile ~/dotfiles/.zsh/plugin/golang-crosscompile
fi

## growl
if [ ! -f ~/dotfiles/.zsh/plugin/growl.zsh ];then
       curl https://raw.githubusercontent.com/patbenatar/dotfiles/master/zsh/growl.zsh -o $HOME/dotfiles/.zsh/plugin/growl.zsh
  chmod +x ~/dotfiles/.zsh/plugin/growl.zsh
fi

## rupa/z
case $OSTYPE in
  drawin*)
    if [ -f `brew --prefix`/etc/profile.d/z.sh ];then
      brew install z
    fi
    . `brew --prefix`/etc/profile.d/z.sh
    ;;
  linux*)
    if [ ! -d ~/dotfiles/.zsh/plugin/z ];then
      git clone https://github.com/rupa/z ~/dotfiles/.zsh/plugin/z
    fi
    . ~/dotfiles/.zsh/plugin/z/z.sh
    ;;
esac

## _z  {{{
if ! type _z > /dev/null 2>&1;then
_z () {
  local datafile="${_Z_DATA:-$HOME/.z}"
  [ -z "$_Z_OWNER" -a -f "$datafile" -a ! -O "$datafile" ] && return
  if [ "$1" = "--add" ]
  then
    shift
    [ "$*" = "$HOME" ] && return
    local exclude
    for exclude in "${_Z_EXCLUDE_DIRS[@]}"
    do
      [ "$*" = "$exclude" ] && return
    done
    local tempfile="$datafile.$RANDOM"
    while read line
    do
      [ -d "${line%%\|*}" ] && echo $line
    done < "$datafile" | awk -v path="$*" -v now="$(date +%s)" -F"|" '
            BEGIN {
                rank[path] = 1
                time[path] = now
            }
            $2 >= 1 {
                # drop ranks below 1
                if( $1 == path ) {
                    rank[$1] = $2 + 1
                    time[$1] = now
                } else {
                    rank[$1] = $2
                    time[$1] = $3
                }
                count += $2
            }
            END {
                if( count > 9000 ) {
                    # aging
                    for( x in rank ) print x "|" 0.99*rank[x] "|" time[x]
                } else for( x in rank ) print x "|" rank[x] "|" time[x]
            }
        ' 2> /dev/null >| "$tempfile"
    if [ $? -ne 0 -a -f "$datafile" ]
    then
      env rm -f "$tempfile"
    else
      [ "$_Z_OWNER" ] && chown $_Z_OWNER:$(id -ng $_Z_OWNER) "$tempfile"
      env mv -f "$tempfile" "$datafile" || env rm -f "$tempfile"
    fi
  elif [ "$1" = "--complete" -a -s "$datafile" ]
  then
    while read line
    do
      [ -d "${line%%\|*}" ] && echo $line
    done < "$datafile" | awk -v q="$2" -F"|" '
            BEGIN {
                if( q == tolower(q) ) imatch = 1
                q = substr(q, 3)
                gsub(" ", ".*", q)
            }
            {
                if( imatch ) {
                    if( tolower($1) ~ tolower(q) ) print $1
                } else if( $1 ~ q ) print $1
            }
        ' 2> /dev/null
  else
    while [ "$1" ]
    do
      case "$1" in
        (--) while [ "$1" ]
          do
            shift
            local fnd="$fnd${fnd:+ }$1"
          done ;;
        (-*) local opt=${1:1}
          while [ "$opt" ]
          do
            case ${opt:0:1} in
              (c) local fnd="^$PWD $fnd" ;;
              (h) echo "${_Z_CMD:-z} [-chlrtx] args" >&2
                return ;;
              (x) sed -i -e "\:^${PWD}|.*:d" "$datafile" ;;
              (l) local list=1 ;;
              (r) local typ="rank" ;;
              (t) local typ="recent" ;;
            esac
            opt=${opt:1}
          done ;;
        (*) local fnd="$fnd${fnd:+ }$1" ;;
      esac
      local last=$1
      shift
    done
    [ "$fnd" -a "$fnd" != "^$PWD " ] || local list=1
    case "$last" in
      (/*) [ -z "$list" -a -d "$last" ] && cd "$last" && return ;;
    esac
    [ -f "$datafile" ] || return
    local cd
    cd="$(while read line; do
            [ -d "${line%%\|*}" ] && echo $line
        done < "$datafile" | awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
            function frecent(rank, time) {
                # relate frequency and time
                dx = t - time
                if( dx < 3600 ) return rank * 4
                if( dx < 86400 ) return rank * 2
                if( dx < 604800 ) return rank / 2
                return rank / 4
            }
            function output(files, out, common) {
                # list or return the desired directory
                if( list ) {
                    cmd = "sort -n >&2"
                    for( x in files ) {
                        if( files[x] ) printf "%-10s %s\n", files[x], x | cmd
                    }
                    if( common ) {
                        printf "%-10s %s\n", "common:", common > "/dev/stderr"
                    }
                } else {
                    if( common ) out = common
                    print out
                }
            }
            function common(matches) {
                # find the common root of a list of matches, if it exists
                for( x in matches ) {
                    if( matches[x] && (!short || length(x) < length(short)) ) {
                        short = x
                    }
                }
                if( short == "/" ) return
                # use a copy to escape special characters, as we want to return
                # the original. yeah, this escaping is awful.
                clean_short = short
                gsub(/[\(\)\[\]\|]/, "\\\\&", clean_short)
                for( x in matches ) if( matches[x] && x !~ clean_short ) return
                return short
            }
            BEGIN {
                gsub(" ", ".*", q)
                hi_rank = ihi_rank = -9999999999
            }
            {
                if( typ == "rank" ) {
                    rank = $2
                } else if( typ == "recent" ) {
                    rank = $3 - t
                } else rank = frecent($2, $3)
                if( $1 ~ q ) {
                    matches[$1] = rank
                } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
                if( matches[$1] && matches[$1] > hi_rank ) {
                    best_match = $1
                    hi_rank = matches[$1]
                } else if( imatches[$1] && imatches[$1] > ihi_rank ) {
                    ibest_match = $1
                    ihi_rank = imatches[$1]
                }
            }
            END {
                # prefer case sensitive
                if( best_match ) {
                    output(matches, best_match, common(matches))
                } else if( ibest_match ) {
                    output(imatches, ibest_match, common(imatches))
                }
            }
        ')"
    [ $? -gt 0 ] && return
    [ "$cd" ] && cd "$cd"
  fi
}
fi
### }}}

compctl -U -K _z_zsh_tab_completion ${_Z_CMD:-z}


## zaw/zaw
if [ ! -d ~/dotfiles/.zsh/plugin/zaw ];then
  git clone https://github.com/zsh-users/zaw ~/dotfiles/.zsh/plugin/zaw
fi
if [ ! -f ~/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh ];then
  curl https://raw.githubusercontent.com/lovingly/dotfiles/master/zsh.d/zaw/zaw-z.zsh -o $HOME/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh
  chmod +x $HOME/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh
fi

## syui/airchrome.zsh
if [ ! -f $PLUGIN/airchrome.zsh/airchrome.zsh ];then
    git clone https://github.com/syui/airchrome.zsh $PLUGIN/airchrome.zsh
fi

## syntax-highlight
if [ ! -f $HOME/dotfiles/.zsh/plugin/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ];then
  git clone https://github.com/zsh-users/zsh-syntax-highlighting $HOME/dotfiles/.zsh/plugin/zsh-syntax-highlighting
fi
### }}}

### source {{{

#source $PLUGIN/oh-my-zsh

source ~/dotfiles/.zsh/plugin/golang-crosscompile/crosscompile.bash
source ~/dotfiles/.zsh/plugin/zaw/zaw.zsh
source $HOME/dotfiles/.zsh/plugin/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

[ -f ~/.zshrc.local ] && source ~/.zshrc.local

[ -s ${HOME}/.rvm/scripts/rvm ] && source ${HOME}/.rvm/scripts/rvm

case $OSTYPE in
    darwin*)
        source $PLUGIN/airchrome.zsh/airchrome.zsh
        source $PLUGIN/growl.zsh
    ;;
esac

unsetopt sh_word_split

### }}}

## zaw {{{
bindkey '^x' zaw
bindkey '^h' zaw-history
bindkey '^@' zaw-gitdir
bindkey '^r' zaw-open-file
bindkey '^j^j' zaw-cdr
bindkey '^j^k' zaw-z
### }}}
$ git clone https://github.com/rupa/z ~/dotfiles/.zsh/plugin/z

$ git clone https://github.com/zsh-users/zaw ~/dotfiles/.zsh/plugin/zaw

$ curl https://raw.githubusercontent.com/lovingly/dotfiles/master/zsh.d/zaw/zaw-z.zsh -o $HOME/dotfiles/.zsh/plugin/zaw/sources/zaw-z.zsh

$ chmod +x !$

また、C-hもよく使います。コマンド履歴を参照します。

ファイル

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
### open {{{{
function openapp() {
case $OSTYPE in
    freebsd*|darwin*)
      BUFFER="open -a "
    ;;
    linux*)
      BUFFER="xdg-open "
      #BUFFER="gnome-open "
    ;;
    cygwin*)
      BUFFER="cygstart "
    ;;
esac
  CURSOR=$#BUFFER
}
zle -N openapp
bindkey '^o' openapp
# bindkey -s '^o' "open -a "
### }}}

クリップボード

まず、Cにグローバルエイリアスを設定します。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
### clipboard {{{
## pbcopy
case ${OSTYPE} in
  linux*)
    if [ ! -f /usr/bin/xsel ];then
      sudo pacman -S xsel
    fi
    alias pbcopy='xsel --clipboard --input'
    ;;
  cygwin*)
    alias pbcopy='putclip'
    ;;
esac

## buffer
pbcopy-buffer(){
  case ${OSTYPE} in
    freebsd*|darwin*)
      print -rn $BUFFER | pbcopy
      ;;
    linux*)
      print -rn $BUFFER | xclip -i -selection clipboard
      ;;
    cygwin*)
      print -rn $BUFFER | putclip
      ;;
  esac
  zle -M "copy : ${BUFFER}"
}
zle -N pbcopy-buffer
bindkey '^p^p' pbcopy-buffer

## alias
if which pbcopy >/dev/null 2>&1 ; then
  # Mac
  alias -g C='| pbcopy'
elif which xclip >/dev/null 2>&1 ; then
  # Linux
  alias -g C='| xclip --input --clipboard'
elif which putclip >/dev/null 2>&1 ; then
  # Cygwin
  alias -g C='| putclip'
fi

## bindkey
# bindkey -s '^b' " | pbcopy"

## clipboard-history
function clipboard-history (){
case $OSTYPE in
  linux*)
    if [ ! -f /usr/bin/anamnesis ];then
      sudo yaourt -S anamnesis
    fi
    anamnesis -l 100 | sed -n '3,100p' | peco | cut -d u -f 2- | head -c -3 | tail -c +2  | xclip -i -selection clipboard
    ;;
  freebsd*|darwin*)
    plutil -convert xml1 ~/Library/Application\ Support/ClipMenu/clips.data -o - | parsrx.sh | grep '/plist/dict/array/string ' | sed '1,2d' | sed 's/\/plist\/dict\/array\/string//g' | peco | pbcopy
    ;;
esac
}
zle -N clipboard-history
bindkey '^[c' clipboard-history
### }}}

これで、例えば、echo test Cコマンドで、クリップボードには、testの文字列が保存されます。

また、M-cでクリップボード履歴をコマンドラインから取得します。ちなみに、クリップボード管理ツールは好きなの使ってください。私は、arch:anamesismac:clipmenuを使っています。

1
2
3
$ yaourt -S anamnesis

$ echo 'anamnesis --start' >> ~/.xinitrc

iTermを使っている方は、そのままでは、Altは使えないので、以下の設定を行います。

Preference -> Profile -> keys -> +Esc

ターミナル

一時的に入力したコマンドを退避するには、C-Qを押します。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
### stack {{{
function show_buffer_stack() {
  POSTDISPLAY="
  stack: $LBUFFER"
  zle push-line-or-edit
}
zle -N show_buffer_stack
setopt noflowcontrol
bindkey '^Q' show_buffer_stack
### }}}

コマンド

コマンド履歴を利用するには、C-rを押します。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
### history {{{
case $OSTYPE in
    linux*)
        function peco-select-history() {
        local tac
        if which tac > /dev/null; then
            tac="tac"
        else
            tac="tail -r"
        fi
        BUFFER=$(\history -rn 1 | \
            eval $tac | \
            peco --query "$LBUFFER")
        CURSOR=$#BUFFER
        zle clear-screen
    }
    ;;
darwin*)
    function peco-select-history() {
    BUFFER=`history -rn 1 | peco`
    CURSOR=$#BUFFER
    zle clear-screen
}
;;
esac
zle -N peco-select-history
bindkey '^h^j' peco-select-history
### }}}

プロンプト

また、プロンプトと連携する場合は、以下を参考にしてください。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
### prompt {{{

# powerline-download

export DOTFILE=$HOME/dotfiles
export PLUGIN=$DOTFILE/.zsh/plugin

if [ ! -f $PLUGIN/powerline.zsh ];then
    curl https://gist.githubusercontent.com/syui/e3fad84e3dba8a3f667b/raw/powerline.zsh -o $PLUGIN/powerline.zsh
fi

source $PLUGIN/powerline.zsh

## default {{{

#case $OSTYPE in
#linux*)
#  TMUX_POWERLINE_SEPARATOR_LEFT_BOLD="◀"
#  TMUX_POWERLINE_SEPARATOR_LEFT_THIN="❮"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD="▶"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_THIN="❯"
#  TMUX_POWERLINE_GIT="ⓦ"
#;;
#darwin*)
#  TMUX_POWERLINE_SEPARATOR_LEFT_BOLD="⮂"
#  TMUX_POWERLINE_SEPARATOR_LEFT_THIN="⮃"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD="⮀"
#  TMUX_POWERLINE_SEPARATOR_RIGHT_THIN="⮁"
#  TMUX_POWERLINE_GIT="⭠"
#;;
#esac
#setopt prompt_subst
#setopt prompt_percent
#setopt transient_rprompt
#
#color256()
#{
#  local red=$1; shift
#  local green=$2; shift
#  local blue=$3; shift
#
#  echo -n $[$red * 36 + $green * 6 + $blue + 16]
#}
#
#fg256()
#{
#  echo -n $'\e[38;5;'$(color256 "$@")"m"
#}
#
#bg256()
#{
#  echo -n $'\e[48;5;'$(color256 "$@")"m"
#}
#
#zstyle ':vcs_info:*' max-exports 3
#zstyle ':vcs_info:hg:*' get-revision true
#zstyle ':vcs_info:hg:*' use-simple true
#
#autoload -Uz is-at-least
#zstyle ':vcs_info:git:*' check-for-changes true
#zstyle ':vcs_info:git:*' stagedstr "-"
#zstyle ':vcs_info:git:*' unstagedstr "${TMUX_POWERLINE_GIT}"
#zstyle ':vcs_info:*' actionformats '[%b|%a]'
#
#zstyle ':vcs_info:git:*' formats '%{%k%f%}%F{black}%K{green}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%F{white}%K{green} %s %f%k%K{blue}%F{green}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%%F{white}%K{blue} %b %f%k%K{black}%F{blue}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%%F{white}%K{black} %c%u %f%k'
#
#autoload -Uz vcs_info
#
#prompt_bar_left_self="%{%F{white}%K{020}%} %n%{%k%f%}%{%F{white}%K{020}%}@%{%k%f%}%{%F{white}%K{020}%}%m %{%k%f%}%{%B%F{020}%K{020}%}%{%b%f%k%}%K{026}%F{blue}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%B%F{white}%K{026}%}  [%~]  %{%k%f%b%}%{%k%f%}%K{069}%F{026}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%(?.%F{white}%K{069}%}`w | grep user, | cut -d , -f 2` %k%f.%B%K{069}%F{red}%}`w | grep user, | cut -d , -f 2` %b%k%f)%{%K{045}%F{069}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%F{white}%K{045}%} %h  %{%k%f%}%K{black}%F{045}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f"
#
#prompt_bar_left="${prompt_bar_left_self} ${prompt_bar_left_status} ${prompt_bar_left_date}"
#prompt_left='%{%F{white}%K{black}%}  $SHELL  %{%k%f%}%{%K{white}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%B%F{black}%K{white}%} %# ${p_buffer_stack} %{%b%k%f%f%}%K{black}%F{white}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f >  '
#
#count_prompt_characters()
#{
#  print -n -P -- "$1" | sed -e $'s/\e\[[0-9;]*m//g' | wc -m | sed -e 's/ //g'
#}
#
#update_prompt()
#{
#  local bar_left_length=$(count_prompt_characters "$prompt_bar_left")
#  local bar_rest_length=$[COLUMNS - bar_left_length]
#  local stash
#  stash="stash "$(git stash list 2>/dev/null | wc -l | tr -d ' ')
#  local ahead
#  ahead="push "$(git rev-list origin/master..master 2>/dev/null \
#    | wc -l \
#    | tr -d ' ')
#  stash="%K{013}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%k%f%}%{%F{white}%K{013}%} $stash %{%k%f%}%F{013}%K{blue}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%k%f%}%{%F{white}%K{blue}%} $ahead %{%k%f%}%F{blue}%K{green}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}"
#  local stad
#  # stash を有効にする
#  #stad=$stash
#  local bar_left="$prompt_bar_left"$stad
#  local bar_right_without_path="${prompt_bar_right:s/%d//}"
#  local bar_right_without_path_length=$(count_prompt_characters "$bar_right_without_path")
#  bar_right=${prompt_bar_right:s/%d/%(C,%${max_path_length}<...<%d%<<,)/}
#  bar_right="%${bar_rest_length}<<${separator}${bar_right}%<<"
#  prompt_bar_left_2="%K{white}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%F{black}%K{white}%} %l %K{black}%F{white}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}%k%f%{%k%f%}%{%F{white}%K{black}%}  $LANG  %{%k%f%}%F{black}${TMUX_POWERLINE_SEPARATOR_RIGHT_BOLD}"
#
#  PROMPT="${bar_left}${bar_right}${prompt_bar_left_2}"$'\n'"${prompt_left}"
#
#  case "$TERM_PROGRAM" in
#    Apple_Terminal)
#      PROMPT="${PROMPT}"
#      ;;
#  esac
#
#  LANG=C vcs_info >&/dev/null
#  if [ -n "$vcs_info_msg_0_" ]; then
#    PROMPT="${bar_left}${bar_right}${vcs_info_msg_0_}${prompt_bar_left_2}"$'\n'"${prompt_left}"
#  fi
#}
#
#precmd_functions=($precmd_functions update_prompt)
#
## }}}

### vi-mode {{{
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if bindkey -lL main | cut -d ' ' -f 3 | grep emacs > /dev/null 2>&1;then
#    EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#    VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#    EMACS_INSERT="%K{black}%F{034}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{034}%F{011} % $EMACS_INSERT %k%f"
#    VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
##VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%%k%f"
#RPROMPT="$EMACS_INSERT$VIM_INSERT"
#function zle-keymap-select {
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if echo $EMACS_INSERT | grep emacs > /dev/null 2>&1;then
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#  EMACS_INSERT="%K{black}%F{034}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{034}%F{011} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{034}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
#RPROMPT="$EMACS_INSERT${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
#zle reset-prompt
#}
#zle -N zle-keymap-select

#function airchrome-bindmode-emacs () {
#bindkey -e
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if echo $EMACS_INSERT | grep emacs > /dev/null 2>&1;then
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
#RPS1="$EMACS_INSERT${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
#RPS2=$RPS1
#zle reset-prompt
#}
#zle -N airchrome-bindmode-emacs
#bindkey -v '^e' airchrome-bindmode-emacs
#bindkey -a '^e' airchrome-bindmode-emacs
#
#function airchrome-bindmode-vi () {
#bindkey -v
#EMACS_INSERT=`bindkey -lL main | cut -d ' ' -f 3`
#if echo $EMACS_INSERT | grep emacs > /dev/null 2>&1;then
#  EMACS_INSERT="%K{black}%F{011}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{011}%F{034} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{011}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{011}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#else
#  EMACS_INSERT="%K{black}%F{034}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{034}%F{011} % $EMACS_INSERT %k%f"
#  VIM_NORMAL="%K{034}%F{125}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{125}%F{015} % NORMAL %k%f%K{125}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#  VIM_INSERT="%K{034}%F{075}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f%K{075}%F{026} % INSERT %k%f%K{075}%F{black}${TMUX_POWERLINE_SEPARATOR_LEFT_BOLD}%k%f"
#fi
#RPS1="$EMACS_INSERT${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
#RPS2=$RPS1
#zle reset-prompt
#}
#zle -N airchrome-bindmode-vi
#bindkey -e '^v' airchrome-bindmode-vi
#### }}}

### }}}

例えば、プロンプトには、エラーも分かりやすく表示しています。具体的には、ログインしているユーザー数の部分がエラーだと赤色になります。これは、単純に終了ステータスを参照する?.とログインユーザーを調べるwコマンドを使っているだけです。このようなやり方は、コマンドやユーザー監視のために役立ちますので、適時カスタマイズして使ってみてください。

キーバインドを入れ替えるには、C-v, C-eを使います。プロンプトに現在のモードを表示しています。

キーバインド

jjvi-cmdに移行します。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
### bindkey {{{

bindkey -M viins 'jj' vi-cmd-mode
bindkey "^I" menu-complete
bindkey '^h^h' run-help
bindkey -s '^o^o' 'vim `zsh -c "ls -A" | peco`'
bindkey -s '^o' "open -a "
bindkey "^[u" undo
bindkey "^[r" redo
bindkey '^]'   vi-find-next-char
bindkey '^[^]' vi-find-prev-char
bindkey "^?" backward-delete-char
bindkey -a 'q' push-line
bindkey "^p" history-beginning-search-backward-end
bindkey "^n" history-beginning-search-forward-end
bindkey "\\ep" history-beginning-search-backward-end
bindkey "\\en" history-beginning-search-forward-end

bindkey '^[[7~' beginning-of-line
bindkey '^[[8~' end-of-line
bindkey '^[[2~' overwrite-mode
bindkey '^[[3~' delete-char
bindkey '^[[A'  up-line-or-history
bindkey '^[[B'  down-line-or-history
bindkey '^[[C'  forward-char
bindkey '^[[D'  backward-char
bindkey '^[[5~' history-beginning-search-backward
bindkey '^[[6~' history-beginning-search-forward

## zaw {{{
bindkey '^x' zaw
bindkey '^h' zaw-history
bindkey '^@' zaw-gitdir
bindkey '^r' zaw-open-file
bindkey '^j^j' zaw-cdr
bindkey '^j^k' zaw-z
### }}}

### }}}

tmux

こちらもコマンドの実行になります。ただし、キーはtmuxのものを使用するため~/.tmux.confに書いたほうが簡易です。

~/.tmux.conf
1
2
3
4
5
6
7
8
9
## copy {{{
# C-b, y : 1行コピー
bind -t vi-copy Y select-line
bind y run 'tmux copy-mode\; send-keys Y Enter'

# C-b, a : 全行コピー
bind -t vi-copy V begin-selection
bind a run 'tmux copy-mode\; send-keys ggVG Enter'
## }}}

しかし、zshからでも設定できます。M-n,mtmuxの1行コピーと全行コピーができるようにしています。Prefix-keyを押す必要がないので、こちらのほうが使いやすいかもしれません。

~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
### tmux {{{

## auto-start
case $OSTYPE in
    darwin*)
        if [ -z "$SSH_CONNECTION" -a ${UID} -ne 0 -a -z "$TMUX" -a -z "$STY" ]; then
            if type tmux >/dev/null 2>&1; then
                tmux
            elif type tmux >/dev/null 2>&1; then
                if tmux has-session && tmux list-sessions | egrep -q '.*]$'; then
                    tmux attach && echo "tmux attached session "
                else
                    tmux new-session && echo "tmux created new session"
                fi
            elif type screen >/dev/null 2>&1; then
                screen -rx || screen -D -RR
            fi
        fi
        ;;
    linux*)
        if [ -z "$TMUX" -a -z "$STY" ]; then
            if type tmux >/dev/null 2>&1; then
                if tmux has-session && tmux list-sessions | /usr/bin/grep -qE '.*]$'; then
                    tmux -2 attach && echo "tmux attached session "
                else
                    tmux -2 new-session && echo "tmux created new session"
                fi
            fi
        fi
        ;;
esac

##copy-mode
function tmux-copy-line () {
tmux copy-mode\; send-keys 2k0Vj Enter
}
zle -N tmux-copy-line
bindkey '^[n' tmux-copy-line

function tmux-copy-all () {
tmux copy-mode\; send-keys ggVG Enter
#tmux copy-mode\; send-keys Space\; send-keys '$'\; send-keys Enter
}
zle -N tmux-copy-all
bindkey '^[m' tmux-copy-all
### }}}

スクリプト

基本的なスクリプトの書き方を紹介します。

基本コマンド

コマンド 内容
パイプ
丨丨 失敗した場合、次を実行
& バックグラウンドで実行
&& 成功した時、次を実行
[ 条件式の真偽を判定
. シェルスクリプトの実行

変数の基本

変数は、arg=http://qiita.com/というように設定します。ここで、スペースは不要で、=以降の文字列を代入できます。

そして、中身を使うには、$argとします。

変数は、{}"", ''で囲う時に動作が変わってきます。

arg=http://qiita.com/
コマンド 結果
echo $arg http://qiita.com/
echo ${arg}syui http://qiita.com/syui
echo “$arg syui” http://qiita.com/ syui
echo ‘$arg syui’ $arg syui

シングルクォートを使うと、基本的にそのままの文字列を使うことができます。ダブルクオーテーションを使うと変数を使えます。

コマンドの実行結果を利用する

特殊な変数を使う

変数 内容
$? コマンドの終了コード | 0=成功, 1=失敗
$$ シェル自身のPID
$! 最後に実行したPID
$0 スクリプトの名前
$n 引数 | nは1, 2, 3, 4…などの数字を指定します
$# 引数の数
$@ 全パラメータ
@* 全パラメータ
!$ 最後の引数
!! 前に実行したコマンド
$LINENO この変数を使用している行の行番号
${PIPESTATUS[@]} パイプで連結した各コマンドの終了ステータス

ディレクトリ名を操作する方法

zshでは、ディレクトリの変数設定が楽にできるというメリットがあります。

例えば、以下のようなスクリプトを実行したとします。

~/script/test.zsh
1
2
3
4
5
6
#!/bin/zsh

# スクリプトがあるディレクトリを取得する
dir=${0:a:h}

echo $dir

すると、結果は、/Users/$USERNAME/scriptとなります。

~/script/test.zshのスクリプトを対象とすると、以下のような感じになります。

${0} | ./test.zsh
${0:a} | /Users/syui/script/test.zsh
${0:h} | .
${0:t} | test.zsh
${0:a:h} | /Users/syui/script
${0:a:h:h} | /Users/syui
${0:a:h:t} | script

これは、様々な場面で使用できます。スクリプトといっても、単なる単体コマンドの羅列に過ぎないからです。

例えば、git cloneした場合、ダウンロードしたディレクトリに移動する時です。

$ git clone https://github.com/zsh-users/zaw

$ cd !$:t

ここで、:tは、最後の領域であるzawが入っていることになります。

ファイル名を操作する方法

name=/var/log/boot.log
変数 結果
${#name} 17
${name##*/} boot.log
${name%/*} /var/log
${name%.*} /var/log/boot
${name##*.} log
${name##/var/} log/boot.log

変数を操作する方法

変数 内容
${val:-str} valが定義されていなければstrを返す、定義されていればその値を返す
${val:=str} valが定義されていなければstrを定義して返す、定義されていればその値を返す
${val:n} valの先頭からn文字スキップして、それ以降を返す
${val:n,m} valの先頭からn文字スキップして、それ以降m文字を返す
${@:n,m} シェル引数を扱う。文字ではなく、引数毎の数えかたとなる

変数は、配列としての値をセットすることができます。

val=( str1 str2 str3 );val[5]=five
変数 結果 解説
${val[1]} str1 インデックスnの値を参照
${val[*]} str1 str2 str3 five 全て結合(間はスペース文字)して1つの文字列とする
“${val[*]}” str1 str2 str3 five 全て結合(間は$IFSにセットされた文字)して1つの文字列とする
${#val[*]} 5 配列の要素数
${#val[n]} 4 配列の要素n番の文字列の長さ

コマンド結果をセットする方法

コマンド結果をセットするには、以下の方法があります。

1
2
3
#!/bin/zsh
com=`echo test`
com=$(echo test)

ここで、$comtestになります。

算術式評価結果を変数に取り込むには、(())で囲みます。

$((1 + 2))

結果は、3です。

exprコマンドでも同じことができます。

変数のネスト

1
2
3
4
5
6
#!/bin/zsh
url=https://github.com/syui/middleman.git

$filename=${${url##*/}%.*}

echo $filename

結果は、middlemanになります。

出力

1
2
3
4
5
# 出力なし
$ command > /dev/null 2>&1

# エラーだけ
$ command > /dev/null

条件式

比較

文字列の比較も大体同じ感じでできます。ただし、""などで囲うほうが良いでしょう。

オプション 意味 コマンド
-eq == condition1 -eq condition2
-ne != condition1 -ne condition2
-lt < condition1 -lt condition2
-gt > condition1 -gt condition2
-le <= condition1 -le condition2
-lg >= condition1 -lg condition2

if

条件式の真偽を判定する必要がない時、つまり、コマンドの終了ステータスで判定するときは、[は不要です。

ワンライナーでは、以下のようになります。

1
$ if ! echo "$hoge" | grep -sqE "^fuga$"; then echo "\$hoge is not fuga." ;fi

ちなみに、;は、その行のコマンドを実行して終わります。

しかし、ワンライナーは可読性が低いため、通常、以下のような使い方をします。

test.zsh
1
2
3
4
#!/bin/zsh
if ! echo "$hoge" | grep -sqE "^fuga$"; then
  echo "\$hoge is not fuga."
fi

[を使った式は以下のようになります。

test.zsh
1
2
3
4
5
6
7
8
9
10
#!/bin/zsh
# コマンド結果の文字列が一致した場合の処理
if [ `echo test` = "test" ];then
  # 一致した
  echo ok
# 一致しなかった場合の処理
else
  # 一致しない
  echo no
fi

実行結果は、okです。注意点は、==ではない所でしょうか。

ちなみに、出力が複雑になることが予想される場合は、それぞれの処理の最後にexitを実行しておくと便利です。

多数の分岐は、elifを使います。

条件を一度に判別するには、-a(and), -o(or)を使います。

test.zsh
1
2
3
4
5
6
7
#!/bin/zsh
word=`echo test`
if [ $word = "test" -a $word = "test" ];then
  echo ok
else
  echo no
fi

また、ファイルの有無などをチェックするには、以下を使います。

オプション 内容
-s ファイルサイズが0以外ならば真を返す
-r 読取可能ならば真を返す
-w 書込可能ならば真を返す
-x 実行可能ならば真を返す
-f 通常ファイルならば真を返す
-d ディレクトリならば真を返す
test.zsh
1
2
3
4
5
6
#!/bin/zsh
if [ -d $HOME ];then
  echo ok
else
  echo no
fi

case

個人的には、caseは好んで使用します。

test.zsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/zsh
# pecoコマンドが存在するかどうか調べる
which peco

# 終了ステータスで判定する
case $? in
  # 成功だった場合
  0) echo ok;;

  # 失敗だった場合
  1) echo no;;

  # それ以外
  \*) echo test;;
esac

ちなみに、以下のように複数の条件を一気に指定できます。[]内はまたはの意味です。|またはです。

test.zsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/zsh
read a
case $a in
  # test, Testの場合
  [tT]est) echo ok;;

  # enter, spaceが押された場合
  ""|" ") echo no;;

  # それ以外
  \*) echo test;;
esac

case "$var" in
  a\* ) echo "aで始まる文字列" ;;
  ?b\* ) echo "2文字目がbの文字列" ;;
  [A-Z]\* ) echo "大文字で始まる文字列" ;;
  [!xX]\* ) echo "先頭がxではない文字列" ;;
  \* ) echo "上記のいずれでもない文字列" ;;
esac

for

繰り返し処理には、whileforを使います。

ワンライナーで書くと、例えば、以下のようになります。

1
$ numb=5 ;for (( i=1;i<=$numb;i++ )); do echo $i ;done
test.zsh
1
2
3
4
5
6
#!/bin/zsh
numb=5
for (( i=1;i<=$numb;i++ ))
do
  echo $i
done

実行結果は、以下の通りです。

1
2
3
4
5
6
$ numb=5 ;for (( i=1;i<=$numb;i++ )); do echo $i ;done
1
2
3
4
5

コマンド

ここでは、便利コマンドを幾つか紹介します。

sed

sedは区切り文字にいろいろ使えます。

1
2
$ echo https://qiita.com/ | sed 's#https://qiita.com/#qiita#g'
qiita

-eで繋げられます。

1
2
$ echo https://qiita.com/ | sed -e 's/https/com/' -e 's/qiita/syui/'
com://syui.com/

cut

cutは、-dで区切り文字を設定でき、-fで領域を設定できます。

1
2
3
4
5
6
7
8
$ echo https://qiita.com/ | cut -d / -f 1-2
https:/

$ echo https://qiita.com/ | cut -d / -f 1-
https://qiita.com/

$ echo https://qiita.com/ | cut -d / -f -1
https

head, tail

head, tailは、-, +を使い分けると便利です。

1
2
$ echo https://qiita.com/ | tail -c +9 | head -c -6
qiita

始まりの9文字から、終わりの6文字まで。

つまり、最初の9(8)文字を削除し、最後の6(5)文字を削除し、抽出します。

tr

trは文字列の一括変換を行います。

1
2
3
4
5
6
$ echo -e "test\ntest" | tr -d '\n'
testtest

$ echo test test | tr ' ' '\n'
test
test

sort, uniq

並び替え、重複削除を行います。

1
2
# よく使うコマンドを表示する
$ history 1 | awk '{print $2}' | sort | uniq -c | sort -rn | head

wc

行数などを調べるコマンドです。

1
$ cat ~/.zsh_history | wc -l

find, grep, xargs

1
2
3
4
5
# カレントディレクトリ配下の全ての.txtファイルに対して、testといいう文字列を含む行を表示する
$ find . -type f -name "*.txt" | xargs grep "test"

# ファイルの名前だけ
find . -type f -print0 | xargs -0 grep -l "test"

grep -R -V -nが便利です。

find -type f -type dが便利です。

xargs -J % hoge -n -v %が便利です。

history

1
2
3
4
5
6
7
8
# 全履歴
$ history 1

# 時間や日時
$ history -Di 1

# 削除
$ history -c

pv, bar

進捗を表示できたりします。

pv

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ brew install pv

$ pv -l >/dev/null

# 受信
$ pv file | nc -w 1 somewhere.com 3000

# 送信
$ cat file | pv -s 12345 | nc -w 1 somewhere.com 3000

# ファイルの圧縮
$ (tar cf - . \
| pv -n -s $(du -sb . | awk '{print $1}') \
| gzip -9 > out.tgz) 2>&1 \
| dialog --gauge 'Progress' 7 70

bar

コピーの進捗表示です。

1
2
3
$ brew install bar

$ bar -o output.iso input.iso

jq

jqは、jsonの形成です。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ echo '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}' | jq -r .
{
  "user": "stedolan",
  "titles": [
    "JQ Primer",
    "More JQ"
  ]
}

$ echo '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}' | jq -r '.[]'
stedolan
[
  "JQ Primer",
  "More JQ"
]

$ echo '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}' | jq -r '.user'
stedolan

nc

高速なネットワーク送受信を行います。

1
2
3
4
5
# HTML
$ nc www.example.com 80

# スキャン
$ nc -zv localhost 1-65535

atool

atoolは、圧縮、解凍を自動化するツールの詰め合わせです。

1
2
# 解凍する
$ aunpack test.zip