sifue's blog

プログラマな二児の父の日常 ポートフォリオは www.soichiro.org

ScalaでEclipseデバック可能な実行jarを作るまでの手順 (例:特定のハッシュタグを含むツイートをファイルに保存し続けるアプリ)

最近Scalaでちょっとしたjarアプリを作ることが多いのでその手順をまとめておきます。まだ発展途上とは言え2.0.2になったことでScala IDE for Eclipseも実用に耐えうるところまできているように思います。あとは、リファクタリング機能とクイックフィックス機能がもう少し良くなると良いですが、コンパイルエラーが出た際に、どうするべきかということがポップアップメニューで出るのでその点で助かっています。
ちなみに今回この記事を書こうと思ったのは、今までSbt0.11.2まで利用できた実行jarを作るproguardというプラグインが利用できなくなってしまったこともあり、sbt-assemblyを利用したものを再度書くことにしました。

環境確認

まず、環境情報の確認です。Macのパッケージ管理システムで利用できる2012/07/28現在でできる限り最新安定版を利用しています。


Javaは、Macの場合は

$ java -version

と実行するとインストールされ、バージョンが確認できます。ソースコード付きのJDKを入れたい方は、この記事を参照。
Homebrewはリンク先を参照してインストールの事。XCodeとCommand line toolsのインストールも必要です。
Scalaとsbtのインストールは

$ brew install scala
$ brew install sbt

で完了です。バージョンアップの際には、

$ brew update
$ brew upgrade scala
$ brew upgrade sbt

を実行します。Eclipse 3.6.2とScala IDE for Eclipse 2.0.2のインストールはリンク先のインストール方法に従って下さい。


というわけで、環境は整ったということでお題であるEclipseデバッグ可能な外部jarライブラリを内包する実行可能jarを作ってきます。お題は、


特定ハッシュタグを含むツイートをファイルに保存し続けるアプリ」


です。すでに実装したものが、GitHubの方にMITライセンスでpushしてありますので、ソースコードだけが欲しい場合はこちらをcloneしてお使いください。

プロジェクトの作成

まず、プロジェクトの作成です。ここではtweet_recorderとします。有りそうな名前ですねw

$ mkdir tweet_recorder
$ cd tweet_recorder

次にjarを作るまでに雛形を作成します。なお基本的にこのtweet_recorderディレクトリから操作していきます。

$ mkdir -p src/main/scala
$ echo 'object TweetRecorder { def main(args: Array[String]) = println("Hi!") }' > src/main/scala/TweetRecorder.scala
$ vim build.sbt

build.sbtを編集

name := "tweet_recorder"

version := "1.0"

scalaVersion := "2.9.2"

次に念のためにsbtもバージョン指定しておきます。

$ mkdir project
$ vim project/build.properties

project/build.propertiesを編集

sbt.version=0.11.3

とここまでで、プロジェクトのひな形は完成。



というわけで早速sbtでビルド、実行してみます。

$ sbt
> compile
[success] Total time: 15 s, completed 2012/07/29 9:00:22
> run
Hi!
[success] Total time: 1 s, completed 2012/07/29 9:00:36
> exit

これで大丈夫なことを確かめます。

実行jarの作成

次にjar化できるようにします。他にもjar化させるものはいくつかありますがsbt-assemblyが非常に良い出来だったので、これを使います。

$ vim project/plugins.sbt

project/plugins.sbtを編集

resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.3")
$ vim build.sbt

build.sbtを編集

import AssemblyKeys._ // put this at the top of the file

assemblySettings

name := "tweet_recorder"

version := "1.0"

scalaVersion := "2.9.2"

mainClass in assembly := Some("TweetRecorder")

他にも設定が、github内に書いてありますが、ここではmainメソッドのあるクラスの定義だけ設定します。
そして早速jarを作ってみます。assemblyコマンドでjar作成とのことです。
早速、jarを作成、実行してみましょう。

$ sbt
> assembly
[info] Done packaging.
[success] Total time: 107 s, completed 2012/07/29 9:14:19
> exit
$ java -jar target/tweet_recorder-assembly-1.0.jar
Hi!

これでOKそうですね。

実行jarへの3rdパーティjarライブラリの梱包

ちなみにもうライブラリとしてtwitter4jを使うことがわかっているので、twitter4jの必要なライブラリとソースをプロジェクトにコピーしてビルドしてみましょう。tmpディレクトリに一度ダウンロードし、削除します。

$ mkdir lib
$ mkdir lib-src
$ mkdir tmp
$ cd tmp
$ curl -O http://twitter4j.org/en/twitter4j-2.2.6.zip
$ unzip twitter4j-2.2.6.zip
$ cp lib/twitter4j-core-2.2.6.jar ../lib
$ cp lib/twitter4j-stream-2.2.6.jar ../lib 
$ cp twitter4j-core/twitter4j-core-2.2.6-sources.jar ../lib-src 
$ cp twitter4j-stream/twitter4j-stream-2.2.6-sources.jar ../lib-src
$ cd ..
$ rm -rf tmp
$ sbt
> assembly
[info] Including twitter4j-core-2.2.6.jar
[info] Including twitter4j-stream-2.2.6.jar
[success] Total time: 1 s, completed 2012/07/29 9:32:14
> exit
$ java -jar target/tweet_recorder-assembly-1.0.jar
Hi!

これでライブラリの実行jarへの内包も大丈夫そうです。


Eclipseへのsbtプロジェクトのインポート

次に、Eclipseにインポートできるようにします。sbteclipseを使います。

$ vim project/plugins.sbt

project/plugins.sbtを編集して、末尾に追記します。

resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.3")

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")

編集後、eclipseコマンドを実行します。

$ sbt
> eclipse
[info] Successfully created Eclipse project files for project(s):
[info] tweet_recorder
> assembly
[info] Including twitter4j-core-2.2.6.jar
[info] Including twitter4j-stream-2.2.6.jar
[success] Total time: 1 s, completed 2012/07/29 9:32:14
> exit
$ java -jar target/tweet_recorder-assembly-1.0.jar
Hi!

eclipseプロジェクトの作成も、実行jarの作成もOKそうです。


次に、Eclipseへのインポートです。ScalaパースペクティブのPackage Explorerビューの右クリックメニューにて。Import > General > Existing Projects into Workspaceを選択して、Nextを押します。


Select root directoryで、プロジェクトのフォルダを選択して、Finishボタンを押します。この際に、copyをせずにそのままそのフォルダを利用します。これは今後sbtでビルドを利用するためです。

Twitter4jのStreamingAPIを使った実装とビルド

これでプロジェクトのインポートが終わったので、早速ちょっとコードを書いてデバッグで止めていましょう。
早速サンプルコードを書いてみます。

TweetRecorder.scalaを編集して

import twitter4j.conf.ConfigurationBuilder
import twitter4j.TwitterStreamFactory
import twitter4j.FilterQuery
import twitter4j.StatusListener
import twitter4j.Status
import twitter4j.StatusDeletionNotice
import java.io.PrintWriter
import java.io.FileWriter
object TweetRecorder { 
  def main(args: Array[String]) = {
    val conf = new ConfigurationBuilder().setUser(args(0)).setPassword(args(1)).build
    val twitterStream = new TwitterStreamFactory(conf).getInstance()
    twitterStream.addListener(new Listener)
    twitterStream.filter(new FilterQuery().track(args.slice(2, args.length)))
  }
  class Listener extends StatusListener {
    override def onStatus(status: Status) = {
      val tweet = status.getCreatedAt().toLocaleString() +
      	"," + status.getUser().getScreenName() + 
      	"," + status.getText() 
      val writer = new PrintWriter(new FileWriter("tweet_recoder.csv", true))
      writer.println(tweet)
      writer.close
      println(tweet)
    } 
    override def onDeletionNotice(statusDeletionNotice: StatusDeletionNotice) = {}
    override def onTrackLimitationNotice(numberOfLimitedStatuses: Int) = {}
    override def onException(ex: Exception) = {}
    override def onScrubGeo(userId: Long, upToStatusId: Long) = {}
  }
}

これでOK。起動する時に第一引数がtwitterのアカウントのID、第二引数がtwitterのアカウントのパスワード、第三引数以降は追跡したいキーワード(英単語か#ではじまるハッシュタグのみ) を半角スペース区切りで追加という感じになります。右クリックでDebag As > Scala Applicationを選択してデバッグ実行で引数が無いという例外が投げられて失敗したあと。
虫アイコンのドロップダウンメニューのDebug ConfigurationのArgumentsタグでそれぞれの引数を設定して実行します。


今回は、単語をすごい量のツイートが流れていそうなhttpに設定して実行します。コンソールに

2012/07/29 11:06:30,Vasilisa_Anime,http://t.co/nKcvZJw7
2012/07/29 11:06:30,Neylianavera,esteeeen; x_x @Georgejsm. http://t.co/Ap5vLa1R

のように表示されればOK。今回は日付、ユーザーID、ツイートをカンマ区切りで表示してます。


無論ブレークポイントを貼ってデバッグすることもできます。


最後にビルドして実際に動くか確かめて見ましょう。
今回は、2chまとめのタグ#MT2とニコ動の#nicovideoで検索してみます。

$ sbt
> assembly
[info] Including twitter4j-core-2.2.6.jar
[info] Including twitter4j-stream-2.2.6.jar
[success] Total time: 1 s, completed 2012/07/29 9:32:14
> exit
$ java -jar target/tweet_recorder-assembly-1.0.jar sifue password \#MT2 \#nicovideo
2012/07/29 11:35:08,nicorank_bot,毎時ランキング第1位:じょしらく 第三席「無情風呂」「浅草参り」「真田小ZOO」  http://t.co/0U9SZFnQ #nicovideo #so18447313 2012/07/29 11:35 現在
2012/07/29 11:35:09,2chtitle,「あっ、こいつインド人だな」って思う仕草 インド人とのつきあい方?インドの常識とビジネスの奥義 を Amazon でチェック!  http://t.co/Lf2sWYQ5 #MT2 #まとめ
2012/07/29 11:35:12,zyazya11,RT @Mell_Ta: ニコニコ有名歌い手がポケモン割れ発覚 http://t.co/qQh9eCvL #MT2 今ぐるたみんが熱い

以上のように表示され無事利用できるようです。これで好きなハッシュタグのツイートなどを保存して解析したりするのに使えますね。
ちゃんとtweet_recoder.csvというファイルを確かめても保存できているようです。


以上でScala2.9.2でsbt-assemblyを使ってEclipseでデバック可能な3rdパーティjarを含む実行jarを作るまでの手順を終わりとします。お疲れ様でした。

イングリッシュ記法(名前に情報を追加する)は、誰もが行うべき重要な変数命名法

リーダブルコードを読み終えました。

リーダブルコード ―より良いコードを書くためのシンプルで実践的なテクニック (Theory in practice)

リーダブルコード ―より良いコードを書くためのシンプルで実践的なテクニック (Theory in practice)

Java, JavaScript, PHPがメインな自分としては、過去に読んだEffective JavaJavaScript: The Good Parts、Clean Code、リファクタリング、プログラミング作法と基本的に同じ情報ではあったのですが、ここ最近のトレンドを取り込み、薄い本としてまとめているというところに非常に価値のある本でした。


その中でも一番のお気に入りは、「2.4 名前に情報を追加する」の項で書かれているハンガリアン記法と区別してイングリッシュ記法を提唱している以下の部分です。

これってハンガリアン記法なの?

ハンガリアン記法というのは、Microsoft社で広く使われていた命名規則だ。すべての変数名の接頭辞に「型」をつける。例えばこんな感じだ。

変数名 意味
pLast あるデータ構造の最後の要素を指すポインタ(p)
pszBuffer ゼロ終端(z)の文字列(s)バッファを指すポインタ(p)
cch 文字(ch)のカウント(c)
mpcopx カラーポインタ(pco)からX軸のポインタ(px)を指すマップ(m)

これも「名前に属性を追加」しているけれど、もっと厳密で規律のあるシステムだ。
一方、僕達が提唱しているのは、もっと大まかで規律のゆるいシステムだ。必要な時にだけ変数の大切な属性を見つけ出して、それを読みやすくして名前に追加する。これをハンガリアンならぬ「イングリッシュ記法」と呼んでもいいだろう。


この項では、変数名を

var start = (new Date()).getTime();

ではなく

var start_ms = (new Date()).getTime();

と書いたりして、変数名に属性を追加しわかりやすくしようということを言っています。


載っていた例としては

状況 変数名 改善後
passwordはプレインテキストなので、処理をする前に暗号化すべきである。 password plaintext_password
ユーザーが入力したcommentは表示する前にエスケープする必要がある。 comment unescaped_comment
htmlの文字コードUTF-8に変えた。 html html_utf8
入力されたdataをURLエンコードした。 data data_urlenc

といったものです。


このイングリッシュ記法は本当に重要で、変数をわかりやすくする他、変数名にあえて属性を入れることで変数の意図しない使い回しを避けさせる効果もあります。

var start = new Date();
if('ms' === type){
    start = start.getTime();
}else if('array' === type){
    start = [start];
}else if('sec' === type){
    start = start / 1000;
}else if('string' === type){
    start = "" + start;
}

// ... この数百行程度の別なコード

// TODO 1年後、startを使った処理を他人が書く。バグらないだろうか?

こういうコードが本当に多いのも難点ですが...、もしこのstartという変数がstart_msやstart_arrayだとすれば、さすがにミリ秒や配列以外のものを代入しようとは思いませんし、また後でこの変数を利用する人が余計な型チェックや状態チェック、特にsecとmsの判定などをせずに、安心して変数をつかうことができます。


このようにイングリッシュ記法には、余計なコードを排除し、わかりやすくなってバグを減らせるという素晴らしい効果があります。しかもエディタの入力補完があるので、総コーディングタイプ数はそんなに変わりません。


あとこれは前職の先輩に教えてもらったテクニックなのですが、選別に使いたい属性を先にしておくと入力補完機能のあるエディタのあるEclipsevimemacsでは非常に良い副作用があります。

var buttonTitle = null;
var buttonTextArea = null;
var buttonCombobox = null;
var labalTitle = null;
var labalTextArea = null;
var labalCombobox = null;
var titles = null;
var mapCombboxContent = null;

大抵コーディングする場合には、そこに書くべき変数の型というのは決まっていることが多いです。 この場合はtitを押して入力補完を実行するとすぐにタイトルの配列titlesが取れます。
これが、もしボタンやラベルまでtitleが最初に付く変数になっていると、後でボタンなのかラベルなのか配列なのかを候補の中から選ばなくてはいけなくなってしまいます。


実装の内容にもよりますが、属性をつけるのを前にするか後にするかでコーディングスピードを変えることができる、というのもこのイングリッシュ記法のメリットだと思います。この辺も考えながら実装するとより、楽な実装ができるのではないかと思います。
ぜひ、イングリッシュ記法を実践してみてください。では楽しい開発を!

// 2012/07/21 変更 最後の例がシステムハンガリアンを強制するような内容であったのでJavaScriptで書き直し

Mac OSXのEclipseにJavaのソース付きのJDKを設定する方法

MacJDKをインストール新たにインストールしたり、今回みたいにFlashback対策のようなセキュリティアップデートがされた際に、JDKを再インストールするわけですが、いつものソース付きJDKインストール、設定の仕方を忘れるのでまとめました。

1. MacのアップデートでJavaのバージョンアップが走ったことを確認する

2. Apple Developerのダウンロードで最新のJava for Mac OS X 2012-01 Developer Packageをダウンロードする

3. EclipseJREデフォルトのものから変更する

/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

のものが登録されているが、新しいJREを以下のホームのものを登録する

/Library/Java/JavaVirtualMachines/1.6.0_31-b04-413.jdk/Contents/Home

デフォルトのものは、勝手に読み込まれる事もあるので除去しても良い。

4. Javaプロジェクト内でStringなどの型を参照して、ソースを添付する

/Library/Java/JavaVirtualMachines/1.6.0_31-b04-413.jdk/Contents/Home/src.jar

これがJavaソースコードになっているので添付する。
以上



これでJavaのソースのコードが実際に読めるようになり、Java自体のパフォーマンスを観たり、Javadocを実装を観ながら確認したりできます。幸せ。

Scala+sbt+EclipseでUTF-8文字とUIを含む実行jarのアプリケーション作成、開発方法

sbt0.11.3以上をお使いの方はこちら


全国のScalaファンのみなさん、こんにちわ!
最近よくScalaをいじっていることもあって、Scalaを使ってUTF-8の文字を表示しつつ、SwingのUIなんかを表示させる実行jarを作ったりすることがあり、いろいろと開発環境の設定が面倒くさい所もあるのでその手順をまとめておきました。
Scalaを使って日本語を使ったUIを表示させることのできる実行jarをビルドするHelloWorld!と考えてもらえれば良いです。無論、UTF-8文字やUIを含まなくてもこの方法でビルドできます。

まず使っている使っている環境です。

となります。


というわけで、早速はじめていきます。プロジェクト名をhelloswingにしてにしてありますが、その辺は適宜変更して使って下さい。ちなみに、自分のワークスペースは、

 $ cd ~/Dropbox/Dev/sbt

というパスから開始してやっていますが、その辺も適宜調整お願いします。

sbtのプロジェクトの作成

 $ mkdir helloswing
 $ cd helloswing
 $ mkdir -p src/main/scala
 $ mkdir -p src/test/scala
 $ echo 'import javax.swing.JOptionPane; object Helloswing { def main(args: Array[String]) = JOptionPane.showMessageDialog(null, "こんにちわ!世界!") }' > src/main/scala/Helloswing.scala
 $ vim build.sbt

ここまでで、Mavenでよく使われているフォルダ構成の作成とMainにてダイアログを表示させる処理を実装しました。最後にbuild.sbtを編集します。別にvimでなくてもお好きなエディタで以下のような内容にします。

name := "helloswing"

version := "1.0"

scalaVersion := "2.9.1"

これで、プロジェクトは完成です。
ビルド後、実行してみましょう。

$ sbt
  > run


以上のようなメッセージダイアログが出ればプログラムは完成です!
Ctrl+Dでsbtは終了させることができます。

実行jarのビルド

というわけで今度はここから実行jarを作成できるようにします。そのためにprogaurdというsbtのプラグインをインストールしていきます。
siasia/xsbt-proguard-plugin · GitHub
以上の本家を参考にしていますが、sbt 0.11.1とsbt0.11.2でフォルダ構成が違うので要注意です。では進めていきます。

 $ mkdir project
 $ vim project/plugins.sbt

場合によっては、projectフォルダは既にあるかもしれません。次に以下を追記します。

libraryDependencies <+= sbtVersion(v => "com.github.siasia" %% "xsbt-proguard-plugin" % (v+"-0.1.1"))

これがプラグインの依存関係を追加する設定です。

 $ mkdir project/project
 $ vim project/project/Build.scala

次に以下を追記します。

import sbt._
object PluginDef extends Build {
	override def projects = Seq(root)
	lazy val root = Project("plugins", file(".")) dependsOn(proguard)
	lazy val proguard = uri("git://github.com/siasia/xsbt-proguard-plugin.git")
}

これは依存関係がなかったらGitHubからダウンロードしてくるという設定です。

 $ vim build.sbt

以上を編集して、以下の用に処理を開始するprogaurdの設定の読み込みと、Mainのobjectの設定を追記します。

name := "helloswing"

version := "1.0"

scalaVersion := "2.9.1"

seq(ProguardPlugin.proguardSettings :_*)

proguardOptions += keepMain("Helloswing")

これでOK。
最後に、scala-liblary.jarをlibフォルダに同梱して、実行jarをビルドしてみましょう。

 $ mkdir lib
 $ cp /usr/local/Cellar/scala/2.9.1-1/libexec/lib/scala-library.jar lib
 $ sbt
   ..
   > update
   ..
   > proguard
   ..
   [success] Total time: 30 s, completed 2012/04/14 17:08:37

これで実行jarの作成完了です。


実行jarの場所は、以上のスクリーンショットのように

target//.min.jar

という形式になります。minがついていないものはscala-library.jarが含まれていないものです。


というわけで、helloswing_2.9.1-1.0.min.jarをダブルクリックしてみましょう。以下のように表示されれば、実行jarビルドは成功です。

Eclipseへのインポート及びデバッグ実行

さて、これを今度はEclispseで動かしてみたいと思います。そのためにtypesafehub/sbteclipse · GitHubというプラグインを使います。このサイトの手順にしたがって、

 $ vim project/plugins.sbt

以上のファイルを編集し、依存関係を追加します。

libraryDependencies <+= sbtVersion(v => "com.github.siasia" %% "xsbt-proguard-plugin" % (v+"-0.1.1"))

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.0.0")

最後の一行を追加して最終的にこのようになります。Eclipseに読み込む設定をします。

 $ sbt
   > eclipse
   [info] About to create Eclipse project files for your project(s).
   [info] Successfully created Eclipse project files for project(s): helloswing

これで完了です。とは以下のようにScala IDEをインストールしたEclipseに読み込みます。


プロジェクトエクスプローラーの右クリック > Import > General > Existing projects into workspaceから、以下のようにコピーをせずにインポートしましょう。(でないと同期してくれなくなります)


じつは、ここからが肝で、エラーが出るのでそれを解消します。まず、プロジェクトエクスプローラーで、helloswingのルートノードを選択して、右クリック > Propertiesから。



Java Build Pathに重複している、Scala Libraryの取り除きを行います。



次に、ResourceからText file encodingがSJISになっているので、UTF-8に変更します。

UTF-8



最後に、Scala Compilerで、プロジェクトの設定を使うようにして、追加コマンドライン引数に-encoding UTF-8加えます。

-encoding UTF-8



これでOKです。早速Helloswing.scalaを開いて、右クリック > Debug As .. > Scala Applicationsからデバッグしてみましょう。



これで無事起動出来ればOKです。無論、ブレークポイントを貼ってデバッグすることもできますので、あとはお好きに。
実行jarの作成は、sbtから行いますので sbt→updatem→proguardという手順でビルドできます。あとはJenckinsにsbtのプラグインを入れてデイリービルドなり、デイリーテストなりをやってみてください。


あと、sbtで依存ライブラリを追加する際には、再度eclipseコマンドを実施してインポートの手順を踏むことでうまくいきます。


以上です。お疲れ様でした。

SSHを介してVimを使う人に感動的なESCキーを押すとESCキーが効きつつIMEがオフになる設定(Google日本語入力とVimの相性は最強!)

Vimをお使いの皆さん、こんにちわ。
Vimを使って日本語のコメントやドキュメントを書かなきゃいけな人をいつも悩ますのが、IMEのモードの問題です。


(IMEオン, IMEオフ) x (挿入モード, コマンドモード, ビジュアルモード) の、この全6パターンを意識しながら操作するのは非常に間違いやすいです。特に日本語を挿入モードで書いたあと、コマンドモードに抜けるとよくIMEがオンになっていて、あうぅ。。とよくなってしまう。


KaoriYaさんのMacVimやGVimを使っている方は幸せです。

set imdisable

という設定をvimrcに書く手があります。これで挿入モードから抜ける際、入る際に必ずIMEがオフになります。


問題は、コンソールやiTermなどからSSHを介してサーバー上のVimを使っている場合です。この設定が効きません。そりゃ普通はサーバー上にIMEはありませんので仕方ありません。なので、この問題がなかなか解消されなかったのです。
中にはこの機能のためにiTerm2の自家製ビルドを作っている方すらいます。


しかし!この由々しき問題を解決してくれたのがGoogle日本語入力です!インストールしてデフォルトのIMEに設定の後、

環境設定... > 一般タブ > キー設定 > キー設定の選択

にて、一度、キーの設定を「ことえり」を選択した後、編集のコンボボックスから新しいエントリーを追加して以下のように、Escapeを押すと「キャンセル後IMEを無効化」というエントリーを全状態に対して6個追加すると、あら不思議!

なんと、Escapeで挿入モードを抜けると必ずIMEがオフになります。これは他のキーのリマップのソフトで設定するのと違ってEscapeキー自体の機能が失われません!
MacOSX LionのiTerm2では検証済みです。Macの場合はターミナルからではダメですし、MacVimではを2回押す必要があります。あと、WindowsXPTeraTermでも、を2回押さねばダメでした...残念、それでもMacVimやTeraTermにはIMEのオンオフでカーソルの形状を変えるオプションがあるので二回押しでも便利かもですが。


これで、SSHを介してVimを使っている方はかなり楽に日本語の入力をサーバー上で行うことができるようになるのではないでしょうか。


ぜひ、ことえりMS-IMEから乗り換えてGoogle日本語入力で快適なVimライフを送ってみてください!


追伸
なお、自分のvimrcは、GitHubにて公開しており、MacOSX, CentOS, FreeBSD, MiracleLinuxにて共有して使っています。日々精進中ですが、もしよかったら見てみてください。

vimを使う上で欠かせないproject.vimのヘルプの日本語訳(意訳)


最近project.vimを使ってプロジェクトツリーを表示してソースを読む事が多いのですが、実際には、:Project {filename}で起動した後、

  • \Cで、フォルダ再帰的にプロジェクトファイルを作るウィザートを起動する
  • \Rで、フォルダ再帰的にプロジェクトファイルを再作成する

以上二つしか使ってきませんでした。
ただ他にもいろいろな使い方ができるようで、そのためにヘルプを読んでいたのですが、その際に作った意訳が他の人にも役立つかもしれないので掲載します。質が悪いので野良翻訳なので、原文も一緒です。


ちなみに、この度知った役に立ちそうなコマンドは、

  • \Gで、現在のプロジェクト以下を全てgrep
    • vimのctagsを使ったタグジャンプは定義元には飛べますが参照元には飛べないので、これを利用
  • で、プロジェクトウインドウの最大化、最小化
  • \sで、水平分割して新たにファイルを表示
  • zMで、プロジェクトを全てたたむ
  • Ctrl+↑or↓で、ファイル名の並び替え
  • プロジェクトファイルに # でコメント行としてTODOなどを記述
  • ファイルを追加する時は、プロジェクトファイルに行追加して開くだけでできる

でした。
in.vimやout.vimを使っていろいろカスタマイズもできそうです。ここまでやると本当にIDE並みです。


なお、project.vimの配布元は
project.tar.gz : Organize/Navigate projects of files (like IDE/buffer explorer)
です。ここでダウンロードできる最新版のproject.txtを意訳しました。:help projectで読めます。


かなり適当な訳ですが悪しからず。
project.txtの日本語訳(意訳)

project.txt
		このプラグインは、複数のソースによる複数のプロジェクト
		を管理するためのものです。
		Vimのバージョンは6.xと7.xに対応しています。
		最終更新日時: Fri 13 Oct 2006 10:20:13 AM EDT

原著: Aric Blumer <aricvim at charter.net>
翻訳(意訳): Soichiro Yoshimura <yoshimura at soichiro.org>

	内容:

		コマンド
		継承
		マッピング
		マッピング追加
		設定
		設定例
		TIPS


このプラグインは、よくアクセスするファイルのリストに簡単に
ナビゲーションするための基本的な機能があります。
このリストはVimウインドウの左側に表示されます。
また<Return>かファイル名でダブルクリックするとリストのファイルを
開くことができます。またファイルエクスプローラーを使って簡単に
ディレクトリ階層を探索することができます。

ディレクトリの変更と選択したファイルへのVimスクリプトの実行を
プラグインにさせることができます。例えば、$PATH内のコンパイラを
含むような環境の変更ができます。これは異なる環境を使う複数の
プロジェクトにクイックフィックスなどを簡単に利用する事ができます。

その他の含まれる特徴:
	プロジェクトの全てのファイルの読み込み/除去(\l, \L, \w, and \W)
	プロジェクト内の全てのファイルをgrepする (\g and \G)
	ユーザスクリプトのファイルへの実行(ファイル上の外部プログラムも可) (\1 through \9)
	プロジェクト内の全てのファイルへのユーザースクリプトの実行 (\f1-\f9 and \F1-\F9)
	高いレベルでのユーザー設定機能
	the XXXX://...という形式を用いるnetrwとの連携 (ftp, rcp, scp, http)

これら全てはシンプルテキストとvimrc内のいくつかのグローバル変数に
記述します。

必ず、noconpatible設定をvimrcファイルにセットしてください。
もしこのプラグインを使わない場合には、vimrcに
	:let loaded_project = 1
を記述してください。

==============================================================================
コマンド

このプラグインを使うために、 ~/.vim/pluginディレクトリに設置してください。
次に、このプラグインを使うためには、
    :Project
or 
    :Project {file}
以上のコマンドを実行します。

特にファイルを指定しない場合は、$HOME/.vimprojects が読み込まれます。

起動時一緒にProjectのウインドウを起動するためには、
	vim +Project
として起動します。

Note 一つのファイルに対しては一度しか :Projectを実行できません。
もし、Projectのファイルを変更したい場合は、
Projectバッファ内で:bwipeを実行した後、プラグインを再実行して下さい。

複数のプロジェクトが{ }で区切られて同じファイルで表示されます。
プロジェクト階層の中に複数のプロジェクトをネストすることができます。
{ } で表示されていない行はファイル名とみなします。
空行と#以降の文字は無視されます。

Vimの通常の折り畳み機能を使っているため、そのまま折り畳みコマンドが
使えます(zaで開閉、zaで再帰開閉など) 最初の行をダブルクリックすると
その折り畳みが開いたり閉じたりします。ファイル名上にカーソルを置いて
<Returen>またはダブルクリックでファイルが右側に表示されます。
もしファイルが存在していれば右側にウインドウを作り、
CTRL-W_p(右のウインドウに移動)を使ったのと同等の動きをします。

それぞれのプロジェクトのエントリは以下の形式です:

project_entry ::=
	<Description>={projpath} [{options}] {
	[ filename ]
	[ project_entry ]
	}

{options} は、ひとつ以上を同じ行に記述します:

CD={path}
	in={filename}
	out={filename}
	filter="{pat}"
	flags={flag}

Note プロジェクトエントリ内にプロジェクトエントリが存在できます。
これでプロジェクトの階層をセットアップできます。

<Description>部分は、折り畳みの際にも表示されますが=を含めません。
また=の横にはスペースを記述できません。

{projpath}はファイルが存在するパスで、環境変数なども含められます。
相対パスの場合、プラグインはパスをプロジェクトの親や親の親から構築します。
基本的に、プロジェクトエントリは、絶対パスで指定してください。
以下にプロジェクトの継承の例を表記します。{projpath}は、スペースを
含める事ができます。しかし、Vimの通常のエスケープが必要です。
二つの同じディレクトリの例を示します:

	Example=/my/directory/with\ spaces {
	}
	Example="/my/directory/with spaces" {
	}

Windowsではこれがオススメです:

	Example="c:\My Documents" {
	}

しかし、これでも十分にスマートです:

	Example=c:\My\ Documents {
	}

CD= は折り畳みの中に入れる、ディレクトリを示します。
例えば、:makeでローカルのMakefileを使えるようにできます。
CD=. は、{projpath} と現在の作業ディレクトリの全てと同等なものになります。
もし、CDが省かれたときは、ディレクトリは変更しません。
なお =. の横にはスペースは記述できません。CDは相対パスも可能です。
project-inheritanceの例をご覧ください。このやり方は、netrw プロジェクトから
無視されています。{projpath}と同様にスペースもパスの中に記述できます。

in= と out= は、ファイルバッファに入ったとき、出た時に、実行される
vimスクリプトです。次のように環境を立ち上げたり、終了させたりする
ことができます:

in.vim: >
	let $PROJECT_HOME='~/my_project'
	" Put the compiler in $PATH
	if $PATH !~ '/path/to/my/compiler'
		let $PATH=$PATH.':/path/to/my/compiler'
	endif

out.vim: >
	" Remove compiler from $PATH
	if $PATH =~ '/path/to/my/compiler'
		let $PATH=substitute($PATH, ':/path/to/my/compiler', '', 'g')
	endif

これで現在編集中のファイルに会わせて適切な環境で:makeすることができます。
もしスクリプトへのパスが相対パスの場合は、{projpath}からの相対パスに
なります。この設定はサブプロジェクトで設定しない限り、サブプロジェクトに
継承されます。netrwプロジェクトを使うたまには、 in=とout=が絶対パスか
ローカルとなるようにパス設定してください。

filter=glob()の ファイルパターンを記述します。 \r (<LocalLeade>r) で。
ファイルのリストを再生成します。フィルタの値は存在しなくてはならず、
複数のファイルパターンを含められます。もしフィルタが省略された場合、
* がパターンとして使われます。 =.の横にはスペースは記述できず、
サブプロジェクトもそこで記述しない限り設定を継承します。

flag= は特に折り畳みに関する機能を設定できます。
一般的なニーモニックスキーマは、小文字でオフ、大文字でオンを表します。
{flag} には以下のものがあります。
charactors:

	フラグ	説明
	l	再帰的な不折り畳みの設定
	r	表示された時にリフレッシュするかどうか(非再帰)
	S	リフレッシュや作成時にソートする
	s	リフレッシュや作成時にソートしない
	T	リストの上方への重力のオン
	t	リストの上方への重力オフ(リフレッシュ時)
	w	再帰的な折り畳みのオフ

フラグはサブプロジェクトに継承されません。

折り畳みの外側の文字は無視されます。

==============================================================================
継承

二つのプロジェクトファイルを比べて継承を紹介します。

	Parent=~/my_project CD=. filter="Make* *.mk" flags=r {
	 Child1=c_code {
	 }
	 Child2=include CD=. filter="*.h" {
	 }
	}

Child1のパスは~/my_project/c_codeです。
これは ~/my_projectから継承します。なおCDも継承します。
ここでは、親のCDは.となっています。
親のパスは~/my_projectです。
Child1は、CDの~/my_projectを継承している事になります。
最後にChild1はフィルタを親から継承します。しかしフラグは継承しません。

Child2は~/my_projectのみを継承しています。

以下は、全てを継承無しに同等に書いた場合です。
>
	Parent=~/my_project CD=. filter="Make* *.mk" flags=r {
	 Child1=~/my_project/c_code CD=~/my_project filter="Make* *.mk" {
	 }
	 Child2=~/my_project/include CD=~/my_project/include filter="*.h" {
	 }
	}

実際のプロジェクトでは、Child1は、親のフィルタを継承したくないはずです。
これは、コンセプトだけを示す例です。なお、\iでいつでも
プロジェクトの継承の状態をを表示することができます。

==============================================================================
マッピング

マッピング	アクション ~

\r	プロジェクトのリフレッシュ、リフレッシュで消えないようにするには、
	行末に# pragma keepを記述。ちなみにnetrwは利用していない。
\R	再帰的な\r
\c	対話形式でプロジェクトエントリを作成
\C	フォルダ再帰的な\c
<Return>
	ファイルを開きそのウインドウにカーソルを移動
<S-Return>
\s
	水平報告にファイルを開き、そのウインドウにカーソルを移動
\S
	プロジェクト内のファイルを全て読み込み垂直方向に分割表示(危険!)
<C-Return>
\o
	新しいウインドウでファイルを開く。
<M-Return>
\v
	新しくファイルを開くがカーソルはそのまま。
<2-LeftMouse>
	ダブルクリックと一緒
<S-2-LeftMouse>
	<S-Return>と一緒
<C-2-LeftMouse>
	<C-Return>と一緒
<RightMouse>
	プロジェクトウインドウの枠を広げ最大化したり、戻したりする
	toggle between a width of
		g:proj_window_width + g:proj_window_increment
	and
		g:proj_window_width.
<space>
	<RightMouse>と一緒
<CTRL-Up>
\<Up>
	ファイルの一覧上で上方向に並べ替えしながら移動
<CTRL-Down>
\<Down>
	ファイルの一覧上で下方向に並べ替えしながら移動

\i	今のプロジェクトのステータスや継承関係を表示
\I	ファイルの完全修飾名を表示
\1 - \9
	g:proj_run{x}で設定しておいたのコマンドを起動
	詳しくは、設定のg:proj_run1 ...  g:proj_run9の項を参照

\f1-\f9
\F1-\F9
	g:proj_run_fold{x}で設定しておいたコマンドを実行
	詳しくは、設定のg:proj_run_fold1 ...  g:proj_run_fold9を参照
\0	1-9に登録してあるコマンドを表示
\f0	f1-f9登録してある登録してるコマンドを表示
\l	今のプロジェクトのファイルを読み込む
\L	今のプロジェクトのサブプロジェクトも含めてファイルを読み込む
\w	今のプロジェクトの読み込んでいるファイルを閉じる。保存もされる。
\W	今のプロジェクトのサブプロジェクトも含めてファイルを閉じ、保存する。
\g	今のプロジェクトのファイルをgrepする
\G	今のプロジェクトのサブプロジェクトも含めてgrepする
\e	現在のプロジェクトの環境設定をセットアップする
\E	今いるプロジェクトのパスからファイルエクスプローラーを起動する
<F12>	'g' フラグが g:proj_flags に設定されているなら、
	ウインドウの開閉をトグルする

==============================================================================
マッピング追加

($HOME/.vimproject_mappingsで、マッピングを追加できますが、翻訳を省略します。
 :help projectを参照ください。すみません。)

==============================================================================
設定

(翻訳を省略します。:help projectを参照ください。すみません。)

==============================================================================
プロジェクトファイルの設定例

~/.vimprojects の設定例です。

  1	My Project=~/c/project CD=. in=in.vim out=out.vim flags=r {
  2	 Makefile
  3      in.vim
  4      out.vim
  5	 GUI Files=. filter="gui*.c gui*.h" {
  6	  gui_window.c
  7	  gui_dialog.c
  8	  gui_list.c
  9	  gui.h	       # Header file
 10	 }
 11	 Database Files=. filter="data*.c data*.h" {
 12	  data_read.c
 13	  data_write.c
 14	  data.h
 15	 }
 16	 OS-Specific Files {
 17	  Win32=. filter="os_win32*.c os_win32*.h" {
 18	   os_win32_gui.c
 19	   os_win32_io.c
 20	  }
 21	  Unix=. filter="os_unix*.c os_unix*.h" {
 22	   os_unix_gui.c
 23	   os_unix_io.c
 24	  }
 25	 }
 26	}

(数字は、%s/^ \+[0-9]\+\t//g などで置換して数字は取り除いてください。)

==============================================================================
TIPS

1.  以下のように入力してプロジェクトエントリを作成できます。

	Label=~/wherever CD=. filter="*.c *.h" {
	}
<
    入力した後に\rを押します。そうするとディレクトリから、ファイルが
    読み込まれます。これは\cのウィザードをダイアログ形式でなくやる方法です。


2.  プロジェクトファイルは、ファイルを追加、削除、並べ直しをファイルのリスト
    上でいつでもおこなうことができます。

3.  一度閉じてしまったプロジェクトを再度開く際は、
	:Project
    と入力するだけで大丈夫です。

    もし、g:proj_flagsに'm'が設定されていると、CTRL-W_oでもう一度表示させる
    ことができます。

4.  プロジェクトにファイルを足す簡単な方法があります。
    普通に、プロジェクトエントリ内にファイルを挿入、記述してください。

5.  quickfixがファイルを読み込む際、ファイルの変更が適用されない時があるれど、
    \Lを押す事でファイルが再帰的に読み込み直されます。

6.  再帰的に全て折りたたみたい際にはzMが利用できます。

7.  上級者向け、 function Project_GetAllFnames()でプロジェクトのファイル名
    をサブプロジェクトを含めて取得できます。他にも、Project_ForEach()、
    Project_GetFname(line_number)などがあります。

8.  :Projectを\Pで実行する以下の設定をvimrcに記述すると便利です。
    このコマンドでカレントディレクトリの.vimprojectsを読み込みます。
>
    	nmap <silent> <Leader>P :Project<CR>
<

9.  .エントリが消えないようにしてプロジェクト内に置きたい場合、
    コメントとして
>
	. # pragma keep
<
    のように記述します。

以上


project.txtの原文

*project.txt*	Plugin for managing multiple projects with multiple sources
		For Vim version 6.x and Vim version 7.x.
		Last Change: Fri 13 Oct 2006 10:20:13 AM EDT
	

				By Aric Blumer
		      aricvim email-at-sign charter.net

						    *project* *project-plugin*
	Contents:

		Commands...................|project-invoking|
		Inheritance.............|project-inheritance|
		Mappings...................|project-mappings|
		Adding Mappings.....|project-adding-mappings|
		Settings...................|project-settings|
		Example File................|project-example|
		Tips...........................|project-tips|


You can use this plugin's basic functionality to set up a list of
frequently-accessed files for easy navigation. The list of files will be
displayed in a window on the left side of the Vim window, and you can press
<Return> or double-click on filenames in the list to open the files. I find
this easier to use than having to navigate a directory hierarchy with the
|file-explorer|.

You can also instruct the Plugin to change to a directory and to run Vim
scripts when you select a file. These scripts can, for example, modify the
environment to include compilers in $PATH. This makes it very easy to use
quickfix with multiple projects that use different environments.

Other features include:
	o Loading/Unloading all the files in a Project (\l, \L, \w, and \W)
	o Grepping all the files in a Project (\g and \G)
	o Running a user-specified script on a file (can be used to launch an
	  external program on the file) (\1 through \9)
	o Running a user-specified script on all the files in a Project
	  (\f1-\f9 and \F1-\F9)
	o High degree of user-configurability
	o Also works with |netrw| using the XXXX://... notation where XXXX is
	  ftp, rcp, scp, or http.

All of this is specified within a simple text file and a few global variables
in your vimrc file.

You must set 'nocompatible' in your |vimrc| file to use this plugin. You can
stop the plugin from being loaded by setting the "loaded_project" variable: >
	:let loaded_project = 1


==============================================================================
COMMANDS						    *project-invoking*

You can use the plugin by placing it in your plugin directory (e.g.,
~/.vim/plugin). See |add-global-plugin|. When you start vim the next time, you
then enter the command >
    :Project
or >
    :Project {file}

If you do not specify the filename, $HOME/.vimprojects is used.

To have Vim come up with the Project Window enabled automatically (say, from a
GUI launcher), run Vim like this:  [g]vim +Project

Note that you can invoke :Project on only one file at a time.  If you wish to
change the Project File, do a :bwipe in the Project Buffer, then re-invoke the
Plugin as described above.

Several Projects can be kept and displayed in the same file, each in a fold
delimited by { and } (see |fold.txt|).  There can be any number of nested
folds to provide you with a Project hierarchy.  Any line without a { or a } in
the file is considered to be a filename.  Blank lines are ignored, and any
text after a # is ignored.

Because the plugin uses standard Vim folds, you can use any of the
|fold-commands|. You can double-click on the first line of a fold to open and
close it. You can select a file to open by putting the cursor on its name and
pressing <Return> or by double-clicking on it.  The plugin will create a new
window to the right or use the |CTRL-W_p| equivalent if it exists.

							      *project-syntax*
Each Project Entry has this form:

project_entry ::=
    <Description>={projpath} [{options}] {
	[ filename ]
	[ project_entry ]
    }

{options} is one or more of the following (on the same line):
    CD={path}
    in={filename}
    out={filename}
    filter="{pat}"
    flags={flag}

Note that a project_entry can reside within a project_entry. This allows you
to set up a hierarchy within your Project.

The <Description> will be displayed in the foldtext and cannot contain "=".
There can be no space character directly on either side of the =.

The {projpath} is the path in which the files listed in the Project's fold
will be found, and it may contain environment variables.  If the path is a
relative path, then the plugin constructs the whole path from the Project's
parent, grandparent, etc., all the way up the hierarchy. An outermost
project_entry must have an absolute path.  See the |project-inheritance|
example below.  {projpath} may contain spaces, but they must be escaped like
normal Vim escapes. Here are two examples of the same directory:
>
	Example=/my/directory/with\ spaces {
	}
	Example="/my/directory/with spaces" {
	}

I recommend this for Windows〓: >

	Example="c:\My Documents" {
	}

But Vim is smart enough to do this, too: >

	Example=c:\My\ Documents {
	}

CD= provides the directory that Vim will change to when you select a file in
that fold (using |:cd|). This allows you, for example, to enter |:make| to use
the local Makefile.  A CD=. means that Vim will make {projpath} or its
inherited equivalent the current working directory.  When CD is omitted, the
directory is not changed.  There can be no space on either side of the =.  The
value of CD can also be a relative path from a parent's CD.  See the
|project-inheritance| example below.  This directive is ignored for |netrw|
projects. Spaces are allowed in the path as for {projpath}.

in= and out= provide the means to run arbitrary Vim scripts whenever you enter
or leave a file's buffer (see the |BufEnter| and |BufLeave| autocommand
events).  The idea is to have a Vim script that sets up or tears down the
environment for the Project like this:

in.vim: >
	let $PROJECT_HOME='~/my_project'
	" Put the compiler in $PATH
	if $PATH !~ '/path/to/my/compiler'
		let $PATH=$PATH.':/path/to/my/compiler'
	endif

out.vim: >
	" Remove compiler from $PATH
	if $PATH =~ '/path/to/my/compiler'
		let $PATH=substitute($PATH, ':/path/to/my/compiler', '', 'g')
	endif

Then you can use :make with the proper environment depending on what file you
are currently editing.  If the path to the script is relative, then it is
relative from {projpath}.  These directives are inherited by Subprojects
unless the Subproject specifies its own. For use with |netrw| projects, the
paths specified for in= and out= must be absolute and local.

filter= specifies a |glob()| file pattern. It is used to regenerate the list
of files in a Project fold when using the \r (<LocalLeader>r) map in the
Project Window.  The filter value must be in quotes because it can contain
multiple file patterns.  If filter is omitted, then the * pattern is used.
There can be no space on either side of the =.  A Subproject will inherit the
filter of its parent unless it specifies its own filter.

flags= provides the means to enable/disable features for a particular fold.
The general mnemonic scheme is for lower case to turn something off and upper
case to turn something on.  {flag} can contain any of the following
characters:

      flag      Description ~

	l	Turn off recursion for this fold for \L.  Subfolds are also
	        blocked from the recursion.

	r	Turn off refresh. When present, do not refresh this fold when
		\r or \R is used.  This does not affect subfold recursion.

	S	Turn on sorting for refresh and create.

	s	Turn off sorting for refresh and create.

	T	Turn on top gravity.  Forces folds to the top of the current
		fold when refreshing. It has the same affect as the 'T' flag
		in g:proj_flags, but controls the feature on a per-fold basis.

	t	Turn off top gravity.  Forces folds to the bottom of the
	        current fold when refreshing.

	w	Turn off recursion for this fold for \W.  Subfolds are also
	        blocked from the recursion.


Flags are not inherited by Subprojects.

Any text outside a fold is ignored.


==============================================================================
INHERITANCE						 *project-inheritance*

It's best to show inheritance by comparing these two Project Files:
>
	Parent=~/my_project CD=. filter="Make* *.mk" flags=r {
	 Child1=c_code {
	 }
	 Child2=include CD=. filter="*.h" {
	 }
	}

Child1's path is "~/my_project/c_code" because ~/my_project is inherited.  It
also inherits the CD from Parent.  Since Parent has CD=., the Parent's cwd is
"~/my_project".  Child1 therefore inherits a CD of "~/my_project".  Finally,
Child1 inherits the filter from Parent. The flags are not inherited.

Child2 only inherits the "~/my_project" from Parent.

Thus, the example above is exactly equivalent to this:
>
	Parent=~/my_project CD=. filter="Make* *.mk" flags=r {
	 Child1=~/my_project/c_code CD=~/my_project filter="Make* *.mk" {
	 }
	 Child2=~/my_project/include CD=~/my_project/include filter="*.h" {
	 }
	}

(For a real Project, Child1 would not want to inherit its parent's filter, but
this example shows the concept.)  You can always enter \i to display what the
cursor's project inherits.


==============================================================================
MAPPINGS						    *project-mappings*

Map	Action ~

\r	Refreshes the Project fold that the cursor is in by placing in the
	fold all the files that match the filter. The Project is refreshed
	using an indent of one space for every foldlevel in the hierarchy.

	You may place a "# pragma keep" (without the quotes) at the end of a
	line, and the file entry on that line will not be removed when you
	refresh.  This is useful, for example, when you have . as an entry so
	you can easily browse the directory.
	
	Note that this mapping is actually <LocalLeader>r, and the default of
	|<LocalLeader>| is \.

	This does not work for Projects using |netrw|.

\R	Executes \r recursively in the current fold and all folds below.
	This does not work for Projects using |netrw|.

\c	Creates a Project fold entry.  It asks for the description, the path
	to the files, the CD parameter, and the filename |glob()| pattern.
	From this information, it will create the Project Entry below the
	cursor.

	This does not work for Projects using |netrw|.

\C	Creates a Project fold entry like \c, but recursively includes all the
	subdirectories.

<Return>
	Select a file to open in the |CTRL-W_p| window or in a new window.  If
	the cursor is on a fold, open or close it.

<S-Return>
\s
	Same as <Return> but horizontally split the target window.
	<LocalLeader>s is provided for those terminals that don't recognize
	<S-Return>.

\S
	Load all files in a project by doing horizontal splits.

<C-Return>
\o
	Same as <Return> but ensure that the opened file is the only other
	window. <LocalLeader>o is provided for those terminals that don't
	recognize <C-Return>.

<M-Return>
\v
	Same as <Return> but only display the file--the cursor stays in the
	Project Window.

<2-LeftMouse>
	(Double-click) If on a closed fold, open it. If on an open fold
	boundary, close it. If on a filename, open the file in the |CTRL-W_p|
	window or in a new window.

<S-2-LeftMouse>
	Same as <S-Return>.

<C-2-LeftMouse>
	Same as <C-Return>.

<RightMouse>
	Increase the width of the Project Window by g:proj_window_increment or
	toggle between a width of
		g:proj_window_width + g:proj_window_increment
	and
		g:proj_window_width.

	Whether you toggle or monotonically increase the width is determined
	by the 't' flag of the g:proj_flags variable (see |project-flags|).

	Note that a Right Mouse click will not automatically place the cursor
	in the Project Window if it is in a different window.  The window will
	go back to the g:proj_window_width width when you leave the window.

<space> Same as <RightMouse>

<CTRL-Up>
\<Up>
	Move the text or fold under the cursor up one row. This may not work
	in a terminal because the terminal is unaware of this key combination.
	<LocalLeader><Up> is provided for those terminals that don't recognize
	<C-Up>.


<CTRL-Down>
\<Down>
	Move the text or fold under the cursor down one row. This may not work
	in a terminal because the terminal is unaware of this key combination.
	<LocalLeader><Down> is provided for those terminals that don't
	recognize <C-Down>.

\i	Show in the status line the completely resolved and inherited
	parameters for the fold the cursor is in.  This is intended for
	debugging your relative path and inherited parameters for manually
	entered Projects.

\I	Show in the status line the completely resolved filename.  Uses the
        Project_GetFname(line('.')) function.

\1 - \9
	Run the command specified in g:proj_run{x} where {x} is the number
	of the key.  See the documentation of g:proj_run1 below.

\f1-\f9
	Run the command specified in g:proj_run_fold{x} where {x} is the
	number of the key.  The command is run on the files at the current
	Project level. See the |project-settings| below.

\F1-\F9
	Run the command specified in g:proj_run_fold{x} where {x} is the
	number of the key.  The command is run on the files at the current
	Project level and all Subprojects. See the |project-settings| below.

\0	Display the commands that are defined for \1 through \9.

\f0	Display the commands that are defined for \f1 through \f9 and \F1
	through \F0.  Same as \F0.

\l	Load all the files in the current Project level into Vim.  While files
	are being loaded, you may press any key to stop.

\L	Load all the files in the current Project and all Subprojects into
	Vim.  Use this mapping with caution--I wouldn't suggest using \L to
	load a Project with thousands of files. (BTW, my Project file has more
	than 5,300 files in it!)  While files are being loaded, you may press
	any key to stop.

\w	Wipe all the files in the current Project level from Vim. (If files
	are modified, they will be saved first.)  While files are being wiped,
	you may press any key to stop.

\W	Wipe all the files in the current Project and all Subprojects from
	Vim. (If files are modified, they will be saved first.)  While files
	are being wiped, you may press any key to stop.

\g	Grep all the files in the current Project level.

\G	Grep all the files in the current Project level and all Subprojects.

\e	Set up the Environment for the Project File as though you had selected
	it with <Return>.  This allows you to do a \e and a :make without
	having to open any files in the project.

\E	Explore (using |file-explorer|) the directory of the project the
	cursor is in.  Does not work with netrw.

<F12>	When the 'g' flag is present in g:proj_flags (see |project-flags|)
	this key toggles the Project Window open and closed. You may remap
	this toggle function by putting the following in your vimrc and
	replacing <Leader>P with whatever key combination you wish:

		nmap <silent> <Leader>P <Plug>ToggleProject

Note that the Project Plugin remaps :help because the Help Window and the
Project Window get into a fight over placement. The mapping avoids the
problem.

==============================================================================
ADDING MAPPINGS 				     *project-adding-mappings*

You can add your own mappings or change the mappings of the plugin by placing
them in the file $HOME/.vimproject_mappings.  This file, if it exists, will be
sourced when the plugin in loaded.  Here is an example that will count the
number of entries in a project when you press \K (Kount, C is taken :-): >

    function! s:Wc()
        let b:loadcount=0
        function! SpawnExec(infoline, fname, lineno, data)
	    let b:loadcount = b:loadcount + 1
	    if getchar(0) != 0 | let b:stop_everything=1 | endif
        endfunction
        call Project_ForEach(1, line('.'), "*SpawnExec", 0, '')
        delfunction SpawnExec
        echon b:loadcount." Files\r"
        unlet b:loadcount
        if exists("b:stop_everything")
	    unlet b:stop_everything
	    echon "Aborted.\r"
	endif
    endfunction

    nnoremap <buffer> <silent> <LocalLeader>K :call <SID>Wc()<CR>

Here's another example of how I integrated the use of perforce with the plugin
in my $HOME/.vimproject_mappings:
>
	function! s:DoP4(cmd)
	   let name=Project_GetFname(line('.'))
	   let dir=substitute(name, '\(.*\)/.*', '\1', 'g')
	   exec 'cd '.dir
	   exec "!".a:cmd.' '.Project_GetFname(line('.'))
	   cd -
	endfunction

	nmap <buffer> <silent> \pa :call <SID>DoP4("p4add")<CR>
	nmap <buffer> <silent> \pe :call <SID>DoP4("p4edit")<CR>
<
(Note that I CD to the directory the file is in so I can pick of the $P4CONFIG
file. See the perforce documentation.)

This creates the mappings \pe to check out the file for edit and \pa to add
the file to the depot.

Here is another example where I remap the <Return> mapping to use an external
program to launch a special kind of file (in this case, it launches ee to view
a jpg file).  It is a bit contrived, but it works.
>
	let s:sid = substitute(maparg('<Return>', 'n'), '.*\(<SNR>.\{-}\)_.*', '\1', '')
	function! s:LaunchOrWhat()
	    let fname=Project_GetFname(line('.'))
	    if fname =~ '\.jpg$'
		exec 'silent! !ee "'.fname.'"&'
	    else
		call {s:sid}_DoFoldOrOpenEntry('', 'e')
	    endif
	endfunction
	nnoremap <buffer> <silent> <Return>   \|:call <SID>LaunchOrWhat()<CR>
<
If the file ends in .jpg, the external program is launched, otherwise the
original mapping of <Return> is run.

==============================================================================
SETTINGS						    *project-settings*

You can set these variables in your vimrc file before the plugin is loaded to
change its default behavior

g:proj_window_width
	The width of the Project Window that the plugin attempts to maintain.
	Default: 24

	The Project Plugin is not always successful in keeping the window
	where I want it with the size specified here, but it does a decent
	job.

g:proj_window_increment
	The increment by which to increase the width of the Project Window
	when pressing <space> or clicking the <LeftMouse>. Default: 100
	(See |project-mappings|.)

							       *project-flags*
g:proj_flags
	Default: "imst"
	Various flags to control the behavior of the Project Plugin.  This
	variable can contain any of the following character flags.

       flag	Description ~

	b	When present, use the |browse()| when selecting directories
		for \c and \C.  This is off by default for Windows, because
		the windows browser does not allow you to select directories.

	c	When present, the Project Window will automatically close when
		you select a file.

	F	Float the Project Window.  That is, turn off automatic
		resizing and placement.  This allows placement between other
		windows that wish to share similar placement at the side of
		the screen.  It is also particularly helpful for external
		window managers.

	g	When present, the mapping for <F12> will be created to toggle
		the Project Window open and closed.

	i	When present, display the filename and the current working
		directory in the command line when a file is selected for
		opening.

	l	When present, the Project Plugin will use the |:lcd| command
		rather than |:cd| to change directories when you select a file
		to open.  This flag is really obsolete and not of much use
		because of L below.

	L	Similar to l, but install a BufEnter/Leave |:autocommand| to
		ensure that the current working directory is changed to the
		one specified in the fold CD specification whenever that
		buffer is active.  (|:lcd| only changes the CWD for a window,
		not a buffer.)

	m	Turn on mapping of the |CTRL-W_o| and |CTRL-W_CTRL_O| normal
	        mode commands to make the current buffer the only visible
		buffer, but keep the Project Window visible, too.

	n	When present, numbers will be turned on for the project
	        window.

	s	When present, the Project Plugin will use syntax highlighting
		in the Project Window.

	S	Turn on sorting for refresh and create.

	t	When present, toggle the size of the window rather than just
		increase the size when pressing <space> or right-clicking.
		See the entry for <RightMouse> in |project-mappings|.

	T	When present, put Subproject folds at the top of the fold when
		refreshing.

	v	When present, use :vimgrep rather than :grep when using \G.

g:proj_run1 ...  g:proj_run9
		Contains a Vim command to execute on the file.  See the
		mappings of \1 to \9 above.
		
		  %f is replaced with the full path and filename
		  %F is replaced with the full path and filename with spaces
		     quoted
		  %n is replaced with the filename alone
		  %N is replaced with the filename alone with spaces quoted
		  %h is replaced with the home directory
		  %H is replaced with the home directory with spaces quoted
		  %r is replaced with the directory relative to the CD path
		  %R is replaced with the directory relative to the CD path
		     with spaces quoted
		  %d is replaced with the CD directory.
		  %D is replaced with the CD directory.with spaces quoted
		  %% is replaced with a single % that is not used in
		     expansion.

		(Deprecated: %s is also replaced with the full path and
		filename for backward compatibility.)

		For example, gvim will be launched on the file under the
		cursor when you enter \3 if the following is in your vimrc
		file: >
		 let g:proj_run3='silent !gvim %f'
<		Here are a few other examples: >
		 let g:proj_run1='!p4 edit %f'
		 let g:proj_run2='!p4 add %f'
		 let g:proj_run4="echo 'Viewing %f'|sil !xterm -e less %f &"
<
		On Windows systems you will want to put the %f, %h, and %d in
		single quotes to avoid \ escaping.

g:proj_run_fold1 ...  g:proj_run_fold9
		Contains a Vim command to execute on the files in a fold.  See
		the mappings of \f1 to \f9  and \F1 to \F9 above.
		
		%f is the filename, %h is replaced with the project home
		directory, and %d is replaced with the CD directory.  Multiple
		filenames can be handled in two ways:

		The first (default) way is to have %f replaced with all the
		absolute filenames, and the command is run once.  The second
		is to have the command run for each of the non-absolute
		filenames (%f is replaced with one filename at a time).  To
		select the second behavior, put an '*' character at the
		beginning of the g:proj_run_fold{x} variable.  (The '*' is
		stripped before the command is run.)

		For example, note the difference between the following: >
		 let g:proj_run_fold3="*echo '%h/%f'"
		 let g:proj_run_fold4="echo '%f'"
<
		Note that on Windows systems, you will want the %f, %h, and %c
		within single quotes, or the \ in the paths will cause
		problems.  The alternative is to put them in |escape()|.


==============================================================================
PROJECT EXAMPLE FILE					     *project-example*

Here is an example ~/.vimprojects file: >

  1	My Project=~/c/project CD=. in=in.vim out=out.vim flags=r {
  2	 Makefile
  3      in.vim
  4      out.vim
  5	 GUI Files=. filter="gui*.c gui*.h" {
  6	  gui_window.c
  7	  gui_dialog.c
  8	  gui_list.c
  9	  gui.h	       # Header file
 10	 }
 11	 Database Files=. filter="data*.c data*.h" {
 12	  data_read.c
 13	  data_write.c
 14	  data.h
 15	 }
 16	 OS-Specific Files {
 17	  Win32=. filter="os_win32*.c os_win32*.h" {
 18	   os_win32_gui.c
 19	   os_win32_io.c
 20	  }
 21	  Unix=. filter="os_unix*.c os_unix*.h" {
 22	   os_unix_gui.c
 23	   os_unix_io.c
 24	  }
 25	 }
 26	}

(Don't type in the line numbers, of course.)


==============================================================================
TIPS ON USING PROJECT PLUGIN					*project-tips*

1.  You can create a Project Entry by entering this: >

	Label=~/wherever CD=. filter="*.c *.h" {
	}
<
    Then you can put the cursor in the fold and press \r. The script will fill
    in the files (C files in this case) from this directory for you.  This is
    equivalent to \c without any dialogs.

2.  You can edit the Project File at any time to add, remove, or reorder files
    in the Project list.

3.  If the Project Window ever gets closed, you can just enter >
	:Project
<   to bring it back again. (You don't need to give it the filename; the
    plugin remembers.)

    If you have the 'm' flag set in g:proj_flags, then you get the Project
    Window to show up again by pressing |CTRL-W_o|. This, of course, will
    close any other windows that may be open that the cursor is not in.

4.  Adding files to a Project is very easy.  To add, for example, the 'more.c'
    file to the Project, just insert the filename in the Project Entry then
    hit <Return> on it.

5.  When |quickfix| loads files, it is not equivalent to pressing <Return> on
    a filename, so the directory will not be changed and the scripts will not
    be run. (If I could make this otherwise, I would.)  The solution is to use
    the \L key to load all of the files in the Project before running
    quickfix.

6.  If the Project window gets a bit cluttered with folds partially
    open/closed, you can press |zM| to close everything and tidy it up.

7.  For advanced users, I am exporting the function Project_GetAllFnames()
    which returns all the filenames within a fold and optionally all its
    Subprojects.  Also, I export Project_ForEach() for running a function for
    each filename in the project. See the code for examples on how to use
    these. Finally, I export Project_GetFname(line_number) so that you can
    write your own mappings and get the filename for it.

8.  Some people have asked how to do a global mapping to take the cursor to
    the Project window. One of my goals for the plugin is for it to be as
    self-contained as possible, so I'm not going to add it by default. But you
    can put this in your vimrc:
>
    	nmap <silent> <Leader>P :Project<CR>

<
9.  You can put the . entry in a project, and it will launch the
    |file-explorer| plugin on the directory.  To avoid removal when you
    refresh, make the entry look like this:
>
 	. # pragma keep
<
==============================================================================
THANKS

	The following people have sent me patches to help with the Project
	Plugin development:

		Tomas Zellerin
		Lawrence Kesteloot
		Dave Eggum
		A Harrison
		Thomas Link
		Richard Bair
		Eric Arnold
		Peter Jones
		Eric Van Dewoestine


 vim:ts=8 sw=8 noexpandtab tw=78 ft=help:

MacでCUIのさくらのレンタルサーバー上にssh+screen+vimでマウスで編集、慣性スクロール可能な開発環境を作成する方法

最近電気代のことも考えて、CentOS 5.5で立てていた自宅サーバーを、さくらのレンタルサーバー(月々500円のスタンダードプラン FreeBSD 8.1)に移行しました。
その際にやった、sshを介して使うscreenとvim、あとvimプラグイン群による、マウス操作可能な開発環境作成についてまとめました。
自分自身、WindowsでもMacOSXでもずっとGVimを使っていたこともあり、どうもオペレーターやテキストオブジェクトを使ってマウスを一切に使わないでVimを利用するスタイルというものが苦手でした。できるけど、そんなに速く編集できない...。
せっかくマウスがあるのだし、マウスを使った範囲指定やMacのトラックパッドを使ったなめらかな慣性スクロールを利用して素早く開発したいですよね。こっちのほうが頭にやさしいです。


例をあげると

<a href="http://hoge"><a>

以上のテキストでカーソルが行頭にある際に、以上のhogeをfugaに編集する場合、

4wci"http://fuga

みたいなのを考えて打つより、hogeをドラッグ選択して

cfuga

の方が楽に編集できますよね。
というわけで、そのような操作が可能な環境の作り方を今から紹介していきます。



最終的にどのような開発環境になるかというと以下のような機能の

  • sshで繋ぐGUIのないサーバー(UNIX, Linux)上において以下のGUI独特の操作が可能
    • クリックによるカーソル移動
    • ドラッグによる範囲選択
    • ダブルクリックによるタグジャンプ
    • 慣性スクロールによるなめらかな文書スクロール
    • ウインドウ分割した際のサッシのドラッグによるウインドウ幅調整
  • screenを利用し、回線切断、シャットダウンの際にも編集状態のセッションを復元可能
  • EclipseのようなIDEと同様な高度な機能
    • プロジェクトツリーの表示と、タブルクリックによる階層探索(project.vim)
    • ファイル名も保管する強力なコンテンツアシスト(neocon+Unite.vim)
    • ソースコードのアウトライン表示(ctags+taglist.vim)
    • 選択領域のコメントアウトのトグル操作切り替え(nerdcommenter)
    • 左右ウインドウ分割表示のリポジトリ上のバージョンとの比較(vcscommand.vim)
    • zencodingや囲い編集のサポート(zencoding-vimとsurround.vim)

以上のような環境となります。


Eclipseを7年使ってきましたが、そのEclipseに劣らないほどの強力な開発環境だと思いませんか?
Eclipseは起動に1分かかることもありますが、このvimの開発環境、起動に1秒もかかりません。更にクライアントマシンがシャットダウンしても編集状態が残るという素晴らしい環境です。


というわけで、早速準備を始めます。

iTerm2のインストール

Development site for iTerm2
以上のDownloadsからiTerm2_v1_0_0.zipを選択してダウンロードし、アプリケーションフォルダに移動してインストール完了です。ちなみにTerminal.appがあるのに、なぜiTerm2を使うのかというと、

  • 表示色に256色が表示できる(Preference...>Profiles>Colors>Load Presets)
  • 以下のvimのマウス利用オプションが利用できる
" マウスモード有効
set mouse=a
" screen対応
set ttymouse=xterm2

以上2つの理由があるからです。
その他にもタブ管理やウインドウ管理機能が充実してたり、クリップボード履歴を利用する機能があります。興味がある人はいろいろいじってみると面白いです。ただし、Terminal.appに比べると描画が2倍ぐらい遅いです。大量にコンソールにプリントするアプリを動かす際には要注意ですが、普段は気にならないと思います。

sshでさくらのサーバーにログインの後、git+vim+ctags+screenのインストール

次に早速sshUNIXまたはLinuxサーバーにつないでみましょう。

$ ssh username@www0000.sakura.ne.jp

以上でログインし、入力を求められるのでパスワードを入力します。さくらのレンタルサーバーFreeBSD 8.1でデフォルトがcshでしたが、そのまま進めていきます。
ちなみに自分はzshに変更していますがその辺はお好みで。まずはホームディレクトリへのソフトウェアのインストールを進めていきます。ここが一番長いですが頑張りましょう。

$ mkdir -p ~/local/source
$ cd ~/local/source
$ wget http://git-core.googlecode.com/files/git-1.7.9.6.tar.gz
$ tar zxvf git-1.7.9.6.tar.gz
$ cd git-1.7.9.6
$ make prefix=$HOME/local
$ make prefix=$HOME/local install
$ cd ..
$ wget http://hp.vector.co.jp/authors/VA025040/ctags/downloads/ctags-5.8j2.tar.gz
$ tar zxvf ctags-5.8j2.tar.gz
$ cd ctags-5.8j2
$ ./configure --prefix=$HOME/local
$ make
$ make install
$ cd ..
$ wget ftp://ftp.vim.org/pub/vim/unix/vim-7.3.tar.bz2
$ tar -jxf vim-7.3.tar.bz2
$ cd vim73
$ ./configure --enable-multibyte --enable-xim --enable-fontset --with-features=big --prefix=$HOME/local
$ make
$ make install
$ cd ..
$ wget ftp://ftp.uni-erlangen.de/pub/utilities/screen/screen-4.0.3.tar.gz
$ tar xzf screen-4.0.3.tar.gz
$ cd screen-4.0.3
$ ~/local/bin/vim pty.c

38行目当たりのsolaris向けのコードをコメントアウト

/* for solaris 2.1, Unixware (SVR4.2) and possibly others */
#ifdef HAVE_SVR4_PTYS
# include <sys/stropts.h>
#endif

無事コメントアウトしたら、

$ ./configure --prefix=$HOME/local
$ make
$ make install
$ ~/local/bin/vim .cshrc

.cshrcを編集して、今回ホームディレクトリにインストールしたものにパスを通したり、環境変数を設定したりします。

alias vi    vim
setenv EDITOR  vim
setenv LANG ja_JP.UTF-8
set path = (/sbin /bin /usr/sbin /usr/bin /usr/local/sbin /usr/local/bin $HOME/bin $HOME/local/bin)

以上のそれぞれの行を.cshrcに追加、または変更して設定します。

$ source ~/.cshrc

最後にこの設定を読み込みます。
これでひと通りのインストールは完了です。これでgitとvimとctagsとscreenがホームディレクトリ以下にインストールされました。

.screenrcの設定とscreenの利用

次は、早速.screenrcの設定などをしていきます。スクリーンの設定、コマンド一覧は、screenコマンド一覧を参考に。

$ vim ~/.screenrc

これで編集を開始して以下を記入します。

escape ^Tt
startup_message off
zombie 

rdstatus alwayslastline "[%02c] %`%-w%{=b bw}%n %t%{-}%+w"
defencoding UTF-8
encoding UTF-8
termcapinfo * 'hs:ts=\E]2;:fs=\007:ds=\E]0;screen\007'
termcapinfo xterm 'is=\E[r\E[m\E[2J\E[H\E[?7h\E[?1;4;6l'
caption always "%{=r dd}%-Lw%40L>%?%F%{=b dR}%:[%? %n%f %t %?%F%{-}%:]%?%+Lw %?%F%-006=■■%:%=%?"
altscreen on
defscrollback 50000
autodetach on
#multiuser on
#acladd soichiro_yoshimura 

この設定は、サーバー時刻を表示するキャプションを設定の他、回線が切れた時にオートデタッチするようにしています。
キーインはCtrl+Tです。スクリーンの利用はコンソールにてコマンドscreen、デタッチはCtrl+T d、再度のアタッチはコマンドscreen -rとなります。これだけ覚えておけばとりあえず使えます。
あと、画面スクロールのためのコピーモードへの入り方は、Ctrl+T [です。残念ながらここではマウスホイール等は使えません、vimやlessと同様のキー操作です(ただ、iTerm2の設定を変えるとスクロールできるようになります、このエントリの最後を参照)。他にも常にログを取ったり、パネルを分割したり、タブを使ったりもできますが、これらは他のレイヤーでも利用できますので、この機能しか使いません。これでMacBookProを閉じてsshが切断されたり、さくらのレンタルサーバーからの強制切断があっても大丈夫です。
というわけで早速screenを利用してみます。

$ screen

これで、途中でサーバーとの接続が不安定になっても自動的にデタッチされるので。切断されたら、sshで繋ぎ直しコマンドscreen -lsでセッションがあることを確認して、コマンドscreen -rで再度アタッチして作業をしましょう。
なお、さくらのレンタルサーバーではsshの接続が一つしかできないこともある時には、sceenのタブ機能が役に立ちます。詳しくは、screenコマンド一覧 3.9.13対応をご覧ください。

.vimrcの設定とvimプラグインのインストール

さて、次は、.vimrcの設定をやっていきます。

$ vim ~/.vimrc

で、.vimrcを編集します。自分の設定は以下の通りですが、好きなようにカスタマイズしてください。

")VimをなるべくVi互換にする
set nocompatible

"""""""""" NeoBundle設定 """"""""""
" https://github.com/Shougo/neobundle.vim
" インストール
" $ mkdir -p ~/.vim/bundle
" $ git clone https://github.com/Shougo/neobundle.vim ~/.vim/bundle/neobundle.vim
filetype plugin indent off     " required!
if has('vim_starting')
	set runtimepath+=~/.vim/bundle/neobundle.vim/
	call neobundle#rc(expand('~/.vim/bundle/'))
endif

" gitを使ったプラグインマネージャ
NeoBundle 'Shougo/neobundle.vim'

"""""""" github
" 強力な入力補完(Uniteと連携)
NeoBundle 'Shougo/neocomplcache'
" Uniteコマンドによる読み出し等
NeoBundle 'Shougo/unite.vim'
" ,,でトグルでコメントアウト
NeoBundle 'scrooloose/nerdcommenter'
" zendogingプラグイン
NeoBundle 'mattn/zencoding-vim'

""""""" vim-scripts repos
" プロジェクトのツリー表示
NeoBundle 'project.tar.gz'
" 括弧囲みの編集操作
NeoBundle 'surround.vim'
" :Tlistでctagsの一覧表示
NeoBundle 'taglist.vim'
" SVNの差分表示用 http://blog.blueblack.net/item_144
NeoBundle 'vcscommand.vim'

filetype on
filetype indent on
filetype plugin on

"""""""""" 追加設定 """"""""""
"バックスペースキーの動作を決定する
"2:indent,eol,startと同じ
set backspace=2

"行数表示
set number

"新しい行を開始したときに、新しい行のインデントを現在行と同じ量にする
set autoindent

"検索で小文字なら大文字を無視、大文字なら無視しない設定
set smartcase

"(no)検索をファイルの末尾まで検索したら、ファイルの先頭へループする
set nowrapscan

"インクリメンタルサーチを行う
set incsearch

"highlight matches with last search pattern
set hlsearch

"閉じ括弧が入力されたとき、対応する括弧を表示する
set showmatch

"カーソルが何行目の何列目に置かれているかを表示する
set ruler

"新しい行を作ったときに高度な自動インデントを行う
set smartindent

"保存しないで他のファイルを表示することが出来るようにする
set hidden

"カレントバッファ内のファイルの文字エンコーディングを設定する
set fileencoding=utf-8

"Insertモードで<Tab> を挿入するのに、適切な数の空白を使う
"set expandtab

"ファイル内の <Tab> が対応する空白の数
set tabstop=4

"自動インデントの各段階に使われる空白の数
set shiftwidth=4

"行頭の余白内で Tab を打ち込むと、'shiftwidth' の数だけインデントする
set smarttab

"強調表示(色付け)のON/OFF設定
syntax on

" カラースキーマ設定 (~/.vim/colors/wombat.vimが必要)
colorscheme wombat

"ステータスラインを表示するウィンドウを設定する
"2:常にステータスラインを表示する
set laststatus=2

"ステータス行の表示内容を設定する
set statusline=%<%f\ %m%r%h%w%{'['.(&fenc!=''?&fenc:&enc).']['.&ff.']'}%=%l,%c%V%8P

"vimのバックアップファイルとスワップファイル
set nobackup
set noswapfile

"バッファをクリップボードにコピー(for OSX, UNIXのgvim用)
set clipboard=unnamed,autoselect

"自動改行オフ
set tw=0

" neocomplcache 起動時に有効化
let g:neocomplcache_enable_at_startup = 1 " 起動時に有効化

" ,, でコメントアウトをトグル
let NERDSpaceDelims = 1
nmap ,, <Plug>NERDCommenterToggle
vmap ,, <Plug>NERDCommenterToggle

"コメントアウトが連続して入力されるのを禁止
autocmd FileType * setlocal formatoptions-=ro

"全角スペースを で表示
highlight JpSpace cterm=underline ctermfg=Blue guifg=Blue
au BufRead,BufNew * match JpSpace / /

"タブを見えるように設定
"set list
"set listchars=tab:>-

" サーチハイライトををESC二回で消す
nnoremap <Esc><Esc> :nohlsearch<CR><Esc>

" マウスモード有効
set mouse=a
" screen対応
set ttymouse=xterm2

" 挿入モードとノーマルモードでステータスラインの色を変更する
au InsertEnter * hi StatusLine guifg=DarkBlue guibg=DarkYellow gui=none ctermfg=Blue ctermbg=Yellow cterm=none
au InsertLeave * hi StatusLine guifg=Black guibg=White gui=none ctermfg=Black ctermbg=White cterm=none

"ctagsの埋め込み 各環境であるものを全て記述(なくても問題ない)
set tags=~/.tags,~/.tags.study 

という感じにします。あと、カラースキームもiTermのデフォルトのカラープリセットで見やすいwombatに設定します。まだカラースキーマwombat.vimの実体がないので、以下の手順でダウンロードします。

$ mkdir -p ~/.vim/colors
$ cd ~/.vim/colors
$ wget http://www.vim.org/scripts/download_script.php?src_id=6657
$ cd ~

これでOKです。


あとは、必要プラグインのインストールをします。まず、プラグインマネージャのNeoBundleをまずはインストール。

$ mkdir -p ~/.vim/bundle
$ export GIT_SSL_NO_VERIFY=true
$ git clone https://github.com/Shougo/neobundle.vim ~/.vim/bundle/neobundle.vim

これでNeoBundleがインストールされます。

$ vim

以上でvimを立ち上げて

:NeoBundleInstall

を実行して、先程.vimrcに記述しておいた他の必要なプラグインをすべてインストールします。
これで環境構築は完了です。


project.vimの使い方は、
Project.vim - Vimでのプログラミングを猛烈に支援してくれるプラグイン
以上のサイトが、
ctagsとvimの連携に関しては
Vim でタグジャンプを使ってみる
以上のサイトなどが勉強になります。ぜひうまく利用してみて下さい。
なお、複数行して,,をコマンドするとコメントアウトのトグル操作。で検索のハイライトが消える設定がしてあります。


以上の環境設定でで、sshを介してマウスを使ったscreen+vim開発環境は完成です。じっくりご堪能下さい。
自分はこの設定に加えて言語ごと(JavaScript, Ruby, PHP, Scala)のプラグインなどを入れています。その設定は、GitHub・sifue/dotfilesにもアップしてあるので参考にしてみてください。

ぜひおすすめのGoogle日本語入力の設定

もし、Google日本語入力を使っても良いというのであれば、ぜひ利用したほうが良いです。
なぜかというと、環境設定 > キーの設定 > 編集 で、Escを押した際に、IMEを無効にできるからです。これをやっておくとiTerm2上でコマンドラインモードなのに、日本語を入力して、うう..。ということがなくなります。この設定だけは本当におすすめです。
以下のように全ての状態において、Escapeが入力された際に、「キャンセル後IMEを無効化」を設定しておきます。これで自動的IMEがオフになります。

MacOSX上でのsshの画面のコピー操作

なお、sshvim画面を範囲選択してMac上の選択したい時は、vim上で:set nonumberの後、altを押しながらドラッグで範囲選択すると綺麗にコピーできます。なお、alt + commandを押しながら選択すると矩形選択になります。これも便利。

iTerm2でscreen上でマウスでスクロールする設定

Preference... > Profiles > Terminal > Save lines to scrollback when an app status bar is present
以上の設定にチェックを入れておけばscreenを使った状態でもマウスでスクロールすることができます。


以上です。お疲れ様でした。