From f853d479d6e699499bee610ea8584b7e09f89cb3 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Sat, 20 Oct 2012 13:14:07 -0500 Subject: Add weechat, ack, git and nethack --- ackrc | 13 + gitconfig | 7 + nethackrc | 6 + vim/.netrwhist | 3 +- weechat/alias.conf | 37 + weechat/aspell.conf | 17 + weechat/buffers.conf | 56 ++ weechat/iset.conf | 27 + weechat/logger.conf | 24 + weechat/perl/autoload/beep.pl | 1 + weechat/perl/autoload/buffers.pl | 1 + weechat/perl/autoload/chanmon.pl | 1 + weechat/perl/autoload/iset.pl | 1 + weechat/perl/beep.pl | 257 +++++++ weechat/perl/buffers.pl | 998 ++++++++++++++++++++++++++ weechat/perl/chanmon.pl | 1116 +++++++++++++++++++++++++++++ weechat/perl/iset.pl | 1196 ++++++++++++++++++++++++++++++++ weechat/plugins.conf | 63 ++ weechat/python/autoload/screen_away.py | 1 + weechat/python/autoload/upside_down.py | 1 + weechat/python/autoload/weeget.py | 980 ++++++++++++++++++++++++++ weechat/python/screen_away.py | 151 ++++ weechat/python/upside_down.py | 130 ++++ weechat/relay.conf | 26 + weechat/rmodifier.conf | 11 + weechat/weechat.conf | 569 +++++++++++++++ weechat/weechat.log | 974 ++++++++++++++++++++++++++ weechat/weeget/plugins.xml.gz | Bin 0 -> 32683 bytes weechat/wg.conf | 16 + weechat/xfer.conf | 36 + 30 files changed, 6718 insertions(+), 1 deletion(-) create mode 100644 ackrc create mode 100644 gitconfig create mode 100644 nethackrc create mode 100644 weechat/alias.conf create mode 100644 weechat/aspell.conf create mode 100644 weechat/buffers.conf create mode 100644 weechat/iset.conf create mode 100644 weechat/logger.conf create mode 120000 weechat/perl/autoload/beep.pl create mode 120000 weechat/perl/autoload/buffers.pl create mode 120000 weechat/perl/autoload/chanmon.pl create mode 120000 weechat/perl/autoload/iset.pl create mode 100644 weechat/perl/beep.pl create mode 100644 weechat/perl/buffers.pl create mode 100644 weechat/perl/chanmon.pl create mode 100644 weechat/perl/iset.pl create mode 100644 weechat/plugins.conf create mode 120000 weechat/python/autoload/screen_away.py create mode 120000 weechat/python/autoload/upside_down.py create mode 100644 weechat/python/autoload/weeget.py create mode 100644 weechat/python/screen_away.py create mode 100644 weechat/python/upside_down.py create mode 100644 weechat/relay.conf create mode 100644 weechat/rmodifier.conf create mode 100644 weechat/weechat.conf create mode 100644 weechat/weechat.log create mode 100644 weechat/weeget/plugins.xml.gz create mode 100644 weechat/wg.conf create mode 100644 weechat/xfer.conf diff --git a/ackrc b/ackrc new file mode 100644 index 0000000..40587f7 --- /dev/null +++ b/ackrc @@ -0,0 +1,13 @@ +--type-add=html=.haml +--type-add=css=.sass,.scss,.less +--type-add=js=.rjs,.coffee +--type-add=ruby=.erb +--ignore-dir=vendor +--ignore-dir=log +--ignore-dir=tmp +--ignore-dir=doc +--ignore-dir=public/system +--sort-files +--color +--follow +--group diff --git a/gitconfig b/gitconfig new file mode 100644 index 0000000..3be84db --- /dev/null +++ b/gitconfig @@ -0,0 +1,7 @@ +[user] + name = Ben Beltran + email = ben@nsovocal.com +[core] + editor = vim +[color] + diff = auto diff --git a/nethackrc b/nethackrc new file mode 100644 index 0000000..2d8fc44 --- /dev/null +++ b/nethackrc @@ -0,0 +1,6 @@ +OPTIONS=color +OPTIONS=catname:Pure +OPTIONS=dogname:Juan +OPTIONS=horsename:Juan +OPTIONS=!DECgraphics +OPTIONS=IBMgraphics diff --git a/vim/.netrwhist b/vim/.netrwhist index ac734e4..6e853d2 100644 --- a/vim/.netrwhist +++ b/vim/.netrwhist @@ -1,4 +1,5 @@ let g:netrw_dirhistmax =10 -let g:netrw_dirhist_cnt =2 +let g:netrw_dirhist_cnt =3 let g:netrw_dirhist_1='/Users/benbeltran/.newsbeuter' let g:netrw_dirhist_2='/Users/benbeltran/.vim' +let g:netrw_dirhist_3='/Users/benbeltran/.dotfiles/tmux-powerline' diff --git a/weechat/alias.conf b/weechat/alias.conf new file mode 100644 index 0000000..81df71a --- /dev/null +++ b/weechat/alias.conf @@ -0,0 +1,37 @@ +# +# alias.conf -- weechat v0.3.8 +# + +[cmd] +AAWAY = "allserv /away" +AME = "allchan /me" +AMSG = "allchan /msg *" +ANICK = "allserv /nick" +BYE = "quit" +C = "buffer clear" +CHAT = "dcc chat" +CL = "buffer clear" +CLOSE = "buffer close" +EXIT = "quit" +IG = "ignore" +J = "join" +K = "kick" +KB = "kickban" +LEAVE = "part" +M = "msg" +MUB = "unban *" +N = "names" +Q = "query" +REDRAW = "window refresh" +SAY = "msg *" +SIGNOFF = "quit" +T = "topic" +UB = "unban" +V = "command core version" +W = "who" +WC = "window merge" +WI = "whois" +WII = "whois $1 $1" +WW = "whowas" + +[completion] diff --git a/weechat/aspell.conf b/weechat/aspell.conf new file mode 100644 index 0000000..e122f1c --- /dev/null +++ b/weechat/aspell.conf @@ -0,0 +1,17 @@ +# +# aspell.conf -- weechat v0.3.8 +# + +[look] +color = lightred + +[check] +commands = "ame,amsg,away,command,cycle,kick,kickban,me,msg,notice,part,query,quit,topic" +default_dict = "" +during_search = off +real_time = off +word_min_length = 2 + +[dict] + +[option] diff --git a/weechat/buffers.conf b/weechat/buffers.conf new file mode 100644 index 0000000..8cb4586 --- /dev/null +++ b/weechat/buffers.conf @@ -0,0 +1,56 @@ +# +# buffers.conf -- weechat v0.3.8 +# + +[color] +current_bg = red +current_fg = lightcyan +default_bg = default +default_fg = default +hotlist_highlight_bg = default +hotlist_highlight_fg = magenta +hotlist_low_bg = default +hotlist_low_fg = white +hotlist_message_bg = default +hotlist_message_fg = yellow +hotlist_private_bg = default +hotlist_private_fg = lightgreen +none_channel_bg = default +none_channel_fg = default +number = lightgreen +number_char = lightgreen +queries_default_bg = default +queries_default_fg = default +queries_highlight_bg = default +queries_highlight_fg = default +queries_message_bg = default +queries_message_fg = default +whitelist_default_bg = default +whitelist_default_fg = default +whitelist_highlight_bg = default +whitelist_highlight_fg = default +whitelist_low_bg = default +whitelist_low_fg = default +whitelist_message_bg = default +whitelist_message_fg = default +whitelist_private_bg = default +whitelist_private_fg = default + +[look] +core_to_front = off +detach = 0 +hide_merged_buffers = none +immune_detach_buffers = "" +indenting = off +indenting_number = on +jump_prev_next_visited_buffer = off +name_crop_suffix = "+" +name_size_max = 0 +number_char = "." +prefix = off +prefix_empty = on +short_names = on +show_lag = off +show_number = on +sort = number +whitelist_buffers = "" diff --git a/weechat/iset.conf b/weechat/iset.conf new file mode 100644 index 0000000..33fb1f1 --- /dev/null +++ b/weechat/iset.conf @@ -0,0 +1,27 @@ +# +# iset.conf -- weechat v0.3.8 +# + +[color] +bg_selected = red +help_default_value = green +help_option_name = white +help_text = default +option = default +option_selected = white +type = brown +type_selected = yellow +value = cyan +value_selected = lightcyan +value_undef = green +value_undef_selected = lightgreen + +[help] +show_help_bar = on +show_help_extra_info = on +show_plugin_description = on + +[look] +scroll_horiz = 10 +show_current_line = on +value_search_char = "=" diff --git a/weechat/logger.conf b/weechat/logger.conf new file mode 100644 index 0000000..dfc8c91 --- /dev/null +++ b/weechat/logger.conf @@ -0,0 +1,24 @@ +# +# logger.conf -- weechat v0.3.8 +# + +[look] +backlog = 20 + +[color] +backlog_end = darkgray +backlog_line = darkgray + +[file] +auto_log = on +flush_delay = 120 +info_lines = off +mask = "$plugin.$name.weechatlog" +name_lower_case = on +path = "%h/logs/" +replacement_char = "_" +time_format = "%Y-%m-%d %H:%M:%S" + +[level] + +[mask] diff --git a/weechat/perl/autoload/beep.pl b/weechat/perl/autoload/beep.pl new file mode 120000 index 0000000..0cc452e --- /dev/null +++ b/weechat/perl/autoload/beep.pl @@ -0,0 +1 @@ +../beep.pl \ No newline at end of file diff --git a/weechat/perl/autoload/buffers.pl b/weechat/perl/autoload/buffers.pl new file mode 120000 index 0000000..445dc3c --- /dev/null +++ b/weechat/perl/autoload/buffers.pl @@ -0,0 +1 @@ +../buffers.pl \ No newline at end of file diff --git a/weechat/perl/autoload/chanmon.pl b/weechat/perl/autoload/chanmon.pl new file mode 120000 index 0000000..0a72383 --- /dev/null +++ b/weechat/perl/autoload/chanmon.pl @@ -0,0 +1 @@ +../chanmon.pl \ No newline at end of file diff --git a/weechat/perl/autoload/iset.pl b/weechat/perl/autoload/iset.pl new file mode 120000 index 0000000..2746e0d --- /dev/null +++ b/weechat/perl/autoload/iset.pl @@ -0,0 +1 @@ +../iset.pl \ No newline at end of file diff --git a/weechat/perl/beep.pl b/weechat/perl/beep.pl new file mode 100644 index 0000000..69096c2 --- /dev/null +++ b/weechat/perl/beep.pl @@ -0,0 +1,257 @@ +# +# Copyright (C) 2006-2012 Sebastien Helleu +# Copyright (C) 2011 Nils Görs +# Copyright (C) 2011 ArZa +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# +# Beep (terminal bell) and/or run command on highlight/private message or new DCC. +# +# History: +# 2012-06-05, ldvx: +# version 1.1: Added wildcard support for whitelist_nicks. +# 2012-05-09, ldvx : +# version 1.0: Added beep_pv_blacklist, beep_highlight_blacklist, blacklist_nicks, +# and wildcard support for blacklist_nicks. +# 2012-05-02, ldvx : +# version 0.9: fix regex for nick in tags, add options "whitelist_channels" +# and "bell_always" +# 2012-04-19, ldvx : +# version 0.8: add whitelist, trigger, use hook_process for commands, +# rename option "beep_command" to "beep_command_pv", add help for options +# 2011-04-16, ArZa : +# version 0.7: fix default beep command +# 2011-03-11, nils_2 : +# version 0.6: add additional command options for dcc and highlight +# 2011-03-09, nils_2 : +# version 0.5: add option for beep command and dcc +# 2009-05-02, Sebastien Helleu : +# version 0.4: sync with last API changes +# 2008-11-05, Sebastien Helleu : +# version 0.3: conversion to WeeChat 0.3.0+ +# 2007-08-10, Sebastien Helleu : +# version 0.2: upgraded licence to GPL 3 +# 2006-09-02, Sebastien Helleu : +# version 0.1: initial release + +use strict; +my $SCRIPT_NAME = "beep"; +my $VERSION = "1.1"; + +# default values in setup file (~/.weechat/plugins.conf) +my %options_default = ('beep_pv' => ['on', 'beep on private message'], + 'beep_pv_whitelist' => ['off', 'turn whitelist for private messages on or off'], + 'beep_pv_blacklist' => ['off', 'turn blacklist for private messages on or off'], + 'beep_highlight' => ['on', 'beep on highlight'], + 'beep_highlight_whitelist' => ['off', 'turn whitelist for highlights on or off'], + 'beep_highlight_blacklist' => ['off', 'turn blacklist for highlights on or off'], + 'beep_dcc' => ['on', 'beep on dcc'], + 'beep_trigger_pv' => ['', 'word that will trigger execution of beep_command_pv (it empty, anything will trigger)'], + 'beep_trigger_highlight' => ['', 'word that will trigger execution of beep_command_highlight (if empty, anything will trigger)'], + 'beep_command_pv' => ['$bell', 'command for beep on private message, special value "$bell" is allowed, as well as "$bell;command"'], + 'beep_command_highlight' => ['$bell', 'command for beep on highlight, special value "$bell" is allowed, as well as "$bell;command"'], + 'beep_command_dcc' => ['$bell', 'command for beep on dcc, special value "$bell" is allowed, as well as "$bell;command"'], + 'beep_command_timeout' => ['30000', 'timeout for command run (in milliseconds, 0 = never kill (not recommended))'], + 'whitelist_nicks' => ['', 'comma-separated list of "server.nick": if not empty, only these nicks will trigger execution of commands (example: "freenode.nick1,freenode.nick2")'], + 'blacklist_nicks' => ['', 'comma-separated list of "server.nick": if not empty, these nicks will not be able to trigger execution of commands. Cannot be used in conjuction with whitelist (example: "freenode.nick1,freenode.nick2")'], + 'whitelist_channels' => ['', 'comma-separated list of "server.#channel": if not empty, only these channels will trigger execution of commands (example: "freenode.#weechat,freenode.#channel2")'], + 'bell_always' => ['', 'use $bell on private messages and/or highlights regardless of trigger and whitelist settings (example: "pv,highlight")'], +); +my %options = (); + +weechat::register($SCRIPT_NAME, "FlashCode ", $VERSION, + "GPL3", "Beep (terminal bell) and/or run command on highlight/private message or new DCC", "", ""); +init_config(); + +weechat::hook_config("plugins.var.perl.$SCRIPT_NAME.*", "toggle_config_by_set", ""); +weechat::hook_print("", "", "", 1, "pv_and_highlight", ""); +weechat::hook_signal("irc_dcc", "dcc", ""); + +sub pv_and_highlight +{ + my ($data, $buffer, $date, $tags, $displayed, $highlight, $prefix, $message) = @_; + + # return if message is filtered + return weechat::WEECHAT_RC_OK if ($displayed != 1); + + # return if nick in message is own nick + my $nick = ""; + $nick = $2 if ($tags =~ m/(^|,)nick_([^,]*)(,|$)/); + return weechat::WEECHAT_RC_OK if (weechat::buffer_get_string($buffer, "localvar_nick") eq $nick); + + # highlight + if ($highlight) + { + # Always print visual bel, regardless of whitelist and trigger settings + # beep_command_highlight does not need to contain $bell + if ($options{bell_always} =~ m/(^|,)highlight(,|$)/) + { + print STDERR "\a"; + } + # Channels whitelist for highlights + if ($options{beep_highlight} eq "on") + { + if ($options{whitelist_channels} ne "") + { + my $serverandchannel = weechat::buffer_get_string($buffer, "localvar_server"). "." . + weechat::buffer_get_string($buffer, "localvar_channel"); + if ($options{beep_trigger_highlight} eq "" or $message =~ m/\b$options{beep_trigger_highlight}\b/) + { + if ($options{whitelist_channels} =~ /(^|,)$serverandchannel(,|$)/) + { + beep_exec_command($options{beep_command_highlight}); + } + # What if we are highlighted and we're in a PM? For now, do nothing. + } + } + else + { + # Execute $bell and/or command with trigger and whitelist/blacklist settings + beep_trigger_whitelist_blacklist($buffer, $message, $nick, $options{beep_trigger_highlight}, + $options{beep_highlight_whitelist}, $options{beep_highlight_blacklist}, + $options{beep_command_highlight}); + } + } + } + # private message + elsif (weechat::buffer_get_string($buffer, "localvar_type") eq "private" and $tags =~ m/(^|,)notify_private(,|$)/) + { + # Always print visual bel, regardless of whitelist and trigger settings + # beep_command_pv does not need to contain $bell + if ($options{bell_always} =~ m/(^|,)pv(,|$)/) + { + print STDERR "\a"; + } + # Execute $bell and/or command with trigger and whitelist/blacklist settings + if ($options{beep_pv} eq "on") + { + beep_trigger_whitelist_blacklist($buffer, $message, $nick, $options{beep_trigger_pv}, + $options{beep_pv_whitelist}, $options{beep_pv_blacklist}, + $options{beep_command_pv}); + } + } + return weechat::WEECHAT_RC_OK; +} + +sub dcc +{ + beep_exec_command($options{beep_command_dcc}) if ($options{beep_dcc} eq "on"); + return weechat::WEECHAT_RC_OK; +} + +sub beep_trigger_whitelist_blacklist +{ + my ($buffer, $message, $nick, $trigger, $whitelist, $blacklist, $command) = @_; + + if ($trigger eq "" or $message =~ m/\b$trigger\b/) + { + my $serverandnick = weechat::buffer_get_string($buffer, "localvar_server").".".$nick; + if ($whitelist eq "on" and $options{whitelist_nicks} ne "") + { + # What to do if there's a wildcard in the whitelit + if ($options{whitelist_nicks} =~ m/\*/ and + match_in_wild_card($serverandnick, $options{whitelist_nicks})) + { + beep_exec_command($command); + } + # What to do if there's no wildcard in the whitelist + elsif ($options{whitelist_nicks} =~ /(^|,)$serverandnick(,|$)/) + { + beep_exec_command($command); + } + } + elsif ($blacklist eq "on" and $options{blacklist_nicks} ne "") + { + # What to do if there's a wildcard in the blacklist + if ($options{blacklist_nicks} =~ m/\*/ and + !match_in_wild_card($serverandnick, $options{blacklist_nicks})) + { + beep_exec_command($command); + } + # What to do if there's no wildcard in the blacklist + elsif ($options{blacklist_nicks} !~ /(^|,)$serverandnick(,|$)/) + { + beep_exec_command($command); + } + } + # What to do if we are not using whitelist of blacklist feature + elsif ($whitelist eq "off" and $blacklist eq "off") + { + beep_exec_command($command); + } + } +} + +sub beep_exec_command +{ + my $command = $_[0]; + if ($command =~ /^\$bell/) + { + print STDERR "\a"; + ($command) = $command =~ /^\$bell;(.+)$/; + } + weechat::hook_process($command, $options{beep_command_timeout}, "my_process", "") if ($command); +} + +sub match_in_wild_card +{ + my ($serverandnick, $white_or_black) = @_; + my $nick_iter; + my @array_of_nicks = split(",", $white_or_black); + + foreach $nick_iter (@array_of_nicks) + { + $nick_iter =~ s/\*/[^,]*/g; + if ($serverandnick =~ /$nick_iter/) + { + return 1; + } + } + return 0; +} + +sub my_process +{ + return weechat::WEECHAT_RC_OK; +} + +sub toggle_config_by_set +{ + my ($pointer, $name, $value) = @_; + $name = substr($name, length("plugins.var.perl.".$SCRIPT_NAME."."), length($name)); + $options{$name} = $value; + return weechat::WEECHAT_RC_OK; +} + +sub init_config +{ + my $version = weechat::info_get("version_number", "") || 0; + foreach my $option (keys %options_default) + { + if (!weechat::config_is_set_plugin($option)) + { + weechat::config_set_plugin($option, $options_default{$option}[0]); + $options{$option} = $options_default{$option}[0]; + } + else + { + $options{$option} = weechat::config_get_plugin($option); + } + if ($version >= 0x00030500) + { + weechat::config_set_desc_plugin($option, $options_default{$option}[1]." (default: \"".$options_default{$option}[0]."\")"); + } + } +} diff --git a/weechat/perl/buffers.pl b/weechat/perl/buffers.pl new file mode 100644 index 0000000..36cab01 --- /dev/null +++ b/weechat/perl/buffers.pl @@ -0,0 +1,998 @@ +# +# Copyright (C) 2008-2012 Sebastien Helleu +# Copyright (C) 2011-2012 Nils G +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# +# Display sidebar with list of buffers. +# +# History: +# +# 2012-06-02, nils_2 : +# v3.5: add values "server|channel|private|all|keepserver|none" to option "hide_merged_buffers" (suggested by dominikh). +# 2012-05-25, nils_2 : +# v3.4: add new option "show_lag". +# 2012-04-07, Sebastien Helleu : +# v3.3: fix truncation of wide chars in buffer name (option name_size_max) (bug #36034) +# 2012-03-15, nils_2 : +# v3.2: add new option "detach"(weechat >= 0.3.8) +# add new option "immune_detach_buffers" (requested by Mkaysi) +# add new function buffers_whitelist add|del|reset (suggested by FiXato) +# add new function buffers_detach add|del|reset +# 2012-03-09, Sebastien Helleu : +# v3.1: fix reload of config file +# 2012-01-29, nils_2 : +# v3.0: fix: buffers did not update directly during window_switch (reported by FiXato) +# 2012-01-29, nils_2 : +# v2.9: add options "name_size_max" and "name_crop_suffix" +# 2012-01-08, nils_2 : +# v2.8: fix indenting for option "show_number off" +# fix unset of buffer activity in hotlist when buffer was moved with mouse +# add buffer with free content and core buffer sorted first (suggested by nyuszika7h) +# add options queries_default_fg/bg and queries_message_fg/bg (suggested by FiXato) +# add clicking with left button on current buffer will do a jump_previously_visited_buffer (suggested by FiXato) +# add clicking with right button on current buffer will do a jump_next_visited_buffer +# add additional informations in help texts +# add default_fg and default_bg for whitelist channels +# internal changes (script is now 3Kb smaller) +# 2012-01-04, Sebastien Helleu : +# v2.7: fix regex lookup in whitelist buffers list +# 2011-12-04, nils_2 : +# v2.6: add own config file (buffers.conf) +# add new behavior for indenting (under_name) +# add new option to set different color for server buffers and buffers with free content +# 2011-10-30, nils_2 : +# v2.5: add new options "show_number_char" and "color_number_char", +# add help-description for options +# 2011-08-24, Sebastien Helleu : +# v2.4: add mouse support +# 2011-06-06, nils_2 : +# v2.3: added: missed option "color_whitelist_default" +# 2011-03-23, Sebastien Helleu : +# v2.2: fix color of nick prefix with WeeChat >= 0.3.5 +# 2011-02-13, nils_2 : +# v2.1: add options "color_whitelist_*" +# 2010-10-05, Sebastien Helleu : +# v2.0: add options "sort" and "show_number" +# 2010-04-12, Sebastien Helleu : +# v1.9: replace call to log() by length() to align buffer numbers +# 2010-04-02, Sebastien Helleu : +# v1.8: fix bug with background color and option indenting_number +# 2010-04-02, Helios : +# v1.7: add indenting_number option +# 2010-02-25, m4v : +# v1.6: add option to hide empty prefixes +# 2010-02-12, Sebastien Helleu : +# v1.5: add optional nick prefix for buffers like IRC channels +# 2009-09-30, Sebastien Helleu : +# v1.4: remove spaces for indenting when bar position is top/bottom +# 2009-06-14, Sebastien Helleu : +# v1.3: add option "hide_merged_buffers" +# 2009-06-14, Sebastien Helleu : +# v1.2: improve display with merged buffers +# 2009-05-02, Sebastien Helleu : +# v1.1: sync with last API changes +# 2009-02-21, Sebastien Helleu : +# v1.0: remove timer used to update bar item first time (not needed any more) +# 2009-02-17, Sebastien Helleu : +# v0.9: fix bug with indenting of private buffers +# 2009-01-04, Sebastien Helleu : +# v0.8: update syntax for command /set (comments) +# 2008-10-20, Jiri Golembiovsky : +# v0.7: add indenting option +# 2008-10-01, Sebastien Helleu : +# v0.6: add default color for buffers, and color for current active buffer +# 2008-09-18, Sebastien Helleu : +# v0.5: fix color for "low" level entry in hotlist +# 2008-09-18, Sebastien Helleu : +# v0.4: rename option "show_category" to "short_names", +# remove option "color_slash" +# 2008-09-15, Sebastien Helleu : +# v0.3: fix bug with priority in hotlist (var not defined) +# 2008-09-02, Sebastien Helleu : +# v0.2: add color for buffers with activity and config options for +# colors, add config option to display/hide categories +# 2008-03-15, Sebastien Helleu : +# v0.1: script creation +# +# Help about settings: +# display all settings for script (or use iset.pl script to change settings): +# /set buffers* +# show help text for option buffers.look.whitelist_buffers: +# /help buffers.look.whitelist_buffers +# +# Mouse-support (standard key bindings): +# left mouse-button: +# - click on a buffer to switch to selected buffer +# - click on current buffer will do action jump_previously_visited_buffer +# - drag a buffer and drop it on another position will move the buffer to position +# right mouse-button: +# - click on current buffer will do action jump_next_visited_buffer +# - moving buffer to the left/right will close buffer. +# + +use strict; +use Encode qw( decode encode ); +# -------------------------------[ internal ]------------------------------------- +my $version = "3.5"; + +my $BUFFERS_CONFIG_FILE_NAME = "buffers"; +my $buffers_config_file; +my $cmd_buffers_whitelist= "buffers_whitelist"; +my $cmd_buffers_detach = "buffers_detach"; + +my %mouse_keys = ("\@item(buffers):button1*" => "hsignal:buffers_mouse", # catch all left mouse button gestures + "\@item(buffers):button2" => "hsignal:buffers_mouse"); # catch right mouse button +my %options; +my %hotlist_level = (0 => "low", 1 => "message", 2 => "private", 3 => "highlight"); +my @whitelist_buffers = (); +my @immune_detach_buffers= (); +my @buffers_focus = (); +my %buffers_timer = (); +my %Hooks = (); + +# --------------------------------[ init ]-------------------------------------- +weechat::register("buffers", "Sebastien Helleu ", $version, + "GPL3", "Sidebar with list of buffers", "", ""); +my $weechat_version = weechat::info_get("version_number", "") || 0; + +buffers_config_init(); +buffers_config_read(); + +weechat::bar_item_new("buffers", "build_buffers", ""); +weechat::bar_new("buffers", "0", "0", "root", "", "left", "horizontal", + "vertical", "0", "0", "default", "default", "default", "1", + "buffers"); +weechat::hook_signal("buffer_*", "buffers_signal_buffer", ""); +weechat::hook_signal("window_switch", "buffers_signal_buffer", ""); +weechat::hook_signal("hotlist_*", "buffers_signal_hotlist", ""); +weechat::bar_item_update("buffers"); +if ($weechat_version >= 0x00030600) +{ + weechat::hook_focus("buffers", "buffers_focus_buffers", ""); + weechat::hook_hsignal("buffers_mouse", "buffers_hsignal_mouse", ""); + weechat::key_bind("mouse", \%mouse_keys); +} + +weechat::hook_command( $cmd_buffers_whitelist, + "add/del current buffer to/from buffers whitelist", + "[add] || [del] || [reset]", + + " add: add current buffer in configuration file\n". + " del: delete current buffer from configuration file\n". + "reset: reset all buffers from configuration file (no confirmation!)\n\n". + "Examples:\n". + "/$cmd_buffers_whitelist add\n", + "add %-||". + "del %-||". + "reset %-", + "buffers_cmd_whitelist", ""); + +weechat::hook_command( $cmd_buffers_detach, + "add/del current buffer to/from buffers detach", + "[add] || [del] || [reset]", + + " add: add current buffer in configuration file\n". + " del: delete current buffer from configuration file\n". + "reset: reset all buffers from configuration file (no confirmation!)\n\n". + "Examples:\n". + "/$cmd_buffers_detach add\n", + "add %-||". + "del %-||". + "reset %-", + "buffers_cmd_detach", ""); + +if ($weechat_version >= 0x00030800) +{ + weechat::hook_config("buffers.look.detach", "hook_timer_detach", ""); +} + + weechat::hook_config("buffers.look.show_lag", "hook_timer_lag", ""); + +# -------------------------------- [ command ] -------------------------------- +sub buffers_cmd_whitelist +{ +my ( $data, $buffer, $args ) = @_; + $args = lc($args); + my $buffers_whitelist = weechat::config_string( weechat::config_get("buffers.look.whitelist_buffers") ); + return weechat::WEECHAT_RC_OK if ( $buffers_whitelist eq "" and $args eq "del" or $buffers_whitelist eq "" and $args eq "reset" ); + my @buffers_list = split( /,/, $buffers_whitelist ); + # get buffers name + my $infolist = weechat::infolist_get("buffer", weechat::current_buffer(), ""); + weechat::infolist_next($infolist); + my $buffers_name = weechat::infolist_string($infolist, "name"); + weechat::infolist_free($infolist); + return weechat::WEECHAT_RC_OK if ( $buffers_name eq "" ); # should never happen + + if ( $args eq "add" ) + { + return weechat::WEECHAT_RC_OK if ( grep /^$buffers_name$/, @buffers_list ); # check if buffer already in list + push @buffers_list,( $buffers_name ); + my $buffers_list = &create_whitelist(\@buffers_list); + weechat::config_option_set( weechat::config_get("buffers.look.whitelist_buffers"), $buffers_list,1 ); + weechat::print(weechat::current_buffer(), "buffer \"$buffers_name\" added to buffers whitelist"); + } + elsif ( $args eq "del" ) + { + return weechat::WEECHAT_RC_OK unless ( grep /^$buffers_name$/, @buffers_list ); # check if buffer is in list + @buffers_list = grep {$_ ne $buffers_name} @buffers_list; # delete entry + my $buffers_list = &create_whitelist(\@buffers_list); + weechat::config_option_set( weechat::config_get("buffers.look.whitelist_buffers"), $buffers_list,1 ); + weechat::print(weechat::current_buffer(), "buffer \"$buffers_name\" deleted from buffers whitelist"); + } + elsif ( $args eq "reset" ) + { + return weechat::WEECHAT_RC_OK if ( $buffers_whitelist eq "" ); + weechat::config_option_set( weechat::config_get("buffers.look.whitelist_buffers"), "",1 ); + weechat::print(weechat::current_buffer(), "buffers whitelist is empty, now..."); + } + return weechat::WEECHAT_RC_OK; +} +sub buffers_cmd_detach +{ +my ( $data, $buffer, $args ) = @_; + $args = lc($args); + my $immune_detach_buffers = weechat::config_string( weechat::config_get("buffers.look.immune_detach_buffers") ); + return weechat::WEECHAT_RC_OK if ( $immune_detach_buffers eq "" and $args eq "del" or $immune_detach_buffers eq "" and $args eq "reset" ); + my @buffers_list = split( /,/, $immune_detach_buffers ); + # get buffers name + my $infolist = weechat::infolist_get("buffer", weechat::current_buffer(), ""); + weechat::infolist_next($infolist); + my $buffers_name = weechat::infolist_string($infolist, "name"); + weechat::infolist_free($infolist); + return weechat::WEECHAT_RC_OK if ( $buffers_name eq "" ); # should never happen + + if ( $args eq "add" ) + { + return weechat::WEECHAT_RC_OK if ( grep /^$buffers_name$/, @buffers_list ); # check if buffer already in list + push @buffers_list,( $buffers_name ); + my $buffers_list = &create_whitelist(\@buffers_list); + weechat::config_option_set( weechat::config_get("buffers.look.immune_detach_buffers"), $buffers_list,1 ); + weechat::print(weechat::current_buffer(), "buffer \"$buffers_name\" added to immune detach buffers"); + } + elsif ( $args eq "del" ) + { + return weechat::WEECHAT_RC_OK unless ( grep /^$buffers_name$/, @buffers_list ); # check if buffer is in list + @buffers_list = grep {$_ ne $buffers_name} @buffers_list; # delete entry + my $buffers_list = &create_whitelist(\@buffers_list); + weechat::config_option_set( weechat::config_get("buffers.look.immune_detach_buffers"), $buffers_list,1 ); + weechat::print(weechat::current_buffer(), "buffer \"$buffers_name\" deleted from immune detach buffers"); + } + elsif ( $args eq "reset" ) + { + return weechat::WEECHAT_RC_OK if ( $immune_detach_buffers eq "" ); + weechat::config_option_set( weechat::config_get("buffers.look.immune_detach_buffers"), "",1 ); + weechat::print(weechat::current_buffer(), "immune detach buffers is empty, now..."); + } + return weechat::WEECHAT_RC_OK; +} +sub create_whitelist +{ + my @buffers_list = @{$_[0]}; + my $buffers_list = ""; + foreach (@buffers_list) + { + $buffers_list .= $_ .","; + } + chop $buffers_list; # remove last "," + return $buffers_list; +} + +# -------------------------------- [ config ] -------------------------------- +sub hook_timer_detach +{ + my $detach = $_[2]; + if ( $detach eq 0 ) + { + weechat::unhook($Hooks{timer_detach}) if $Hooks{timer_detach}; + $Hooks{timer_detach} = ""; + } + else + { + weechat::unhook($Hooks{timer_detach}) if $Hooks{timer_detach}; + $Hooks{timer_detach} = weechat::hook_timer( weechat::config_integer( $options{"detach"}) * 1000, 60, 0, "buffers_signal_buffer", ""); + } + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} + +sub hook_timer_lag +{ + my $lag = $_[2]; + if ( $lag eq 0 ) + { + weechat::unhook($Hooks{timer_lag}) if $Hooks{timer_lag}; + $Hooks{timer_lag} = ""; + } + else + { + weechat::unhook($Hooks{timer_lag}) if $Hooks{timer_lag}; + $Hooks{timer_lag} = weechat::hook_timer( weechat::config_integer(weechat::config_get("irc.network.lag_refresh_interval")) * 1000, 0, 0, "buffers_signal_hotlist", ""); + } + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} + +sub buffers_config_read +{ + return weechat::config_read($buffers_config_file) if ($buffers_config_file ne ""); +} +sub buffers_config_write +{ + return weechat::config_write($buffers_config_file) if ($buffers_config_file ne ""); +} +sub buffers_config_reload_cb +{ + my ($data,$config_file) = ($_[0], $_[1]); + return weechat::config_reload($config_file) +} +sub buffers_config_init +{ + $buffers_config_file = weechat::config_new($BUFFERS_CONFIG_FILE_NAME,"buffers_config_reload_cb",""); + return if ($buffers_config_file eq ""); + +my %default_options_color = +("color_current_fg" => ["current_fg", "color", "foreground color for current buffer", "", 0, 0,"lightcyan", "lightcyan", 0, "", "","buffers_signal_config", "", "", ""], + "color_current_bg" => ["current_bg", "color", "background color for current buffer", "", 0, 0,"red", "red", 0, "", "","buffers_signal_config", "", "", ""], + "color_default_fg" => ["default_fg", "color", "default foreground color for buffer name", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_default_bg" => ["default_bg", "color", "default background color for buffer name", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_highlight_fg" => ["hotlist_highlight_fg", "color", "change foreground color of buffer name if a highlight messaged received","", 0, 0,"magenta", "magenta", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_highlight_bg" => ["hotlist_highlight_bg", "color", "change background color of buffer name if a highlight messaged received", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_low_fg" => ["hotlist_low_fg", "color", "change foreground color of buffer name if a low message received", "", 0, 0,"white", "white", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_low_bg" => ["hotlist_low_bg", "color", "change background color of buffer name if a low message received", "", 0, 0, + "default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_message_fg" => ["hotlist_message_fg", "color", "change foreground color of buffer name if a normal message received", "", 0, 0,"yellow", "yellow", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_message_bg" => ["hotlist_message_bg", "color", "change background color of buffer name if a normal message received", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_private_fg" => ["hotlist_private_fg", "color", "change foreground color of buffer name if a private message received", "", 0, 0,"lightgreen", "lightgreen", 0, "", "","buffers_signal_config", "", "", ""], + "color_hotlist_private_bg" => ["hotlist_private_bg", "color", "change background color of buffer name if a private message received", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_number" => ["number", "color", "color for buffer number", "", 0, 0,"lightgreen", "lightgreen", 0, "", "","buffers_signal_config", "", "", ""], + "color_number_char" => ["number_char", "color", "color for buffer number char", "", 0, 0,"lightgreen", "lightgreen", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_default_fg" => ["whitelist_default_fg", "color", "default foreground color for whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_default_bg" => ["whitelist_default_bg", "color", "default background color for whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_low_fg" => ["whitelist_low_fg", "color", "low color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_low_bg" => ["whitelist_low_bg", "color", "low color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_message_fg" => ["whitelist_message_fg", "color", "message color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_message_bg" => ["whitelist_message_bg", "color", "message color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_private_fg" => ["whitelist_private_fg", "color", "private color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_private_bg" => ["whitelist_private_bg", "color", "private color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_highlight_fg" => ["whitelist_highlight_fg", "color", "highlight color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_whitelist_highlight_bg" => ["whitelist_highlight_bg", "color", "highlight color of whitelist buffer name", "", 0, 0,"", "", 0, "", "","buffers_signal_config", "", "", ""], + "color_none_channel_fg" => ["none_channel_fg", "color", "foreground color for none channel buffer (e.g.: core/server/plugin buffer)", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "color_none_channel_bg" => ["none_channel_bg", "color", "background color for none channel buffer (e.g.: core/server/plugin buffer)", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "queries_default_fg" => ["queries_default_fg", "color", "foreground color for query buffer without message", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "queries_default_bg" => ["queries_default_bg", "color", "background color for query buffer without message", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "queries_message_fg" => ["queries_message_fg", "color", "foreground color for query buffer with unread message", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "queries_message_bg" => ["queries_message_bg", "color", "background color for query buffer with unread message", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "queries_highlight_fg" => ["queries_highlight_fg", "color", "foreground color for query buffer with unread highlight", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], + "queries_highlight_bg" => ["queries_highlight_bg", "color", "background color for query buffer with unread highlight", "", 0, 0,"default", "default", 0, "", "","buffers_signal_config", "", "", ""], +); + +my %default_options_look = +( + "show_lag" => ["show_lag","boolean","show lag behind servername. This option is using \"irc.color.item_lag_finished\", \"irc.network.lag_min_show\" and \"irc.network.lag_refresh_interval\"","",0,0,"off","off",0,"","","buffers_signal_config","","",""], + "look_whitelist_buffers" => ["whitelist_buffers", "string", "comma separated list of buffers for using a differnt color scheme (for example: freenode.#weechat,freenode.#weechat-fr)", "", 0, 0,"", "", 0, "", "", "buffers_signal_config_whitelist", "", "", ""], + "hide_merged_buffers" => ["hide_merged_buffers", "integer", "hide merged buffers. The value determines which merged buffers should be hidden, keepserver meaning 'all except server buffers'. Other values correspondent to the buffer type.", "server|channel|private|keepserver|all|none", 0, 0,"none", "none", 0, "", "", "buffers_signal_config", "", "", ""], + "indenting" => ["indenting", "integer", "use indenting for channel and query buffers. This option only takes effect if bar is left/right positioned", "off|on|under_name", 0, 0,"off", "off", 0, "", "", "buffers_signal_config", "", "", ""], + "indenting_number" => ["indenting_number", "boolean", "use indenting for numbers. This option only takes effect if bar is left/right positioned", "", 0, 0,"on", "on", 0, "", "", "buffers_signal_config", "", "", ""], + "short_names" => ["short_names", "boolean", "display short names (remove text before first \".\" in buffer name)", "", 0, 0,"on", "on", 0, "", "", "buffers_signal_config", "", "", ""], + "show_number" => ["show_number", "boolean", "display channel number in front of buffername", "", 0, 0,"on", "on", 0, "", "", "buffers_signal_config", "", "", ""], + "show_number_char" => ["number_char", "string", "display a char after channel number", "", 0, 0,".", ".", 0, "", "", "buffers_signal_config", "", "", ""], + "show_prefix" => ["prefix", "boolean", "show your prefix for channel", "", 0, 0,"off", "off", 0, "", "", "buffers_signal_config", "", "", ""], + "show_prefix_empty" => ["prefix_empty", "boolean", "use a placeholder for channels without prefix", "", 0, 0,"on", "on", 0, "", "", "buffers_signal_config", "", "", ""], + "sort" => ["sort", "integer", "sort buffer-list by \"number\" or \"name\"", "number|name", 0, 0,"number", "number", 0, "", "", "buffers_signal_config", "", "", ""], + "core_to_front" => ["core_to_front", "boolean", "core buffer and buffers with free content will be listed first. Take only effect if buffer sort is by name", "", 0, 0,"off", "off", 0, "", "", "buffers_signal_config", "", "", ""], + "jump_prev_next_visited_buffer" => ["jump_prev_next_visited_buffer", "boolean", "jump to previously or next visited buffer if you click with left/right mouse button on currently visiting buffer", "", 0, 0,"off", "off", 0, "", "", "buffers_signal_config", "", "", ""], + "name_size_max" => ["name_size_max","integer","maximum size of buffer name. 0 means no limitation","",0,256,0,0,0, "", "", "buffers_signal_config", "", "", ""], + "name_crop_suffix" => ["name_crop_suffix","string","contains an optional char(s) that is appended when buffer name is shortened","",0,0,"+","+",0,"","","buffers_signal_config", "", "", ""], + "detach" => ["detach", "integer","detach channel from buffers list after a specific period of time (in seconds) without action (weechat ≥ 0.3.8 required)", "", 0, 31536000,0, "number", 0, "", "", "buffers_signal_config", "", "", ""], + "immune_detach_buffers" => ["immune_detach_buffers", "string", "comma separated list of buffers which will not get detached automatically. Good with e.g. BitlBee", "", 0, 0,"", "", 0, "", "", "buffers_signal_config_immune_detach_buffers", "", "", ""], +); + # section "color" + my $section_color = weechat::config_new_section($buffers_config_file,"color", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_color eq "") + { + weechat::config_free($buffers_config_file); + return; + } + foreach my $option (keys %default_options_color) + { + $options{$option} = weechat::config_new_option($buffers_config_file, $section_color, + $default_options_color{$option}[0],$default_options_color{$option}[1],$default_options_color{$option}[2], + $default_options_color{$option}[3],$default_options_color{$option}[4],$default_options_color{$option}[5], + $default_options_color{$option}[6],$default_options_color{$option}[7],$default_options_color{$option}[8], + $default_options_color{$option}[9],$default_options_color{$option}[10],$default_options_color{$option}[11], + $default_options_color{$option}[12],$default_options_color{$option}[13],$default_options_color{$option}[14]); + } + + # section "look" + my $section_look = weechat::config_new_section($buffers_config_file,"look", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_look eq "") + { + weechat::config_free($buffers_config_file); + return; + } + foreach my $option (keys %default_options_look) + { + $options{$option} = weechat::config_new_option($buffers_config_file, $section_look, + $default_options_look{$option}[0],$default_options_look{$option}[1],$default_options_look{$option}[2], + $default_options_look{$option}[3],$default_options_look{$option}[4],$default_options_look{$option}[5], + $default_options_look{$option}[6],$default_options_look{$option}[7],$default_options_look{$option}[8], + $default_options_look{$option}[9],$default_options_look{$option}[10],$default_options_look{$option}[11], + $default_options_look{$option}[12],$default_options_look{$option}[13],$default_options_look{$option}[14]); + } +} + +sub build_buffers +{ + my $str = ""; + + # get bar position (left/right/top/bottom) + my $position = "left"; + my $option_position = weechat::config_get("weechat.bar.buffers.position"); + if ($option_position ne "") + { + $position = weechat::config_string($option_position); + } + + # read hotlist + my %hotlist; + my $infolist = weechat::infolist_get("hotlist", "", ""); + while (weechat::infolist_next($infolist)) + { + $hotlist{weechat::infolist_pointer($infolist, "buffer_pointer")} = + weechat::infolist_integer($infolist, "priority"); + } + weechat::infolist_free($infolist); + + # read buffers list + @buffers_focus = (); + my @buffers; + my @current1 = (); + my @current2 = (); + my $old_number = -1; + my $max_number = 0; + my $max_number_digits = 0; + my $active_seen = 0; + $infolist = weechat::infolist_get("buffer", "", ""); + while (weechat::infolist_next($infolist)) + { + my $buffer; + my $number = weechat::infolist_integer($infolist, "number"); + if ($number ne $old_number) + { + @buffers = (@buffers, @current2, @current1); + @current1 = (); + @current2 = (); + $active_seen = 0; + } + if ($number > $max_number) + { + $max_number = $number; + } + $old_number = $number; + my $active = weechat::infolist_integer($infolist, "active"); + if ($active) + { + $active_seen = 1; + } + $buffer->{"pointer"} = weechat::infolist_pointer($infolist, "pointer"); + $buffer->{"number"} = $number; + $buffer->{"active"} = $active; + $buffer->{"current_buffer"} = weechat::infolist_integer($infolist, "current_buffer"); + $buffer->{"plugin_name"} = weechat::infolist_string($infolist, "plugin_name"); + $buffer->{"name"} = weechat::infolist_string($infolist, "name"); + $buffer->{"short_name"} = weechat::infolist_string($infolist, "short_name"); + $buffer->{"full_name"} = $buffer->{"plugin_name"}.".".$buffer->{"name"}; + $buffer->{"type"} = weechat::buffer_get_string($buffer->{"pointer"},"localvar_type"); +# weechat::print("",$buffer->{"type"}); + + unless( grep {$_ eq $buffer->{"name"}} @immune_detach_buffers ) + { + my $detach_time = weechat::config_integer( $options{"detach"}); + my $current_time = time(); + # set timer for buffers with no hotlist action + $buffers_timer{$buffer->{"pointer"}} = $current_time + if ( not exists $hotlist{$buffer->{"pointer"}} + and $buffer->{"type"} eq "channel" + and not exists $buffers_timer{$buffer->{"pointer"}} + and $detach_time > 0); + + # check for detach + unless ( $buffer->{"current_buffer"} eq 0 + and not exists $hotlist{$buffer->{"pointer"}} + and $buffer->{"type"} eq "channel" + and exists $buffers_timer{$buffer->{"pointer"}} + and $detach_time > 0 + and $weechat_version >= 0x00030800 + and $current_time - $buffers_timer{$buffer->{"pointer"}} >= $detach_time ) + { + if ($active_seen) + { + push(@current2, $buffer); + } + else + { + push(@current1, $buffer); + } + } + } + else + { + if ($active_seen) + { + push(@current2, $buffer); + } + else + { + push(@current1, $buffer); + } + } + + } # while end + + + if ($max_number >= 1) + { + $max_number_digits = length(int($max_number)); + } + @buffers = (@buffers, @current2, @current1); + weechat::infolist_free($infolist); + + # sort buffers by number, name or shortname + my %sorted_buffers; + if (1) + { + my $number = 0; + for my $buffer (@buffers) + { + my $key; + if (weechat::config_integer( $options{"sort"} ) eq 1) # number = 0; name = 1 + { + my $name = $buffer->{"name"}; + $name = $buffer->{"short_name"} if (weechat::config_boolean( $options{"short_names"} ) eq 1); + if (weechat::config_integer($options{"name_size_max"}) >= 1){ + $name = encode("UTF-8", substr(decode("UTF-8", $name), 0, weechat::config_integer($options{"name_size_max"}))); + } + if ( weechat::config_boolean($options{"core_to_front"}) eq 1) + { + if ( (weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") ne "channel" ) and ( weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") ne "private") ) + { + my $type = weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type"); + if ( $type eq "" and $name ne "weechat") + { + $name = " " . $name + }else + { + $name = " " . $name; + } + } + } + $key = sprintf("%s%08d", lc($name), $buffer->{"number"}); + } + else + { + $key = sprintf("%08d", $number); + } + $sorted_buffers{$key} = $buffer; + $number++; + } + } + + # build string with buffers + $old_number = -1; + foreach my $key (sort keys %sorted_buffers) + { + my $buffer = $sorted_buffers{$key}; + + if ( weechat::config_string($options{"hide_merged_buffers"}) eq "server" ) + { + # buffer type "server" or merged with core? + if ( ($buffer->{"type"} eq "server" or $buffer->{"plugin_name"} eq "core") && (! $buffer->{"active"}) ) + { + next; + } + } + if ( weechat::config_string($options{"hide_merged_buffers"}) eq "channel" ) + { + # buffer type "channel" or merged with core? + if ( ($buffer->{"type"} eq "channel" or $buffer->{"plugin_name"} eq "core") && (! $buffer->{"active"}) ) + { + next; + } + } + if ( weechat::config_string($options{"hide_merged_buffers"}) eq "private" ) + { + # buffer type "private" or merged with core? + if ( ($buffer->{"type"} eq "private" or $buffer->{"plugin_name"} eq "core") && (! $buffer->{"active"}) ) + { + next; + } + } + if ( weechat::config_string($options{"hide_merged_buffers"}) eq "keepserver" ) + { + if ( ($buffer->{"type"} ne "server" or $buffer->{"plugin_name"} eq "core") && (! $buffer->{"active"}) ) + { + next; + } + } + if ( weechat::config_string($options{"hide_merged_buffers"}) eq "all" ) + { + if ( ! $buffer->{"active"} ) + { + next; + } + } + + push(@buffers_focus, $buffer); # buffer > buffers_focus, for mouse support + my $color = ""; + my $bg = ""; + + $color = weechat::config_color( $options{"color_default_fg"} ); + $bg = weechat::config_color( $options{"color_default_bg"} ); + + if ( weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") eq "private" ) + { + if ( (weechat::config_color($options{"queries_default_bg"})) ne "default" || (weechat::config_color($options{"queries_default_fg"})) ne "default" ) + { + $bg = weechat::config_color( $options{"queries_default_bg"} ); + $color = weechat::config_color( $options{"queries_default_fg"} ); + } + } + # check for core and buffer with free content + if ( (weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") ne "channel" ) and ( weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") ne "private") ) + { + $color = weechat::config_color( $options{"color_none_channel_fg"} ); + $bg = weechat::config_color( $options{"color_none_channel_bg"} ); + } + # default whitelist buffer? + if (grep {$_ eq $buffer->{"name"}} @whitelist_buffers) + { + $color = weechat::config_color( $options{"color_whitelist_default_fg"} ); + $bg = weechat::config_color( $options{"color_whitelist_default_bg"} ); + } + + $color = "default" if ($color eq ""); + + # color for channel and query buffer + if (exists $hotlist{$buffer->{"pointer"}}) + { + delete $buffers_timer{$buffer->{"pointer"}}; + # check if buffer is in whitelist buffer + if (grep {$_ eq $buffer->{"name"}} @whitelist_buffers) + { + $bg = weechat::config_color( $options{"color_whitelist_".$hotlist_level{$hotlist{$buffer->{"pointer"}}}."_bg"} ); + $color = weechat::config_color( $options{"color_whitelist_".$hotlist_level{$hotlist{$buffer->{"pointer"}}}."_fg"} ); + } + elsif ( weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") eq "private" ) + { + # queries_default_fg/bg and buffers.color.queries_message_fg/bg + if ( (weechat::config_color($options{"queries_highlight_fg"})) ne "default" || + (weechat::config_color($options{"queries_highlight_bg"})) ne "default" || + (weechat::config_color($options{"queries_message_fg"})) ne "default" || + (weechat::config_color($options{"queries_message_bg"})) ne "default" ) + { + if ( ($hotlist{$buffer->{"pointer"}}) == 2 ) + { + $bg = weechat::config_color( $options{"queries_message_bg"} ); + $color = weechat::config_color( $options{"queries_message_fg"} ); + } + + elsif ( ($hotlist{$buffer->{"pointer"}}) == 3 ) + { + $bg = weechat::config_color( $options{"queries_highlight_bg"} ); + $color = weechat::config_color( $options{"queries_highlight_fg"} ); + } + }else + { + $bg = weechat::config_color( $options{"color_hotlist_".$hotlist_level{$hotlist{$buffer->{"pointer"}}}."_bg"} ); + $color = weechat::config_color( $options{"color_hotlist_".$hotlist_level{$hotlist{$buffer->{"pointer"}}}."_fg"} ); + } + }else + { + $bg = weechat::config_color( $options{"color_hotlist_".$hotlist_level{$hotlist{$buffer->{"pointer"}}}."_bg"} ); + $color = weechat::config_color( $options{"color_hotlist_".$hotlist_level{$hotlist{$buffer->{"pointer"}}}."_fg"} ); + } + } + + if ($buffer->{"current_buffer"}) + { + $color = weechat::config_color( $options{"color_current_fg"} ); + $bg = weechat::config_color( $options{"color_current_bg"} ); + } + my $color_bg = ""; + $color_bg = weechat::color(",".$bg) if ($bg ne ""); + + # create channel number for output + if ( weechat::config_boolean( $options{"show_number"} ) eq 1 ) # on + { + if (( weechat::config_boolean( $options{"indenting_number"} ) eq 1) + && (($position eq "left") || ($position eq "right"))) + { + $str .= weechat::color("default").$color_bg + .(" " x ($max_number_digits - length(int($buffer->{"number"})))); + } + if ($old_number ne $buffer->{"number"}) + { + $str .= weechat::color( weechat::config_color( $options{"color_number"} ) ) + .$color_bg + .$buffer->{"number"} + .weechat::color("default") + .$color_bg + .weechat::color( weechat::config_color( $options{"color_number_char"} ) ) + .weechat::config_string( $options{"show_number_char"} ) + .$color_bg; + } + else + { + my $indent = ""; + $indent = ((" " x length($buffer->{"number"}))." ") if (($position eq "left") || ($position eq "right")); + $str .= weechat::color("default") + .$color_bg + .$indent; + } + } + + if (( weechat::config_integer( $options{"indenting"} ) ne 0 ) # indenting NOT off + && (($position eq "left") || ($position eq "right"))) + { + my $type = weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type"); + if (($type eq "channel") || ($type eq "private")) + { + if ( weechat::config_integer( $options{"indenting"} ) eq 1 ) + { + $str .= " "; + } + elsif ( (weechat::config_integer($options{"indenting"}) eq 2) and (weechat::config_integer($options{"indenting_number"}) eq 0) ) #under_name + { + if ( weechat::config_boolean( $options{"show_number"} ) eq 0 ) + { + $str .= " "; + }else + { + $str .= ( (" " x ( $max_number_digits - length($buffer->{"number"}) ))." " ); + } + } + } + } + if (weechat::config_boolean( $options{"show_prefix"} ) eq 1) + { + my $nickname = weechat::buffer_get_string($buffer->{"pointer"}, "localvar_nick"); + if ($nickname ne "") + { + # with version >= 0.3.2, this infolist will return only nick + # with older versions, whole nicklist is returned for buffer, and this can be very slow + my $infolist_nick = weechat::infolist_get("nicklist", $buffer->{"pointer"}, "nick_".$nickname); + if ($infolist_nick ne "") + { + my $version = weechat::info_get("version_number", ""); + $version = 0 if ($version eq ""); + while (weechat::infolist_next($infolist_nick)) + { + if ((weechat::infolist_string($infolist_nick, "type") eq "nick") + && (weechat::infolist_string($infolist_nick, "name") eq $nickname)) + { + my $prefix = weechat::infolist_string($infolist_nick, "prefix"); + if (($prefix ne " ") or (weechat::config_boolean( $options{"show_prefix_empty"} ) eq 1)) + { + # with version >= 0.3.5, it is now a color name (for older versions: option name with color) + if (int($version) >= 0x00030500) + { + $str .= weechat::color(weechat::infolist_string($infolist_nick, "prefix_color")); + } + else + { + $str .= weechat::color(weechat::config_color( + weechat::config_get( + weechat::infolist_string($infolist_nick, "prefix_color")))); + } + $str .= $prefix; + } + last; + } + } + weechat::infolist_free($infolist_nick); + } + } + } + $str .= weechat::color($color) . weechat::color(",".$bg); + + if (weechat::config_boolean( $options{"short_names"} ) eq 1) + { + if (weechat::config_integer($options{"name_size_max"}) >= 1) # check max_size of buffer name + { + $str .= encode("UTF-8", substr(decode("UTF-8", $buffer->{"short_name"}), 0, weechat::config_integer($options{"name_size_max"}))); + $str .= weechat::color(weechat::config_color( $options{"color_number_char"})).weechat::config_string($options{"name_crop_suffix"}) if (length($buffer->{"short_name"}) > weechat::config_integer($options{"name_size_max"})); + } + else + { + $str .= $buffer->{"short_name"}; + } + } + else + { + if (weechat::config_integer($options{"name_size_max"}) >= 1) # check max_size of buffer name + { + $str .= encode("UTF-8", substr(decode("UTF-8", $buffer->{"name"},), 0, weechat::config_integer($options{"name_size_max"}))); + $str .= weechat::color(weechat::config_color( $options{"color_number_char"})).weechat::config_string($options{"name_crop_suffix"}) if (length($buffer->{"name"}) > weechat::config_integer($options{"name_size_max"})); + } + else + { + $str .= $buffer->{"name"}; + } + } + if ( weechat::buffer_get_string($buffer->{"pointer"}, "localvar_type") eq "server" and weechat::config_boolean($options{"show_lag"}) eq 1) + { + my $color_lag = weechat::config_color(weechat::config_get("irc.color.item_lag_finished")); + my $min_lag = weechat::config_integer(weechat::config_get("irc.network.lag_min_show")); + my $infolist_server = weechat::infolist_get("irc_server","",$buffer->{"short_name"}); + weechat::infolist_next($infolist_server); + my $lag = (weechat::infolist_integer($infolist_server, "lag")); + weechat::infolist_free($infolist_server); + if ( int($lag) > int($min_lag) ) + { + $lag = $lag / 1000; + $str .= weechat::color("default") . " (" . weechat::color($color_lag) . $lag . weechat::color("default") . ")"; + } + } + $str .= "\n"; + $old_number = $buffer->{"number"}; + } + + return $str; +} + +sub buffers_signal_buffer +{ +my ($data, $signal, $signal_data) = @_; + # check for buffer_switch and set the detach time or remove detach time + if ($weechat_version >= 0x00030800) + { + if ($signal eq "buffer_switch") + { + my $pointer = weechat::hdata_get_list (weechat::hdata_get("buffer"), "gui_buffer_last_displayed"); # get switched buffer + my $current_time = time(); + if ( weechat::buffer_get_string($pointer, "localvar_type") eq "channel") + { + $buffers_timer{$pointer} = $current_time; + } + else + { + delete $buffers_timer{$pointer}; + } + } + if ($signal eq "buffer_opened") + { + my $current_time = time(); + $buffers_timer{$signal_data} = $current_time; + } + if ($signal eq "buffer_closing") + { + delete $buffers_timer{$signal_data}; + } + } + + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} + +sub buffers_signal_hotlist +{ + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} + + +sub buffers_signal_config_whitelist +{ + @whitelist_buffers = (); + @whitelist_buffers = split( /,/, weechat::config_string( $options{"look_whitelist_buffers"} ) ); + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} +sub buffers_signal_config_immune_detach_buffers +{ + @immune_detach_buffers = (); + @immune_detach_buffers = split( /,/, weechat::config_string( $options{"immune_detach_buffers"} ) ); + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} + +sub buffers_signal_config +{ + weechat::bar_item_update("buffers"); + return weechat::WEECHAT_RC_OK; +} + +# called when mouse click occured in buffers item: this callback returns buffer +# hash according to line of item where click occured +sub buffers_focus_buffers +{ + my %info = %{$_[1]}; + my $item_line = int($info{"_bar_item_line"}); + undef my $hash; + if (($info{"_bar_item_name"} eq "buffers") && ($item_line >= 0) && ($item_line <= $#buffers_focus)) + { + $hash = $buffers_focus[$item_line]; + } + else + { + $hash = {}; + my $hash_focus = $buffers_focus[0]; + foreach my $key (keys %$hash_focus) + { + $hash->{$key} = "?"; + } + } + return $hash; +} + +# called when a mouse action is done on buffers item, to execute action +# possible actions: jump to a buffer or move buffer in list (drag & drop of buffer) +sub buffers_hsignal_mouse +{ + my ($data, $signal, %hash) = ($_[0], $_[1], %{$_[2]}); + my $current_buffer = weechat::buffer_get_integer(weechat::current_buffer(), "number"); # get current buffer number + + if ( $hash{"_key"} eq "button1" ) # left mouse button + { + if ($hash{"number"} eq $hash{"number2"}) + { + if ( weechat::config_integer($options{"jump_prev_next_visited_buffer"}) eq 1 ) + { + if ( $current_buffer eq $hash{"number"} ) + { + weechat::command("","/input jump_previously_visited_buffer"); + } + else + { + weechat::command("", "/buffer ".$hash{"full_name"}); + } + } + else + { + weechat::command("", "/buffer ".$hash{"full_name"}); + } + } + else + { + move_buffer(%hash); + } + } + elsif ( ($hash{"_key"} eq "button2") && (weechat::config_integer($options{"jump_prev_next_visited_buffer"}) eq 1) )# right mouse button + { + if ( $current_buffer eq $hash{"number2"} ) + { + weechat::command("","/input jump_next_visited_buffer"); + } + } + else + { + move_buffer(%hash); + } +} +sub move_buffer +{ + my %hash = @_; + my $number2 = $hash{"number2"}; + if ($number2 eq "?") + { + # if number 2 is not known (end of gesture outside buffers list), then set it + # according to mouse gesture + $number2 = "999999"; + $number2 = "1" if (($hash{"_key"} =~ /gesture-left/) || ($hash{"_key"} =~ /gesture-up/)); + } + my $ptrbuf = weechat::current_buffer(); + weechat::command($hash{"pointer"}, "/buffer move ".$number2); +} diff --git a/weechat/perl/chanmon.pl b/weechat/perl/chanmon.pl new file mode 100644 index 0000000..18544de --- /dev/null +++ b/weechat/perl/chanmon.pl @@ -0,0 +1,1116 @@ +# +# chanmon.pl - Channel Monitoring for weechat 0.3.0 +# Version 2.3.1 +# +# Add 'Channel Monitor' buffer/bar that you can position to show IRC channel +# messages in a single location without constantly switching buffers +# i.e. In a seperate window beneath the main channel buffer +# +# Usage: +# /chanmon [help] | [monitor [channel [server]]] | [dynmon] | [clean default|orphan|all] +# Command wrapper for chanmon commands +# +# /chmonitor [channel] [server] is used to toggle a channel monitoring on and off, this +# can be used in the channel buffer for the channel you wish to toggle, or be given +# with arguments e.g. /monitor #weechat freenode +# +# /dynmon is used to toggle 'Dynamic Channel Monitoring' on and off, this +# will automagically stop monitoring the current active buffer, without +# affecting regular settings (Default is off) +# +# /chanclean default|orphan|all will clean the config section of default 'on' entries, +# channels you are no longer joined, or both +# +# /set plugins.var.perl.chanmon.alignment +# The config setting "alignment" can be changed to; +# "channel", "schannel", "nchannel", "channel,nick", "schannel,nick", "nchannel,nick" +# to change how the monitor appears +# The 'channel' value will show: "#weechat" +# The 'schannel' value will show: "6" +# The 'nchannel' value will show: "6:#weechat" +# +# /set plugins.var.perl.chanmon.short_names +# Setting this to 'on' will trim the network name from chanmon, ala buffers.pl +# +# /set plugins.var.perl.chanmon.merge_private +# Setting this to 'on' will merge private messages to chanmon's display +# +# /set plugins.var.perl.chanmon.color_buf +# This turns colored buffer names on or off, you can also set a single fixed color by using a weechat color name. +# This *must* be a valid color name, or weechat will likely do unexpected things :) +# +# /set plugins.var.perl.chanmon.show_aways +# Toggles showing the Weechat away messages +# +# /set plugins.var.perl.chanmon.logging +# Toggles logging status for chanmon buffer (default: off) +# +# /set plugins.var.perl.chanmon.output +# Changes where output method of chanmon; takes either "bar" or "buffer" (default; buffer) +# /set plugins.var.perl.chanmon.bar_lines +# Changes the amount of lines the output bar will hold. +# (Only appears once output has been set to bar, defaults to 10) +# +# /set plugins.var.perl.chanmon.nick_prefix +# /set plugins.var.perl.chanmon.nick_suffix +# Sets the prefix and suffix chars in the chanmon buffer +# (Defaults to <> if nothing set, and blank if there is) +# +# servername.#channel +# servername is the internal name for the server (set when you use /server add) +# #channel is the channel name, (where # is whatever channel type that channel happens to be) +# +# Ideal set up: +# Split the layout 70/30 (or there abouts) horizontally and load +# Optionally, make the status and input lines only show on active windows +# +# /window splith 70 --> open the chanmon buffer +# /set weechat.bar.status.conditions "active" +# /set weechat.bar.input.conditions "active" + +# History: +# 2012-04-15, KenjiE20 : +# v2.3.1: -fix: Colour tags in bar timestamp string, bar error fixes from highmon +# 2012-02-28, KenjiE20 : +# v2.3: -feature: Added merge_private option to display private messages (default: off) +# 2010-12-22, KenjiE20 : +# v2.2: -change: Use API instead of config to find channel colours, ready for 0.3.4 and 256 colours +# 2010-12-05, KenjiE20 : +# v2.1.3: -change: /monitor is now /chmonitor to avoid command conflicts (thanks m4v) +# (/chanmon monitor remains the same) +# -fix: Add command list to inbuilt help +# 2010-09-30, KenjiE20 : +# v2.1.2: -fix: logging config was not correctly toggling back on (thanks to sleo for noticing) +# 2010-09-20, m4v : +# v2.1.1: -fix: chanmon wasn't detecting buffers displayed on more than one window +# 2010-08-27, KenjiE20 : +# v2.1: -feature: Add 'nchannel' option to alignment to display buffer and name +# 2010-04-25, KenjiE20 : +# v2.0: Release as version 2.0 +# 2010-04-24, KenjiE20 : +# -fix: No longer using hard-coded detection for ACTION and +# TOPIC messages. Use config settings for ACTION printing +# 2010-04-15, KenjiE20 : +# v1.9: Rewrite for v2.0 +# -feature: /monitor takes arguments +# -feature: Added /chanclean for config cleanup +# -feature: Buffer logging option (default: off) +# -feature: Selectable output (Bar/Buffer (default)) +# -feature: /chanmon is now a command wrapper for all commands +# /help chanmon gives command help +# /chanmon help gives config help +# -code change: Made more subs to shrink the code down in places +# -fix: Stop chanmon attempting to double load/hook +# 2010-02-10, m4v : +# v1.7.1: -fix: chanmon was leaking infolists, changed how chanmon +# detects if the buffer is displayed or not. +# 2010-01-25, KenjiE20 : +# v1.7: -fixture: Let chanmon be aware of nick_prefix/suffix +# and allow custom prefix/suffix for chanmon buffer +# (Defaults to <> if nothing set, and blank if there is) +# -fix: Make dynamic monitoring aware of multiple windows +# rather than just the active buffer +# (Thanks to m4v for these) +# 2009-09-07, KenjiE20 : +# v1.6: -feature: colored buffer names +# -change: chanmon version sync +# 2009-09-05, KenjiE20 : +# v1.5: -fix: disable buffer highlight +# 2009-09-02, KenjiE20 : +# v.1.4.1 -change: Stop unsightly text block on '/help' +# 2009-08-10, KenjiE20 : +# v1.4: -feature: In-client help added +# -fix: Added missing help entries +# Fix remaining ugly vars +# 2009-07-09, KenjiE20 : +# v.1.3.3 -fix: highlight on the channel monitor when someone /me highlights +# 2009-07-04, KenjiE20 : +# v.1.3.2 -fix: use new away_info tag instead of ugly regexp for away detection +# -code: cleanup old raw callback arguement variables to nice neat named ones +# 2009-07-04, KenjiE20 : +# v.1.3.1 -feature(tte): Hide /away messages by default, change 'show_aways' to get them back +# 2009-07-01, KenjiE20 : +# v.1.3 -feature(tte): Mimic buffers.pl 'short_names' +# 2009-06-29, KenjiE20 : +# v.1.2.1 -fix: let the /monitor message respect the alignment setting +# 2009-06-19, KenjiE20 : +# v.1.2 -feature(tte): Customisable alignment +# Thanks to 'FreakGaurd' for the idea +# 2009-06-14, KenjiE20 : +# v.1.1.2 -fix: don't assume chanmon buffer needs creating +# fixes crashing with /upgrade +# 2009-06-13, KenjiE20 : +# v.1.1.1 -code: change from True/False to on/off for weechat consistency +# Settings WILL NEED to be changed manually from previous versions +# 2009-06-13, KenjiE20 : +# v1.1: -feature: Dynamic Channel Monitoring, +# don't display messages from active channel buffer +# defaults to Disabled +# Thanks to 'sjohnson' for the idea +# -fix: don't set config entries for non-channels +# -fix: don't assume all channels are # +# 2009-06-12, KenjiE20 : +# v1.0.1: -fix: glitch with tabs in IRC messages +# 2009-06-10, KenjiE20 : +# v1.0: Initial Public Release + +# Copyright (c) 2009 by KenjiE20 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +@bar_lines = (); +@bar_lines_time = (); +# Replicate info earlier for in-client help +$chanmonhelp = weechat::color("bold")."/chanmon [help] | [monitor [channel [server]]] | [dynmon] | [clean default|orphan|all]".weechat::color("-bold")." +Command wrapper for chanmon commands + +".weechat::color("bold")."/chmonitor [channel] [server]".weechat::color("-bold")." is used to toggle a channel monitoring on and off, this + can be used in the channel buffer for the channel you wish to toggle, or be given with arguments e.g. /monitor #weechat freenode + +".weechat::color("bold")."/dynmon".weechat::color("-bold")." is used to toggle 'Dynamic Channel Monitoring' on and off, this will automagically stop monitoring the current active buffer, without affecting regular settings (Default is off) + +".weechat::color("bold")."/chanclean".weechat::color("-bold")." default|orphan|all will clean the config section of default 'on' entries, channels you are no longer joined, or both + +".weechat::color("bold")."/set plugins.var.perl.chanmon.alignment".weechat::color("-bold")." + The config setting \"alignment\" can be changed to; + \"channel\", \"schannel\", \"nchannel\", \"channel,nick\", \"schannel,nick\", \"nchannel,nick\" + to change how the monitor appears + The 'channel' value will show: \"#weechat\" + The 'schannel' value will show: \"6\" + The 'nchannel' value will show: \"6:#weechat\" + +".weechat::color("bold")."/set plugins.var.perl.chanmon.short_names".weechat::color("-bold")." + Setting this to 'on' will trim the network name from chanmon, ala buffers.pl + +".weechat::color("bold")."/set plugins.var.perl.chanmon.merge_private".weechat::color("-bold")." + Setting this to 'on' will merge private messages to chanmon's display + +".weechat::color("bold")."/set plugins.var.perl.chanmon.color_buf".weechat::color("-bold")." + This turns colored buffer names on or off, you can also set a single fixed color by using a weechat color name. + This ".weechat::color("bold")."must".weechat::color("-bold")." be a valid color name, or weechat will likely do unexpected things :) + +".weechat::color("bold")."/set plugins.var.perl.chanmon.show_aways".weechat::color("-bold")." + Toggles showing the Weechat away messages + +".weechat::color("bold")."/set plugins.var.perl.chanmon.logging".weechat::color("-bold")." + Toggles logging status for chanmon buffer (default: off) + +".weechat::color("bold")."/set plugins.var.perl.chanmon.output".weechat::color("-bold")." + Changes where output method of chanmon; takes either \"bar\" or \"buffer\" (default; buffer) +".weechat::color("bold")."/set plugins.var.perl.chanmon.bar_lines".weechat::color("-bold")." + Changes the amount of lines the output bar will hold. + (Only appears once output has been set to bar, defaults to 10) + +".weechat::color("bold")."/set plugins.var.perl.chanmon.nick_prefix".weechat::color("-bold")." +".weechat::color("bold")."/set plugins.var.perl.chanmon.nick_suffix".weechat::color("-bold")." + Sets the prefix and suffix chars in the chanmon buffer + (Defaults to <> if nothing set, and blank if there is) + +".weechat::color("bold")."servername.#channel".weechat::color("-bold")." + servername is the internal name for the server (set when you use /server add) + #channel is the channel name, (where # is whatever channel type that channel happens to be) + +".weechat::color("bold")."Ideal set up:".weechat::color("-bold")." +Split the layout 70/30 (or there abouts) horizontally and load +Optionally, make the status and input lines only show on active windows + +".weechat::color("bold")."/window splith 70 --> open the chanmon buffer".weechat::color("-bold")." +".weechat::color("bold")."/set weechat.bar.status.conditions \"active\"".weechat::color("-bold")." +".weechat::color("bold")."/set weechat.bar.input.conditions \"active\"".weechat::color("-bold"); +# Print verbose help +sub print_help +{ + weechat::print("", "\t".weechat::color("bold")."Chanmon Help".weechat::color("-bold")."\n\n"); + weechat::print("", "\t".$chanmonhelp); + return weechat::WEECHAT_RC_OK; +} + +# Bar item build +sub chanmon_bar_build +{ + # Get max lines + $max_lines = weechat::config_get_plugin("bar_lines"); + $max_lines = $max_lines ? $max_lines : 10; + $str = ''; + $align_num = 0; + $count = 0; + # Keep lines within max + while ($#bar_lines > $max_lines) + { + shift(@bar_lines); + shift(@bar_lines_time); + } + # So long as we have some lines, build a string + if (@bar_lines) + { + # Build loop + foreach(@bar_lines) + { + # Find max align needed + $prefix_num = (index(weechat::string_remove_color($_, ""), " | ")); + $align_num = $prefix_num if ($prefix_num > $align_num); + } + foreach(@bar_lines) + { + # Get align for this line + $prefix_num = (index(weechat::string_remove_color($_, ""), " | ")); + + # Make string + $str = $str.$bar_lines_time[$count]." ".(" " x ($align_num - $prefix_num)).$_."\n"; + # Increment count for sync with time list + $count++; + } + } + return $str; +} + +# Make a new bar +sub chanmon_bar_open +{ + # Make the bar item + weechat::bar_item_new("chanmon", "chanmon_bar_build", ""); + + $chanmon_bar = weechat::bar_new ("chanmon", "off", 100, "root", "", "bottom", "vertical", "vertical", 0, 0, "default", "cyan", "default", "on", "chanmon"); + + return weechat::WEECHAT_RC_OK; +} +# Close bar +sub chanmon_bar_close +{ + # Find if bar exists + $chanmon_bar = weechat::bar_search("chanmon"); + # If is does, close it + if ($chanmon_bar ne "") + { + weechat::bar_remove($chanmon_bar); + } + + # Find if bar item exists + $chanmon_bar_item = weechat::bar_item_search("chanmon_bar"); + # If is does, close it + if ($chanmon_bar_item ne "") + { + weechat::bar_remove($chanmon_bar_item); + } + + @bar_lines = (); + return weechat::WEECHAT_RC_OK; +} + +# Make a new buffer +sub chanmon_buffer_open +{ + # Search for pre-existing buffer + $chanmon_buffer = weechat::buffer_search("perl", "chanmon"); + + # Make a new buffer + if ($chanmon_buffer eq "") + { + $chanmon_buffer = weechat::buffer_new("chanmon", "chanmon_buffer_input", "", "chanmon_buffer_close", ""); + } + + # Turn off notify, highlights + if ($chanmon_buffer ne "") + { + weechat::buffer_set($chanmon_buffer, "notify", "0"); + weechat::buffer_set($chanmon_buffer, "highlight_words", "-"); + weechat::buffer_set($chanmon_buffer, "title", "Channel Monitor"); + # Set no_log + if (weechat::config_get_plugin("logging") eq "off") + { + weechat::buffer_set($chanmon_buffer, "localvar_set_no_log", "1"); + } + } + return weechat::WEECHAT_RC_OK; +} +# Buffer input has no action +sub chanmon_buffer_input +{ + return weechat::WEECHAT_RC_OK; +} +# Close up +sub chanmon_buffer_close +{ + $chanmon_buffer = ""; + return weechat::WEECHAT_RC_OK; +} + +# Chanmon command wrapper +sub chanmon_command_cb +{ + $data = $_[0]; + $buffer = $_[1]; + $args = $_[2]; + my $cmd = ''; + my $arg = ''; + + if ($args ne "") + { + # Split argument up + @arg_array = split(/ /,$args); + # Take first as command + $cmd = shift(@arg_array); + # Rebuild string to pass to subs + if (@arg_array) + { + $arg = join(" ", @arg_array); + } + } + + # Help command + if ($cmd eq "" || $cmd eq "help") + { + print_help(); + } + # /monitor command + elsif ($cmd eq "monitor") + { + chanmon_toggle($data, $buffer, $arg); + } + # /dynmon command + elsif ($cmd eq "dynmon") + { + chanmon_dyn_toggle(); + } + # /chanclean command + elsif ($cmd eq "clean") + { + chanmon_config_clean($data, $buffer, $arg); + } + return weechat::WEECHAT_RC_OK; +} + +# Clean up config entries +sub chanmon_config_clean +{ + $data = $_[0]; + $buffer = $_[1]; + $args = $_[2]; + + # Don't do anything if bad option given + if ($args ne "default" && $args ne "orphan" && $args ne "all") + { + weechat::print("", "\tchanmon.pl: Unknown option"); + return weechat::WEECHAT_RC_OK; + } + + @chans = (); + # Load an infolist of chanmon options + $infolist = weechat::infolist_get("option", "", "*chanmon*"); + while (weechat::infolist_next($infolist)) + { + $name = weechat::infolist_string($infolist, "option_name"); + $name =~ s/perl\.chanmon\.(\w*)\.([#&\+!])(.*)/$1.$2$3/; + if ($name =~ /^(.*)\.([#&\+!])(.*)$/) + { + $action = 0; + # Clean up all 'on's + if ($args eq "default" || $args eq "all") + { + # If value in config is "on" + if (weechat::config_get_plugin($name) eq "on") + { + # Unset and if successful flag as changed + $rc = weechat::config_unset_plugin($name); + if ($rc eq weechat::WEECHAT_CONFIG_OPTION_UNSET_OK_REMOVED) + { + $action = 1; + } + } + } + # Clean non joined + if ($args eq "orphan" || $args eq "all") + { + # If we can't find the buffer for this entry + if (weechat::buffer_search("irc", $name) eq "") + { + # Unset and if successful flag as changed + $rc = weechat::config_unset_plugin($name); + if ($rc eq weechat::WEECHAT_CONFIG_OPTION_UNSET_OK_REMOVED) + { + $action = 1; + } + } + } + # Add changed entry names to list + push (@chans, $name) if ($action); + } + } + weechat::infolist_free($infolist); + # If channels were cleaned from config + if (@chans) + { + # If only one entry + if (@chans == 1) + { + $str = "\tchanmon.pl: Cleaned ".@chans." entry from the config:"; + } + else + { + $str = "\tchanmon.pl: Cleaned ".@chans." entries from the config:"; + } + # Build a list of channels + foreach(@chans) + { + $str = $str." ".$_; + } + # Print what happened + weechat::print("",$str); + } + # Config seemed to be clean + else + { + weechat::print("", "\tchanmon.pl: No entries removed"); + } + return weechat::WEECHAT_RC_OK; +} + +# Check config elements +sub chanmon_config_init +{ + # Alignment default + if (!(weechat::config_is_set_plugin ("alignment"))) + { + weechat::config_set_plugin("alignment", "channel"); + } + if (weechat::config_get_plugin("alignment") eq "") + { + weechat::config_set_plugin("alignment", "none"); + } + + # Dynmon default + if (!(weechat::config_is_set_plugin ("dynamic"))) + { + weechat::config_set_plugin("dynamic", "off"); + } + + # Short name default + if (!(weechat::config_is_set_plugin ("short_names"))) + { + weechat::config_set_plugin("short_names", "off"); + } + + # Coloured names default + if (!(weechat::config_is_set_plugin ("color_buf"))) + { + weechat::config_set_plugin("color_buf", "on"); + } + + # Away message default + if (!(weechat::config_is_set_plugin ("show_aways"))) + { + weechat::config_set_plugin("show_aways", "off"); + } + + # chanmon log default + if (!(weechat::config_is_set_plugin ("logging"))) + { + weechat::config_set_plugin("logging", "off"); + } + + # Output default + if (!(weechat::config_is_set_plugin ("output"))) + { + weechat::config_set_plugin("output", "buffer"); + } + + # Private message merging + if (!(weechat::config_is_set_plugin ("merge_private"))) + { + weechat::config_set_plugin("merge_private", "off"); + } + + # Check for exisiting prefix/suffix chars, and setup accordingly + $prefix = weechat::config_get("irc.look.nick_prefix"); + $prefix = weechat::config_string($prefix); + $suffix = weechat::config_get("irc.look.nick_suffix"); + $suffix = weechat::config_string($suffix); + + if (!(weechat::config_is_set_plugin("nick_prefix"))) + { + if ($prefix eq "" && $suffix eq "") + { + weechat::config_set_plugin("nick_prefix", "<"); + } + else + { + weechat::config_set_plugin("nick_prefix", ""); + } + } + + if (!(weechat::config_is_set_plugin("nick_suffix"))) + { + if ($prefix eq "" && $suffix eq "") + { + weechat::config_set_plugin("nick_suffix", ">"); + } + else + { + weechat::config_set_plugin("nick_suffix", ""); + } + } +} + +# Get config updates +sub chanmon_config_cb +{ + $point = $_[0]; + $name = $_[1]; + $value = $_[2]; + + $name =~ s/^plugins\.var\.perl\.chanmon\.//; + + # Set logging on buffer + if ($name eq "logging") + { + # Search for pre-existing buffer + $chanmon_buffer = weechat::buffer_search("perl", "chanmon"); + if ($value eq "off") + { + weechat::buffer_set($chanmon_buffer, "localvar_set_no_log", "1"); + } + else + { + weechat::buffer_set($chanmon_buffer, "localvar_del_no_log", ""); + } + } + # Output changer + elsif ($name eq "output") + { + if ($value eq "bar") + { + # Search for pre-existing buffer + $chanmon_buffer = weechat::buffer_search("perl", "chanmon"); + # Close if it exists + if ($chanmon_buffer ne "") + { + weechat::buffer_close($chanmon_buffer) + } + + # Output bar lines default + if (!(weechat::config_is_set_plugin ("bar_lines"))) + { + weechat::config_set_plugin("bar_lines", "10"); + } + # Make a bar if doesn't exist + chanmon_bar_open(); + } + elsif ($value eq "buffer") + { + # If a bar exists, close it + chanmon_bar_close(); + # Open buffer + chanmon_buffer_open(); + } + + } + return weechat::WEECHAT_RC_OK; +} + +# Toggle dynamic monitoring on/off +sub chanmon_dyn_toggle +{ + if (weechat::config_get_plugin("dynamic") eq "off") + { + weechat::config_set_plugin("dynamic", "on"); + chanmon_print("Dynamic Channel Monitoring Enabled"); + return weechat::WEECHAT_RC_OK; + } + elsif (weechat::config_get_plugin("dynamic") eq "on") + { + weechat::config_set_plugin("dynamic", "off"); + chanmon_print("Dynamic Channel Monitoring Disabled"); + return weechat::WEECHAT_RC_OK; + } +} + +# Set up weechat hooks / commands +sub chanmon_hook +{ + weechat::hook_print("", "", "", 0, "chanmon_new_message", ""); + weechat::hook_command("chmonitor", "Toggles monitoring for a channel", "[channel [server]]", " channel: What channel to toggle monitoring for\n server: Internal server name, if channel is on more than one server", "%(irc_channels) %(irc_servers)", "chanmon_toggle", ""); + weechat::hook_command("dynmon", "Toggles 'dynamic' monitoring (auto-disable monitoring for current channel)", "", "", "", "chanmon_dyn_toggle", ""); + weechat::hook_command("chanclean", "Chanmon config clean up", "default|orphan|all", " default: Cleans all config entries with the default \"on\" value\n orphan: Cleans all config entries for channels you aren't currently joined\n all: Does both defaults and orphan", "default|orphan|all", "chanmon_config_clean", ""); + + weechat::hook_command("chanmon", "Chanmon help", "[help] | [monitor [channel [server]]] | [dynmon] | [clean default|orphan|all]", " help: Print help for chanmon\n monitor: Toggles monitoring for a channel (/chmonitor)\n dynmon: Toggles 'dynamic' monitoring (auto-disable monitoring for current channel) (/dynmon)\n clean: Chanmon config clean up (/chanclean)", "help || monitor %(irc_channels) %(irc_servers) || dynmon || clean default|orphan|all", "chanmon_command_cb", ""); + + weechat::hook_config("plugins.var.perl.chanmon.*", "chanmon_config_cb", ""); +} + +# Main body, Callback for hook_print +sub chanmon_new_message +{ + my $net = ""; + my $chan = ""; + my $nick = ""; + my $outstr = ""; + my $window_displayed = ""; + my $dyncheck = "0"; + +# DEBUG point +# $string = "\t"."0: ".$_[0]." 1: ".$_[1]." 2: ".$_[2]." 3: ".$_[3]." 4: ".$_[4]." 5: ".$_[5]." 6: ".$_[6]." 7: ".$_[7]; +# weechat::print("", "\t".$string); + + $cb_datap = $_[0]; + $cb_bufferp = $_[1]; + $cb_date = $_[2]; + $cb_tags = $_[3]; + $cb_disp = $_[4]; + $cb_high = $_[5]; + $cb_prefix = $_[6]; + $cb_msg = $_[7]; + + # Only work on messages and topic notices + if ($cb_tags =~ /irc_privmsg/ || $cb_tags =~ /irc_topic/) + { + # Check buffer name is an IRC channel or private message when enabled + $bufname = weechat::buffer_get_string($cb_bufferp, 'name'); + if ($bufname =~ /(.*)\.([#&\+!])(.*)/ || (weechat::config_get_plugin("merge_private") eq "on" && $cb_tags =~ /notify_private/)) + { + # Are we running on this channel + if (weechat::config_get_plugin($bufname) ne "off" && $cb_disp eq "1") + { + # Are we running dynamically + if (weechat::config_get_plugin("dynamic") eq "on") + { + # Check if this buffer is shown in a window somewhere + $window_displayed = weechat::buffer_get_integer($cb_bufferp, "num_displayed"); + if ($window_displayed ne 0) + { + # Stop running + return weechat::WEECHAT_RC_OK; + } + } + + # Format nick + # Line isn't action or topic notify + if (!($cb_tags =~ /irc_action/) && !($cb_tags =~ /irc_topic/)) + { + # Highlight + if ($cb_high eq "1") + { + # Strip nick colour + $uncolnick = weechat::string_remove_color($cb_prefix, ""); + # Format nick + $nick = " ".weechat::config_get_plugin("nick_prefix").weechat::color("chat_highlight").$uncolnick.weechat::color("reset").weechat::config_get_plugin("nick_suffix"); + } + # Normal line + else + { + # Format nick + $nick = " ".weechat::config_get_plugin("nick_prefix").$cb_prefix.weechat::color("reset").weechat::config_get_plugin("nick_suffix"); + } + } + # Topic line + elsif ($cb_tags =~ /irc_topic/) + { + + $nick = " ".$cb_prefix.weechat::color("reset"); + } + # Action line + else + { + # Highlight + if ($cb_high eq "1") + { + $uncolnick = weechat::string_remove_color($cb_prefix, ""); + $nick = weechat::color("chat_highlight").$uncolnick.weechat::color("reset"); + } + # Normal line + else + { + $nick = $cb_prefix.weechat::color("reset"); + } + } + # Send to output + chanmon_print ($cb_msg, $cb_bufferp, $nick); + } + } + } + # Special outgoing ACTION & away_info catcher + elsif ($cb_tags eq "" || $cb_tags =~ /away_info/ && weechat::config_get_plugin("show_aways") eq "on" ) + { + # Check buffer name is an IRC channel or private message when enabled + $bufname = weechat::buffer_get_string($cb_bufferp, 'name'); + if ($bufname =~ /(.*)\.([#&\+!])(.*)/ || (weechat::config_get_plugin("merge_private") eq "on" && $cb_tags =~ /notify_private/)) + { + # Are we running dynamically + if (weechat::config_get_plugin("dynamic") eq "on") + { + # Check if this buffer is shown in a window somewhere + $window_displayed = weechat::buffer_get_integer($cb_bufferp, "num_displayed"); + if ($window_displayed eq 1) + { + # Stop running + return weechat::WEECHAT_RC_OK; + } + } + + $net = $1; + $mynick = weechat::info_get("irc_nick", $net); + if ($cb_msg =~ $mynick) + { + $action_colour = weechat::color(weechat::config_string(weechat::config_get("weechat.color.chat_prefix_action"))); + $action_prefix = weechat::config_string(weechat::config_get("weechat.look.prefix_action")); + $nick_self_colour = weechat::color(weechat::config_string(weechat::config_get("weechat.color.chat_nick_self"))); + $nick = $action_colour.$action_prefix.$nick_self_colour.$nick.weechat::color("reset"); + # Send to output + chanmon_print ($cb_msg, $cb_bufferp, $nick); + } + } + } + return weechat::WEECHAT_RC_OK; +} + +# Output formatter and printer takes (msg bufpointer nick) +sub chanmon_print +{ + $cb_msg = $_[0]; + my $cb_bufferp = $_[1] if ($_[1]); + my $nick = $_[2] if ($_[2]); + + #Normal channel message + if ($cb_bufferp && $nick) + { + # Format buffer name + $bufname = format_buffer_name($cb_bufferp); + + # If alignment is #channel | nick msg + if (weechat::config_get_plugin("alignment") eq "channel") + { + $nick =~ s/\s(.*)/$1/; + # Build string + $outstr = $bufname."\t".$nick." ".$cb_msg; + } + # or if it is channel number | nick msg + elsif (weechat::config_get_plugin("alignment") eq "schannel") + { + $nick =~ s/\s(.*)/$1/; + # Use channel number instead + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').weechat::color("reset"); + # Build string + $outstr = $bufname."\t".$nick." ".$cb_msg; + } + # or if it is number:#channel | nick msg + elsif (weechat::config_get_plugin("alignment") eq "nchannel") + { + $nick =~ s/\s(.*)/$1/; + # Place channel number in front of formatted name + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').":".weechat::color("reset").$bufname; + # Build string + $outstr = $bufname."\t".$nick." ".$cb_msg; + } + # or if it is #channel nick | msg + elsif (weechat::config_get_plugin("alignment") eq "channel,nick") + { + # Build string + $outstr = $bufname.":".$nick."\t".$cb_msg; + } + # or if it is channel number nick | msg + elsif (weechat::config_get_plugin("alignment") eq "schannel,nick") + { + # Use channel number instead + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').weechat::color("reset"); + # Build string + $outstr = $bufname.":".$nick."\t".$cb_msg; + } + # or if it is number:#channel nick | msg + elsif (weechat::config_get_plugin("alignment") eq "nchannel,nick") + { + # Place channel number in front of formatted name + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').":".weechat::color("reset").$bufname; + # Build string + $outstr = $bufname.":".$nick."\t".$cb_msg; + } + # or finally | #channel nick msg + else + { + # Build string + $outstr = "\t".$bufname.":".$nick." ".$cb_msg; + } + } + # chanmon channel toggle message + elsif ($cb_bufferp && !$nick) + { + # Format buffer name + $bufname = format_buffer_name($cb_bufferp); + + # If alignment is #channel * | * + if (weechat::config_get_plugin("alignment") =~ /channel/) + { + # If it's actually channel number * | * + if (weechat::config_get_plugin("alignment") =~ /schannel/) + { + # Use channel number instead + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').weechat::color("reset"); + } + # Or if it's actually number:#channel * | * + if (weechat::config_get_plugin("alignment") =~ /nchannel/) + { + # Place channel number in front of formatted name + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').":".weechat::color("reset").$bufname; + } + $outstr = $bufname."\t".$cb_msg; + } + # or if alignment is | * + else + { + $outstr = $bufname.": ".$cb_msg; + } + } + # chanmon dynmon + elsif (!$cb_bufferp && !$nick) + { + $outstr = "\t".$cb_msg; + } + + # Send string to buffer + if (weechat::config_get_plugin("output") eq "buffer") + { + # Search for and confirm buffer + $chanmon_buffer = weechat::buffer_search("perl", "chanmon"); + # Print + weechat::print($chanmon_buffer, $outstr); + } + elsif (weechat::config_get_plugin("output") eq "bar") + { + # Add time string + use POSIX qw(strftime); + $time = strftime(weechat::config_string(weechat::config_get("weechat.look.buffer_time_format")), localtime); + # Colourise + if ($time =~ /\$\{\w+\}/) # Coloured string + { + while ($time =~ /\$\{(\w+)\}/) + { + $color = weechat::color($1); + $time =~ s/\$\{\w+\}/$color/; + } + } + else # Default string + { + $colour = weechat::color(weechat::config_string(weechat::config_get("weechat.color.chat_time_delimiters"))); + $reset = weechat::color("reset"); + $time =~ s/(\d*)(.)(\d*)/$1$colour$2$reset$3/g; + } + # Push updates to bar lists + push (@bar_lines_time, $time); + + # Change tab char + $delim = weechat::color(weechat::config_string(weechat::config_get("weechat.color.chat_delimiters")))." | ".weechat::color("reset"); + $outstr =~ s/\t/$delim/; + + push (@bar_lines, $outstr); + # Trigger update + weechat::bar_item_update("chanmon"); + } +} + +# Start the output display +sub chanmon_start +{ + if (weechat::config_get_plugin("output") eq "buffer") + { + chanmon_buffer_open(); + } + elsif (weechat::config_get_plugin("output") eq "bar") + { + chanmon_bar_open(); + } +} + +# Takes two optional args (channel server), toggles monitoring on/off +sub chanmon_toggle +{ + $data = $_[0]; + $buffer = $_[1]; + $args = $_[2]; + + # Check if we've been told what channel to act on + if ($args ne "") + { + # Split argument up + @arg_array = split(/ /,$args); + # Check if a server was given + if ($arg_array[1]) + { + # Find matching + $bufp = weechat::buffer_search("irc", $arg_array[1].".".$arg_array[0]); + } + else + { + $found_chans = 0; + # Loop through defined servers + $infolist = weechat::infolist_get("buffer", "", ""); + while (weechat::infolist_next($infolist)) + { + # Only interesting in IRC buffers + if (weechat::infolist_string($infolist, "plugin_name") eq "irc") + { + # Find buffers that maych + $sname = weechat::infolist_string($infolist, "short_name"); + if ($sname eq $arg_array[0]) + { + $found_chans++; + $bufp = weechat::infolist_pointer($infolist, "pointer"); + } + } + } + weechat::infolist_free($infolist); + # If the infolist found more than one channel, halt as we need to know which one + if ($found_chans > 1) + { + weechat::print("", "Channel name is not unique, please define server"); + return weechat::WEECHAT_RC_OK; + } + } + # Something didn't return right + if ($bufp eq "") + { + weechat::print("", "Could not find buffer"); + return weechat::WEECHAT_RC_OK; + } + } + else + { + # Get pointer from where we are + $bufp = weechat::current_buffer(); + } + # Get buffer name + $bufname = weechat::buffer_get_string($bufp, 'name'); + # Test if buffer is an IRC channel + if ($bufname =~ /(.*)\.([#&\+!])(.*)/) + { + if (weechat::config_get_plugin($bufname) eq "off") + { + # If currently off, set on + weechat::config_set_plugin($bufname, "on"); + + # Send to output formatter + chanmon_print("Channel Monitoring Enabled", $bufp); + return weechat::WEECHAT_RC_OK; + } + elsif (weechat::config_get_plugin($bufname) eq "on" || weechat::config_get_plugin($bufname) eq "") + { + # If currently on, set off + weechat::config_set_plugin($bufname, "off"); + + # Send to output formatter + chanmon_print("Channel Monitoring Disabled", $bufp); + return weechat::WEECHAT_RC_OK; + } + } +} + +# Takes a buffer pointer and returns a formatted name +sub format_buffer_name +{ + $cb_bufferp = $_[0]; + $bufname = weechat::buffer_get_string($cb_bufferp, 'name'); + + # Set colour from buffer name + if (weechat::config_get_plugin("color_buf") eq "on") + { + # Determine what colour to use + $color = weechat::info_get("irc_nick_color", $bufname); + if (!$color) + { + $color = 0; + @char_array = split(//,$bufname); + foreach $char (@char_array) + { + $color += ord($char); + } + $color %= 10; + $color = sprintf "weechat.color.chat_nick_color%02d", $color+1; + $color = weechat::config_get($color); + $color = weechat::config_string($color); + $color = weechat::color($color); + } + + # Private message just show network + if (weechat::config_get_plugin("merge_private") eq "on" && weechat::buffer_get_string($cb_bufferp, "localvar_type") eq "private") + { + $bufname = weechat::buffer_get_string($cb_bufferp, "localvar_server"); + } + # Format name to short or 'nicename' + elsif (weechat::config_get_plugin("short_names") eq "on") + { + $bufname = weechat::buffer_get_string($cb_bufferp, 'short_name'); + } + else + { + $bufname =~ s/(.*)\.([#&\+!])(.*)/$1$2$3/; + } + + # Build a coloured string + $bufname = $color.$bufname.weechat::color("reset"); + } + # User set colour name + elsif (weechat::config_get_plugin("color_buf") ne "off") + { + # Private message just show network + if (weechat::config_get_plugin("merge_private") eq "on" && weechat::buffer_get_string($cb_bufferp, "localvar_type") eq "private") + { + $bufname = weechat::buffer_get_string($cb_bufferp, "localvar_server"); + } + # Format name to short or 'nicename' + elsif (weechat::config_get_plugin("short_names") eq "on") + { + $bufname = weechat::buffer_get_string($cb_bufferp, 'short_name'); + } + else + { + $bufname =~ s/(.*)\.([#&\+!])(.*)/$1$2$3/; + } + + $color = weechat::config_get_plugin("color_buf"); + $bufname = weechat::color($color).$bufname.weechat::color("reset"); + } + # Stick with default colour + else + { + # Private message just show network + if (weechat::config_get_plugin("merge_private") eq "on" && weechat::buffer_get_string($cb_bufferp, "localvar_type") eq "private") + { + $bufname = weechat::buffer_get_string($cb_bufferp, "localvar_server"); + } + # Format name to short or 'nicename' + elsif (weechat::config_get_plugin("short_names") eq "on") + { + $bufname = weechat::buffer_get_string($cb_bufferp, 'short_name'); + } + else + { + $bufname =~ s/(.*)\.([#&\+!])(.*)/$1$2$3/; + } + } + + return $bufname; +} + +# Check result of register, and attempt to behave in a sane manner +if (!weechat::register("chanmon", "KenjiE20", "2.3.1", "GPL3", "Channel Monitor", "", "")) +{ + # Double load + weechat::print ("", "\tChanmon is already loaded"); + return weechat::WEECHAT_RC_OK; +} +else +{ + # Start everything + chanmon_hook(); + chanmon_config_init(); + chanmon_start(); +} \ No newline at end of file diff --git a/weechat/perl/iset.pl b/weechat/perl/iset.pl new file mode 100644 index 0000000..4fb8124 --- /dev/null +++ b/weechat/perl/iset.pl @@ -0,0 +1,1196 @@ +# +# Copyright (C) 2008-2012 Sebastien Helleu +# Copyright (C) 2010-2012 Nils Görs +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# Set WeeChat and plugins options interactively. +# +# History: +# +# 2012-03-17, Sebastien Helleu : +# version 2.5: fix check of sections when creating config file +# 2012-03-09, Sebastien Helleu : +# version 2.4: fix reload of config file +# 2012-02-02, nils_2 : +# version 2.3: fixed: refresh problem with new search results and cursor was outside window. +# : add: new option "current_line" in title bar +# version 2.2: fixed: refresh error when toggling plugins description +# 2011-11-05, nils_2 : +# version 2.1: use own config file (iset.conf), fix own help color (used immediately) +# 2011-10-16, nils_2 : +# version 2.0: add support for left-mouse-button and more sensitive mouse gesture (for integer/color options) +# add help text for mouse support +# 2011-09-20, Sebastien Helleu : +# version 1.9: add mouse support, fix iset buffer, fix errors on first load under FreeBSD +# 2011-07-21, nils_2 : +# version 1.8: added: option "show_plugin_description" (alt+p) +# fixed: typos in /help iset (lower case for alt+'x' keys) +# 2011-05-29, nils_2 : +# version 1.7: added: version check for future needs +# added: new option (scroll_horiz) and usage of scroll_horiz function (weechat >= 0.3.6 required) +# fixed: help_bar did not pop up immediately using key-shortcut +# 2011-02-19, nils_2 : +# version 1.6: added: display of all possible values in help bar (show_help_extra_info) +# fixed: external user options never loaded when starting iset first time +# 2011-02-13, Sebastien Helleu : +# version 1.5: use new help format for command arguments +# 2011-02-03, nils_2 : +# version 1.4: fixed: restore value filter after /upgrade using buffer local variable. +# 2011-01-14, nils_2 : +# version 1.3: added function to search for values (option value_search_char). +# code optimization. +# 2010-12-26, Sebastien Helleu : +# version 1.2: improve speed of /upgrade when iset buffer is open, +# restore filter used after /upgrade using buffer local variable, +# use /iset filter argument if buffer is open. +# 2010-11-21, drubin : +# version 1.1.1: fix bugs with cursor position +# 2010-11-20, nils_2 : +# version 1.1: cursor position set to value +# 2010-08-03, Sebastien Helleu : +# version 1.0: move misplaced call to infolist_free() +# 2010-02-02, rettub : +# version 0.9: turn all the help stuff off if option 'show_help_bar' is 'off', +# new key binding - to toggle help_bar and help stuff on/off +# 2010-01-30, nils_2 : +# version 0.8: fix error when option does not exist +# 2010-01-24, Sebastien Helleu : +# version 0.7: display iset bar only on iset buffer +# 2010-01-22, nils_2 and drubin: +# version 0.6: add description in a bar, fix singular/plural bug in title bar, +# fix selected line when switching buffer +# 2009-06-21, Sebastien Helleu : +# version 0.5: fix bug with iset buffer after /upgrade +# 2009-05-02, Sebastien Helleu : +# version 0.4: sync with last API changes +# 2009-01-04, Sebastien Helleu : +# version 0.3: open iset buffer when /iset command is executed +# 2009-01-04, Sebastien Helleu : +# version 0.2: use null values for options, add colors, fix refresh bugs, +# use new keys to reset/unset options, sort options by name, +# display number of options in buffer's title +# 2008-11-05, Sebastien Helleu : +# version 0.1: first official version +# 2008-04-19, Sebastien Helleu : +# script creation + +use strict; + +my $PRGNAME = "iset"; +my $VERSION = "2.5"; +my $DESCR = "Interactive Set for configuration options"; +my $AUTHOR = "Sebastien Helleu "; +my $LICENSE = "GPL3"; +my $LANG = "perl"; +my $ISET_CONFIG_FILE_NAME = "iset"; + +my $iset_config_file; +my $iset_buffer = ""; +my $wee_version_number = 0; +my @iset_focus = (); +my @options_names = (); +my @options_types = (); +my @options_values = (); +my @options_is_null = (); +my $option_max_length = 0; +my $current_line = 0; +my $filter = "*"; +my $description = ""; +my $options_name_copy = ""; +my $iset_filter_title = ""; + +my %options_iset; + +my %mouse_keys = ("\@chat(perl.$PRGNAME):button1" => "hsignal:iset_mouse", + "\@chat(perl.$PRGNAME):button2*" => "hsignal:iset_mouse", + "\@chat(perl.$PRGNAME):wheelup" => "/repeat 5 /iset **up", + "\@chat(perl.$PRGNAME):wheeldown" => "/repeat 5 /iset **down"); + + +sub iset_title +{ + if ($iset_buffer ne "") + { + my $current_line_text = ""; + $current_line_text = ($current_line + 1) . "/" if (weechat::config_boolean($options_iset{"show_current_line"}) == 1); + $iset_filter_title = "Filter: " if ($iset_filter_title eq ""); + $filter = "*" if ($filter eq ""); + my $postfix = "s"; + my $option_txt = " option"; + my $opt_txt = $option_txt; + $opt_txt = $option_txt.$postfix if (@options_names > 1); + my $show_plugin_descr_txt = ""; + $show_plugin_descr_txt = " (plugins description hidden)" if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0); + weechat::buffer_set($iset_buffer, "title", + "Interactive set (iset.pl v$VERSION) | " + .$iset_filter_title.weechat::color("yellow").$filter.weechat::color("default")." | " + .$current_line_text.@options_names.$opt_txt . $show_plugin_descr_txt); + } +} + +sub iset_filter +{ + $filter = $_[0]; + $filter = "$1.*" if ($filter =~ /f (.*)/); + $filter = "*.$1.*" if ($filter =~ /s (.*)/); + if ((substr($filter, 0, 1) ne "*") && (substr($filter, -1, 1) ne "*")) + { + $filter = "*".$filter."*"; + } + if ($iset_buffer ne "") + { + weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); + } +} + +sub iset_buffer_input +{ + my ($data, $buffer, $string) = ($_[0], $_[1], $_[2]); + + my $string2 = substr($string, 0, 1); + if ($string2 eq weechat::config_string($options_iset{"value_search_char"})) + { + $filter = substr($string, 1); + iset_get_values($filter); + $iset_filter_title = "Filter (by value): "; + if ($iset_buffer ne "") + { + weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); + } + } + else + { + $iset_filter_title = ""; + iset_filter($string); + iset_get_options(); + } + weechat::buffer_clear($buffer); + iset_title($iset_filter_title); + $current_line = 0; + iset_refresh(); + return weechat::WEECHAT_RC_OK; +} + +sub iset_buffer_close +{ + $iset_buffer = ""; + + return weechat::WEECHAT_RC_OK; +} + +sub iset_init +{ + $current_line = 0; + $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); + if ($iset_buffer eq "") + { + $iset_buffer = weechat::buffer_new($PRGNAME, "iset_buffer_input", "", "iset_buffer_close", ""); + } + else + { + my $new_filter = weechat::buffer_get_string($iset_buffer, "localvar_iset_filter"); + $filter = $new_filter if ($new_filter ne ""); + } + if ($iset_buffer ne "") + { + weechat::buffer_set($iset_buffer, "type", "free"); + iset_title(); + weechat::buffer_set($iset_buffer, "key_bind_ctrl-L", "/iset **refresh"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-A", "/iset **up"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-B", "/iset **down"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-23~", "/iset **left"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-24~" , "/iset **right"); + weechat::buffer_set($iset_buffer, "key_bind_meta- ", "/iset **toggle"); + weechat::buffer_set($iset_buffer, "key_bind_meta-+", "/iset **incr"); + weechat::buffer_set($iset_buffer, "key_bind_meta--", "/iset **decr"); + weechat::buffer_set($iset_buffer, "key_bind_meta-imeta-r", "/iset **reset"); + weechat::buffer_set($iset_buffer, "key_bind_meta-imeta-u", "/iset **unset"); + weechat::buffer_set($iset_buffer, "key_bind_meta-ctrl-J", "/iset **set"); + weechat::buffer_set($iset_buffer, "key_bind_meta-ctrl-M", "/iset **set"); + weechat::buffer_set($iset_buffer, "key_bind_meta-meta2-1~", "/iset **scroll_top"); + weechat::buffer_set($iset_buffer, "key_bind_meta-meta2-4~", "/iset **scroll_bottom"); + weechat::buffer_set($iset_buffer, "key_bind_meta-v", "/iset **toggle_help"); + weechat::buffer_set($iset_buffer, "key_bind_meta-p", "/iset **toggle_show_plugin_desc"); + weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); + } +} + +sub iset_get_options +{ + @iset_focus = (); + + @options_names = (); + @options_types = (); + @options_values = (); + @options_is_null = (); + $option_max_length = 0; + my %options_internal = (); + my $i = 0; + my $key; + my $iset_struct; + my %iset_struct; + + my $infolist = weechat::infolist_get("option", "", $filter); + while (weechat::infolist_next($infolist)) + { + $key = sprintf("%08d", $i); + my $name = weechat::infolist_string($infolist, "full_name"); + next if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0 and index ($name, "plugins.desc.") != -1); + my $type = weechat::infolist_string($infolist, "type"); + my $value = weechat::infolist_string($infolist, "value"); + my $is_null = weechat::infolist_integer($infolist, "value_is_null"); + + $options_internal{$name}{"type"} = $type; + $options_internal{$name}{"value"} = $value; + $options_internal{$name}{"is_null"} = $is_null; + $option_max_length = length($name) if (length($name) > $option_max_length); + + $iset_struct{$key} = $options_internal{$name}; + push(@iset_focus, $iset_struct{$key}); + $i++; + } + weechat::infolist_free($infolist); + + foreach my $name (sort keys %options_internal) + { + push(@options_names, $name); + push(@options_types, $options_internal{$name}{"type"}); + push(@options_values, $options_internal{$name}{"value"}); + push(@options_is_null, $options_internal{$name}{"is_null"}); + } +} + +sub iset_get_values +{ + my $var_value = $_[0]; + @options_names = (); + @options_types = (); + @options_values = (); + @options_is_null = (); + $option_max_length = 0; + my %options_internal = (); + my $i = 0; + my $infolist = weechat::infolist_get("option", "", "*"); + $var_value =~ tr/[a-z][0-9].=-_!//cd; # kill meta chars + $var_value = lc($var_value); + while (weechat::infolist_next($infolist)) + { + my $name = weechat::infolist_string($infolist, "full_name"); + next if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0 and index ($name, "plugins.desc.") != -1); + my $type = weechat::infolist_string($infolist, "type"); + my $value = weechat::infolist_string($infolist, "value"); + my $is_null = weechat::infolist_integer($infolist, "value_is_null"); + if (lc($value) =~ m/$var_value/) + { + $options_internal{$name}{"type"} = $type; + $options_internal{$name}{"value"} = $value; + $options_internal{$name}{"is_null"} = $is_null; + $option_max_length = length($name) if (length($name) > $option_max_length); + } + $i++; + } + weechat::infolist_free($infolist); + foreach my $name (sort keys %options_internal) + { + push(@options_names, $name); + push(@options_types, $options_internal{$name}{"type"}); + push(@options_values, $options_internal{$name}{"value"}); + push(@options_is_null, $options_internal{$name}{"is_null"}); + } + weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $var_value); +} + +sub iset_refresh_line +{ + if ($iset_buffer ne "") + { + my $y = $_[0]; + if ($y <= $#options_names) + { + return if (! defined($options_types[$y])); + my $format = sprintf("%%s%%-%ds %%s %%-7s %%s %%s%%s%%s", $option_max_length); + my $around = ""; + $around = "\"" if ((!$options_is_null[$y]) && ($options_types[$y] eq "string")); + + my $color1 = weechat::color(weechat::config_color($options_iset{"color_option"})); + my $color2 = weechat::color(weechat::config_color($options_iset{"color_type"})); + my $color3 = ""; + if ($options_is_null[$y]) + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef"})); + } + else + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value"})); + } + if ($y == $current_line) + { + $color1 = weechat::color(weechat::config_color($options_iset{"color_option_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + $color2 = weechat::color(weechat::config_color($options_iset{"color_type_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + if ($options_is_null[$y]) + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + } + else + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + } + } + my $value = $options_values[$y]; + $value = "(undef)" if ($options_is_null[$y]); + my $strline = sprintf($format, + $color1, $options_names[$y], + $color2, $options_types[$y], + $color3, $around, $value, $around); + weechat::print_y($iset_buffer, $y, $strline); + } + } +} + +sub iset_refresh +{ + iset_title(); + if (($iset_buffer ne "") && ($#options_names >= 0)) + { + foreach my $y (0 .. $#options_names) + { + iset_refresh_line($y); + } + } + + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); +} + +sub iset_full_refresh +{ + $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); + if ($iset_buffer ne "") + { + weechat::buffer_clear($iset_buffer); + # search for "*" in $filter. + if ($filter =~ m/\*/) + { + iset_get_options(); + } + else + { + iset_get_values($filter); + $iset_filter_title = "Filter (by value): "; + } + if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 1) + { + iset_set_current_line($current_line); + }else + { + $current_line = $#options_names if ($current_line > $#options_names); + } + iset_refresh(); + weechat::command($iset_buffer, "/window refresh"); + } +} + +sub iset_set_current_line +{ + my $new_current_line = $_[0]; + my $old_current_line = $current_line; + $current_line = $new_current_line; + $current_line = $#options_names if ($current_line > $#options_names); + if ($old_current_line != $current_line) + { + iset_refresh_line($old_current_line); + iset_refresh_line($current_line); + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); + } +} + +sub iset_signal_window_scrolled_cb +{ + my ($data, $signal, $signal_data) = ($_[0], $_[1], $_[2]); + if ($iset_buffer ne "") + { + my $infolist = weechat::infolist_get("window", $signal_data, ""); + if (weechat::infolist_next($infolist)) + { + if (weechat::infolist_pointer($infolist, "buffer") eq $iset_buffer) + { + my $old_current_line = $current_line; + my $new_current_line = $current_line; + my $start_line_y = weechat::infolist_integer($infolist, "start_line_y"); + my $chat_height = weechat::infolist_integer($infolist, "chat_height"); + $new_current_line += $chat_height if ($new_current_line < $start_line_y); + $new_current_line -= $chat_height if ($new_current_line >= $start_line_y + $chat_height); + $new_current_line = $start_line_y if ($new_current_line < $start_line_y); + $new_current_line = $start_line_y + $chat_height - 1 if ($new_current_line >= $start_line_y + $chat_height); + iset_set_current_line($new_current_line); + } + } + weechat::infolist_free($infolist); + } + + return weechat::WEECHAT_RC_OK; +} + +sub iset_get_window_number +{ + if ($iset_buffer ne "") + { + my $window = weechat::window_search_with_buffer($iset_buffer); + return "-window ".weechat::window_get_integer ($window, "number")." " if ($window ne ""); + } + return ""; +} + +sub iset_check_line_outside_window +{ + if ($iset_buffer ne "") + { + undef my $infolist; + if ($wee_version_number >= 0x00030500) + { + my $window = weechat::window_search_with_buffer($iset_buffer); + $infolist = weechat::infolist_get("window", $window, "") if $window; + } + else + { + $infolist = weechat::infolist_get("window", "", "current"); + } + if ($infolist) + { + if (weechat::infolist_next($infolist)) + { + my $start_line_y = weechat::infolist_integer($infolist, "start_line_y"); + my $chat_height = weechat::infolist_integer($infolist, "chat_height"); + my $window_number = ""; + if ($wee_version_number >= 0x00030500) + { + $window_number = "-window ".weechat::infolist_integer($infolist, "number")." "; + } + if ($start_line_y > $current_line) + { + weechat::command($iset_buffer, "/window scroll ".$window_number."-".($start_line_y - $current_line)); + } + else + { + if ($start_line_y <= $current_line - $chat_height) + { + weechat::command($iset_buffer, "/window scroll ".$window_number."+".($current_line - $start_line_y - $chat_height + 1)); + } + } + } + weechat::infolist_free($infolist); + } + } +} + +sub iset_get_option_name_index +{ + my $option_name = $_[0]; + my $index = 0; + while ($index <= $#options_names) + { + return -1 if ($options_names[$index] gt $option_name); + return $index if ($options_names[$index] eq $option_name); + $index++; + } + return -1; +} + +sub iset_config_cb +{ + my ($data, $option_name, $value) = ($_[0], $_[1], $_[2]); + + if ($iset_buffer ne "") + { + return weechat::WEECHAT_RC_OK if (weechat::info_get("weechat_upgrading", "") eq "1"); + + my $index = iset_get_option_name_index($option_name); + if ($index >= 0) + { + # refresh info about changed option + my $infolist = weechat::infolist_get("option", "", $option_name); + if ($infolist) + { + weechat::infolist_next($infolist); + if (weechat::infolist_fields($infolist)) + { + $options_types[$index] = weechat::infolist_string($infolist, "type"); + $options_values[$index] = weechat::infolist_string($infolist, "value"); + $options_is_null[$index] = weechat::infolist_integer($infolist, "value_is_null"); + iset_refresh_line($index); + iset_title($iset_filter_title) if ($option_name eq "iset.look.show_current_line"); + } + else + { + iset_full_refresh(); + } + weechat::infolist_free($infolist); + } + } + else + { + iset_full_refresh() if ($option_name ne "weechat.bar.isetbar.hidden"); + } + } + + return weechat::WEECHAT_RC_OK; +} + +sub iset_set_option +{ + my $option = weechat::config_get($_[0]); + weechat::config_option_set($option, $_[1], 1) if ($option ne ""); +} + +sub iset_reset_option +{ + my $option = weechat::config_get($_[0]); + weechat::config_option_reset($option, 1) if ($option ne ""); +} + +sub iset_unset_option +{ + my $option = weechat::config_get($_[0]); + weechat::config_option_unset($option) if ($option ne ""); + weechat::buffer_clear($iset_buffer); + iset_refresh(); +} + + +sub iset_cmd_cb +{ + my ($data, $buffer, $args) = ($_[0], $_[1], $_[2]); + my $filter_set = 0; + if (($args ne "") && (substr($args, 0, 2) ne "**")) + { + if (substr($args, 0, 1) eq weechat::config_string($options_iset{"value_search_char"})) + { + my $var_value = substr($args, 1); # cut value_search_char + if ($iset_buffer ne "") + { + weechat::buffer_clear($iset_buffer); + weechat::command($iset_buffer, "/window refresh"); + } + iset_init(); + iset_get_values($var_value); + iset_refresh(); + weechat::buffer_set($iset_buffer, "display", "1"); + $iset_filter_title = "Filter (by value): "; + $filter = $var_value; + iset_title($iset_filter_title); + return weechat::WEECHAT_RC_OK; + } + else + { + iset_filter($args); + $filter_set = 1; + my $ptrbuf = weechat::buffer_search($LANG, $PRGNAME); + if ($ptrbuf eq "") + { + iset_init(); + iset_get_options(); + iset_full_refresh(); + weechat::buffer_set(weechat::buffer_search($LANG, $PRGNAME), "display", "1"); + return weechat::WEECHAT_RC_OK; + } + } + } + + if ($iset_buffer eq "") + { + iset_init(); + iset_get_options(); + iset_refresh(); + } + else + { + iset_full_refresh() if ($filter_set); + } + + if ($args eq "") + { + weechat::buffer_set($iset_buffer, "display", "1"); + } + else + { + if ($args eq "**refresh") + { + iset_full_refresh(); + } + if ($args eq "**up") + { + if ($current_line > 0) + { + $current_line--; + iset_refresh_line($current_line + 1); + iset_refresh_line($current_line); + iset_check_line_outside_window(); + } + } + if ($args eq "**down") + { + if ($current_line < $#options_names) + { + $current_line++; + iset_refresh_line($current_line - 1); + iset_refresh_line($current_line); + iset_check_line_outside_window(); + } + } + if ($args eq "**left" && $wee_version_number >= 0x00030600) + { + weechat::command($iset_buffer, "/window scroll_horiz ".iset_get_window_number()."-".weechat::config_integer($options_iset{"scroll_horiz"})."%"); + } + if ($args eq "**right" && $wee_version_number >= 0x00030600) + { + weechat::command($iset_buffer, "/window scroll_horiz ".iset_get_window_number().weechat::config_integer($options_iset{"scroll_horiz"})."%"); + } + if ($args eq "**scroll_top") + { + my $old_current_line = $current_line; + $current_line = 0; + iset_refresh_line ($old_current_line); + iset_refresh_line ($current_line); + weechat::command($iset_buffer, "/window scroll_top ".iset_get_window_number()); + } + if ($args eq "**scroll_bottom") + { + my $old_current_line = $current_line; + $current_line = $#options_names; + iset_refresh_line ($old_current_line); + iset_refresh_line ($current_line); + weechat::command($iset_buffer, "/window scroll_bottom ".iset_get_window_number()); + } + if ($args eq "**toggle") + { + if ($options_types[$current_line] eq "boolean") + { + iset_set_option($options_names[$current_line], "toggle"); + } + } + if ($args eq "**incr") + { + if (($options_types[$current_line] eq "integer") + || ($options_types[$current_line] eq "color")) + { + iset_set_option($options_names[$current_line], "++1"); + } + } + if ($args eq "**decr") + { + if (($options_types[$current_line] eq "integer") + || ($options_types[$current_line] eq "color")) + { + iset_set_option($options_names[$current_line], "--1"); + } + } + if ($args eq "**reset") + { + iset_reset_option($options_names[$current_line]); + } + if ($args eq "**unset") + { + iset_unset_option($options_names[$current_line]); + } + if ($args eq "**toggle_help") + { + if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1) + { + weechat::config_option_set($options_iset{"show_help_bar"},0,1); + iset_show_bar(0); + } + else + { + weechat::config_option_set($options_iset{"show_help_bar"},1,1); + iset_show_bar(1); + } + } + if ($args eq "**toggle_show_plugin_desc") + { + if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 1) + { + weechat::config_option_set($options_iset{"show_plugin_description"},0,1); + iset_full_refresh(); + iset_check_line_outside_window(); + } + else + { + weechat::config_option_set($options_iset{"show_plugin_description"},1,1); + iset_full_refresh(); + iset_check_line_outside_window(); + } + } + if ($args eq "**set") + { + my $quote = ""; + my $value = $options_values[$current_line]; + if ($options_is_null[$current_line]) + { + $value = "null"; + } + else + { + $quote = "\"" if ($options_types[$current_line] eq "string"); + } + weechat::buffer_set($iset_buffer, "input", "/set ".$options_names[$current_line]." ".$quote.$value.$quote); + weechat::command($iset_buffer, "/input move_beginning_of_line"); + weechat::command($iset_buffer, "/input move_next_word"); + weechat::command($iset_buffer, "/input move_next_word"); + weechat::command($iset_buffer, "/input move_next_char"); + weechat::command($iset_buffer, "/input move_next_char") if ($quote ne ""); + } + } + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); + return weechat::WEECHAT_RC_OK; +} + +sub iset_get_help +{ + my ($redraw) = ($_[0]); + + return '' if (weechat::config_boolean($options_iset{"show_help_bar"}) == 0); + + if (not defined $options_names[$current_line]) + { + return "No option selected. Set a new filter using command line (use '*' to see all options)"; + } + if ($options_name_copy eq $options_names[$current_line] and not defined $redraw) + { + return $description; + } + $options_name_copy = $options_names[$current_line]; + my $optionlist =""; + $optionlist = weechat::infolist_get("option", "", $options_names[$current_line]); + weechat::infolist_next($optionlist); + my $full_name = weechat::infolist_string($optionlist,"full_name"); + my $option_desc = ""; + my $option_default_value = ""; + my $option_range = ""; + my $possible_values = ""; + my $re = qq(\Q$full_name); + if (grep (/^$re$/,$options_names[$current_line])) + { + $option_desc = weechat::infolist_string($optionlist, "description_nls"); + $option_desc = weechat::infolist_string($optionlist, "description") if ($option_desc eq ""); + $option_desc = "No help found" if ($option_desc eq ""); + $option_default_value = weechat::infolist_string($optionlist, "default_value"); + $possible_values = weechat::infolist_string($optionlist, "string_values") if (weechat::infolist_string($optionlist, "string_values") ne ""); + if ((weechat::infolist_string($optionlist, "type") eq "integer") && ($possible_values eq "")) + { + $option_range = weechat::infolist_integer($optionlist, "min") + ." .. ".weechat::infolist_integer($optionlist, "max"); + } + } + weechat::infolist_free($optionlist); + iset_title(); + + $description = weechat::color(weechat::config_color($options_iset{"color_help_option_name"})).$options_names[$current_line] + .weechat::color("bar_fg").": " + .weechat::color(weechat::config_color($options_iset{"color_help_text"})).$option_desc; + + # show additional infos like default value and possible values + + if (weechat::config_boolean($options_iset{"show_help_extra_info"}) == 1) + { + $description .= + weechat::color("bar_delim")." [" + .weechat::color("bar_fg")."default: " + .weechat::color("bar_delim")."\"" + .weechat::color(weechat::config_color($options_iset{"color_help_default_value"})).$option_default_value + .weechat::color("bar_delim")."\""; + if ($option_range ne "") + { + $description .= weechat::color("bar_fg").", values: ".$option_range; + } + if ($possible_values ne "") + { + $possible_values =~ s/\|/", "/g; # replace '|' to '", "' + $description .= weechat::color("bar_fg").", values: ". "\"" . $possible_values . "\""; + + } + $description .= weechat::color("bar_delim")."]"; + } + return $description; +} + +sub iset_check_condition_isetbar_cb +{ + my ($data, $modifier, $modifier_data, $string) = ($_[0], $_[1], $_[2], $_[3]); + my $buffer = weechat::window_get_pointer($modifier_data, "buffer"); + if ($buffer ne "") + { + if ((weechat::buffer_get_string($buffer, "plugin") eq $LANG) + && (weechat::buffer_get_string($buffer, "name") eq $PRGNAME)) + { + return "1"; + } + } + return "0"; +} + +sub iset_show_bar +{ + my $show = $_[0]; + my $barhidden = weechat::config_get("weechat.bar.isetbar.hidden"); + if ($barhidden) + { + if ($show) + { + if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1) + { + if (weechat::config_boolean($barhidden)) + { + weechat::config_option_set($barhidden, 0, 1); + } + } + } + else + { + if (!weechat::config_boolean($barhidden)) + { + weechat::config_option_set($barhidden, 1, 1); + } + } + } +} + +sub iset_signal_buffer_switch_cb +{ + my $buffer_pointer = $_[2]; + my $show_bar = 0; + $show_bar = 1 if (weechat::buffer_get_integer($iset_buffer, "num_displayed") > 0); + iset_show_bar($show_bar); + iset_check_line_outside_window() if ($buffer_pointer eq $iset_buffer); + return weechat::WEECHAT_RC_OK; +} + +sub iset_item_cb +{ + return iset_get_help(); +} + +sub iset_upgrade_ended +{ + iset_full_refresh(); +} + +sub iset_end +{ + # when script is unloaded, we hide bar + iset_show_bar(0); +} + +# -------------------------------[ mouse support ]------------------------------------- + +sub hook_focus_iset_cb +{ + my %info = %{$_[1]}; + my $bar_item_line = int($info{"_bar_item_line"}); + undef my $hash; + if (($info{"_buffer_name"} eq $PRGNAME) && $info{"_buffer_plugin"} eq $LANG && ($bar_item_line >= 0) && ($bar_item_line <= $#iset_focus)) + { + $hash = $iset_focus[$bar_item_line]; + } + else + { + $hash = {}; + my $hash_focus = $iset_focus[0]; + foreach my $key (keys %$hash_focus) + { + $hash->{$key} = "?"; + } + } + return $hash; +} + +# _chat_line_y contains selected line +sub iset_hsignal_mouse_cb +{ + my ($data, $signal, %hash) = ($_[0], $_[1], %{$_[2]}); + + if ($hash{"_buffer_name"} eq $PRGNAME && ($hash{"_buffer_plugin"} eq $LANG)) + { + if ($hash{"_key"} eq "button1") + { + $current_line = $hash{"_chat_line_y"}; + iset_refresh_line($current_line); + iset_refresh(); + } + elsif ($hash{"_key"} eq "button2") + { + if ($options_types[$hash{"_chat_line_y"}] eq "boolean") + { + iset_set_option($options_names[$hash{"_chat_line_y"}], "toggle"); + $current_line = $hash{"_chat_line_y"}; + iset_refresh_line($current_line); + iset_refresh(); + } + elsif ($options_types[$hash{"_chat_line_y"}] eq "string") + { + $current_line = $hash{"_chat_line_y"}; + iset_refresh_line($current_line); + iset_refresh(); + weechat::command("", "/$PRGNAME **set"); + } + } + elsif ($hash{"_key"} eq "button2-gesture-left" or $hash{"_key"} eq "button2-gesture-left-long") + { + if ($options_types[$hash{"_chat_line_y"}] eq "integer" or ($options_types[$hash{"_chat_line_y"}] eq "color")) + { + $current_line = $hash{"_chat_line_y"}; + iset_refresh_line($current_line); + iset_refresh(); + my $distance = distance($hash{"_chat_line_x"},$hash{"_chat_line_x2"}); + weechat::command("", "/repeat $distance /$PRGNAME **decr"); + } + } + elsif ($hash{"_key"} eq "button2-gesture-right" or $hash{"_key"} eq "button2-gesture-right-long") + { + if ($options_types[$hash{"_chat_line_y"}] eq "integer" or ($options_types[$hash{"_chat_line_y"}] eq "color")) + { + $current_line = $hash{"_chat_line_y"}; + iset_refresh_line($current_line); + iset_refresh(); + my $distance = distance($hash{"_chat_line_x"},$hash{"_chat_line_x2"}); + weechat::command("", "/repeat $distance /$PRGNAME **incr"); + } + } + } +} +sub distance +{ + my ($x1,$x2) = ($_[0], $_[1]); + my $distance; + $distance = $x1 - $x2; + $distance = abs($distance); + if ($distance > 0) + { + use integer; + $distance = $distance / 3; + $distance = 1 if ($distance == 0); + } + elsif ($distance == 0) + { + $distance = 1; + } + return $distance; +} + +# -----------------------------------[ config ]--------------------------------------- + +sub iset_config_init +{ + $iset_config_file = weechat::config_new($ISET_CONFIG_FILE_NAME,"iset_config_reload_cb",""); + return if ($iset_config_file eq ""); + + # section "color" + my $section_color = weechat::config_new_section($iset_config_file,"color", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_color eq "") + { + weechat::config_free($iset_config_file); + return; + } + $options_iset{"color_option"} = weechat::config_new_option( + $iset_config_file, $section_color, + "option", "color", "Color for option name in iset buffer", "", 0, 0, + "default", "default", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_option_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "option_selected", "color", "Color for selected option name in iset buffer", "", 0, 0, + "white", "white", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_type"} = weechat::config_new_option( + $iset_config_file, $section_color, + "type", "color", "Color for option type (integer, boolean, string)", "", 0, 0, + "brown", "brown", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_type_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "type_selected", "color", "Color for selected option type (integer, boolean, string)", "", 0, 0, + "yellow", "yellow", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value", "color", "Color for option value", "", 0, 0, + "cyan", "cyan", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_selected", "color", "Color for selected option value", "", 0, 0, + "lightcyan", "lightcyan", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_undef"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_undef", "color", "Color for option value undef", "", 0, 0, + "green", "green", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_undef_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_undef_selected", "color", "Color for selected option value undef", "", 0, 0, + "lightgreen", "lightgreen", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_bg_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "bg_selected", "color", "Background color for current selected option", "", 0, 0, + "red", "red", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_help_option_name"} = weechat::config_new_option( + $iset_config_file, $section_color, + "help_option_name", "color", "Color for option name in help-bar", "", 0, 0, + "white", "white", 0, "", "", "bar_refresh", "", "", ""); + $options_iset{"color_help_text"} = weechat::config_new_option( + $iset_config_file, $section_color, + "help_text", "color", "Color for option description in help-bar", "", 0, 0, + "default", "default", 0, "", "", "bar_refresh", "", "", ""); + $options_iset{"color_help_default_value"} = weechat::config_new_option( + $iset_config_file, $section_color, + "help_default_value", "color", "Color for default option value in help-bar", "", 0, 0, + "green", "green", 0, "", "", "bar_refresh", "", "", ""); + + # section "help" + my $section_help = weechat::config_new_section($iset_config_file,"help", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_help eq "") + { + weechat::config_free($iset_config_file); + return; + } + $options_iset{"show_help_bar"} = weechat::config_new_option( + $iset_config_file, $section_help, + "show_help_bar", "boolean", "Show help bar", "", 0, 0, + "on", "on", 0, "", "", "toggle_help_cb", "", "", ""); + $options_iset{"show_help_extra_info"} = weechat::config_new_option( + $iset_config_file, $section_help, + "show_help_extra_info", "boolean", "Show additional information in help bar (default value, max./min. value) ", "", 0, 0, + "on", "on", 0, "", "", "", "", "", ""); + $options_iset{"show_plugin_description"} = weechat::config_new_option( + $iset_config_file, $section_help, + "show_plugin_description", "boolean", "Show plugin description in iset buffer", "", 0, 0, + "on", "on", 0, "", "", "full_refresh_cb", "", "", ""); + + # section "look" + my $section_look = weechat::config_new_section($iset_config_file, "look", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_look eq "") + { + weechat::config_free($iset_config_file); + return; + } + $options_iset{"value_search_char"} = weechat::config_new_option( + $iset_config_file, $section_look, + "value_search_char", "string", "Trigger char to tell iset to search for value instead of option (for example: =red)", "", 0, 0, + "=", "=", 0, "", "", "", "", "", ""); + $options_iset{"scroll_horiz"} = weechat::config_new_option( + $iset_config_file, $section_look, + "scroll_horiz", "integer", "scroll content of iset buffer n%", "", 1, 100, + "10", "10", 0, "", "", "", "", "", ""); + $options_iset{"show_current_line"} = weechat::config_new_option( + $iset_config_file, $section_look, + "show_current_line", "boolean", "show current line in title bar.", "", 0, 0, + "on", "on", 0, "", "", "", "", "", ""); +} + +sub iset_config_reload_cb +{ + my ($data,$config_file) = ($_[0], $_[1]); + return weechat::config_reload($config_file) +} + +sub iset_config_read +{ + return weechat::config_read($iset_config_file) if ($iset_config_file ne ""); +} + +sub iset_config_write +{ + return weechat::config_write($iset_config_file) if ($iset_config_file ne ""); +} + +sub full_refresh_cb +{ + iset_full_refresh(); + return weechat::WEECHAT_RC_OK; +} + +sub bar_refresh +{ + iset_get_help(1); + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); + return weechat::WEECHAT_RC_OK; +} + +sub toggle_help_cb +{ + my $value = weechat::config_boolean($options_iset{"show_help_bar"}); + iset_show_bar($value); + return weechat::WEECHAT_RC_OK; +} + +# -----------------------------------[ main ]----------------------------------------- + +weechat::register($PRGNAME, $AUTHOR, $VERSION, $LICENSE, + $DESCR, "iset_end", ""); + +$wee_version_number = weechat::info_get("version_number", "") || 0; + +iset_config_init(); +iset_config_read(); + +weechat::hook_command($PRGNAME, "Interactive set", "f || s
|| [=]", + "f file : show options for a file\n". + "s section : show options for a section\n". + "text : show options with 'text' in name\n". + weechat::config_string($options_iset{"value_search_char"})."text : show options with 'text' in value\n\n". + "Keys for iset buffer:\n". + "f11,f12 : move iset content left/right\n". + "up,down : move one option up/down\n". + "pgup,pdwn : move one page up/down\n". + "home,end : move to first/last option\n". + "ctrl+'L' : refresh options and screen\n". + "alt+space : toggle boolean on/off\n". + "alt+'+' : increase value (for integer or color)\n". + "alt+'-' : decrease value (for integer or color)\n". + "alt+'i',alt+'r': reset value of option\n". + "alt+'i',alt+'u': unset option\n". + "alt+enter : set new value for option (edit it with command line)\n". + "text,enter : set a new filter using command line (use '*' to see all options)\n". + "alt+'v' : toggle help bar on/off\n". + "alt+'p' : toggle option \"show_plugin_description\" on/off\n". + "\n". + "standard mouse actions:\n". + "wheel up / wheel down : move option up/down\n". + "left-mouse-button : select an option from list\n". + "right-mouse-button : toggle boolean (on/off) or set a new value for option (edit it with command line)\n". + "right-mouse-button + gesture left/right: increase/decrease value (for integer or color)\n". + "\n". + "Examples:\n". + " show options for file 'weechat'\n". + " /iset f weechat\n". + " show options for file 'irc'\n". + " /iset f irc\n". + " show options for section 'look'\n". + " /iset s look\n". + " show all options with text 'nicklist' in name\n". + " /iset nicklist\n". + " show all values which contain 'red'. '" . weechat::config_string($options_iset{"value_search_char"}) . "' is a trigger char.\n". + " /iset ". weechat::config_string($options_iset{"value_search_char"}) ."red\n", + "", "iset_cmd_cb", ""); +weechat::hook_signal("upgrade_ended", "iset_upgrade_ended", ""); +weechat::hook_signal("window_scrolled", "iset_signal_window_scrolled_cb", ""); +weechat::hook_signal("buffer_switch", "iset_signal_buffer_switch_cb",""); +weechat::bar_item_new("isetbar_help", "iset_item_cb", ""); +weechat::bar_new("isetbar", "on", "0", "window", "", "top", "horizontal", + "vertical", "3", "3", "default", "cyan", "default", "1", + "isetbar_help"); +weechat::hook_modifier("bar_condition_isetbar", "iset_check_condition_isetbar_cb", ""); +weechat::hook_config("*", "iset_config_cb", ""); +$iset_buffer = weechat::buffer_search($LANG, $PRGNAME); +iset_init() if ($iset_buffer ne ""); + +if ($wee_version_number >= 0x00030600) +{ + weechat::hook_focus("chat", "hook_focus_iset_cb", ""); + weechat::hook_hsignal($PRGNAME."_mouse", "iset_hsignal_mouse_cb", ""); + weechat::key_bind("mouse", \%mouse_keys); +} diff --git a/weechat/plugins.conf b/weechat/plugins.conf new file mode 100644 index 0000000..70d1c69 --- /dev/null +++ b/weechat/plugins.conf @@ -0,0 +1,63 @@ +# +# plugins.conf -- weechat v0.3.8 +# + +[var] +fifo.fifo = "on" +guile.check_license = "on" +lua.check_license = "on" +perl.beep.beep_command_dcc = "growlnotify -m 'Someone sent you DCC' IRC DCC" +perl.beep.beep_command_highlight = "growlnotify -m 'Someone mentioned your name on weechat' IRC Highlight" +perl.beep.beep_command_pv = "growlnotify -m 'Someone sent you a private message' IRC Private Message" +perl.beep.beep_command_timeout = "30000" +perl.beep.beep_dcc = "on" +perl.beep.beep_highlight = "on" +perl.beep.beep_highlight_blacklist = "off" +perl.beep.beep_highlight_whitelist = "off" +perl.beep.beep_pv = "on" +perl.beep.beep_pv_blacklist = "off" +perl.beep.beep_pv_whitelist = "off" +perl.beep.beep_trigger_highlight = "" +perl.beep.beep_trigger_pv = "" +perl.beep.bell_always = "" +perl.beep.blacklist_nicks = "" +perl.beep.whitelist_channels = "" +perl.beep.whitelist_nicks = "" +perl.chanmon.alignment = "nchannel" +perl.chanmon.bar_lines = "10" +perl.chanmon.color_buf = "on" +perl.chanmon.dynamic = "off" +perl.chanmon.logging = "off" +perl.chanmon.merge_private = "on" +perl.chanmon.nick_prefix = "<" +perl.chanmon.nick_suffix = ">" +perl.chanmon.output = "bar" +perl.chanmon.short_names = "on" +perl.chanmon.show_aways = "off" +perl.check_license = "on" +python.check_license = "on" +python.screen_away.away_suffix = "[away]" +python.screen_away.command_on_attach = "" +python.screen_away.command_on_detach = "" +python.screen_away.interval = "5" +python.screen_away.message = "Detached from tmux" +tcl.check_license = "on" + +[desc] +perl.beep.beep_command_dcc = "command for beep on dcc, special value "$bell" is allowed, as well as "$bell;command" (default: "$bell")" +perl.beep.beep_command_highlight = "command for beep on highlight, special value "$bell" is allowed, as well as "$bell;command" (default: "$bell")" +perl.beep.beep_command_pv = "command for beep on private message, special value "$bell" is allowed, as well as "$bell;command" (default: "$bell")" +perl.beep.beep_command_timeout = "timeout for command run (in milliseconds, 0 = never kill (not recommended)) (default: "30000")" +perl.beep.beep_dcc = "beep on dcc (default: "on")" +perl.beep.beep_highlight = "beep on highlight (default: "on")" +perl.beep.beep_highlight_blacklist = "turn blacklist for highlights on or off (default: "off")" +perl.beep.beep_highlight_whitelist = "turn whitelist for highlights on or off (default: "off")" +perl.beep.beep_pv = "beep on private message (default: "on")" +perl.beep.beep_pv_blacklist = "turn blacklist for private messages on or off (default: "off")" +perl.beep.beep_pv_whitelist = "turn whitelist for private messages on or off (default: "off")" +perl.beep.beep_trigger_highlight = "word that will trigger execution of beep_command_highlight (if empty, anything will trigger) (default: "")" +perl.beep.beep_trigger_pv = "word that will trigger execution of beep_command_pv (it empty, anything will trigger) (default: "")" +perl.beep.bell_always = "use $bell on private messages and/or highlights regardless of trigger and whitelist settings (example: "pv,highlight") (default: "")" +perl.beep.blacklist_nicks = "comma-separated list of "server.nick": if not empty, these nicks will not be able to trigger execution of commands. Cannot be used in conjuction with whitelist (example: "freenode.nick1,freenode.nick2") (default: "")" +perl.beep.whitelist_channels = "comma-separated list of "server.#channel": if not empty, only these channels will trigger execution of commands (example: "freenode.#weechat,freenode.#channel2") (default: "")" +perl.beep.whitelist_nicks = "comma-separated list of "server.nick": if not empty, only these nicks will trigger execution of commands (example: "freenode.nick1,freenode.nick2") (default: "")" diff --git a/weechat/python/autoload/screen_away.py b/weechat/python/autoload/screen_away.py new file mode 120000 index 0000000..e485b70 --- /dev/null +++ b/weechat/python/autoload/screen_away.py @@ -0,0 +1 @@ +../screen_away.py \ No newline at end of file diff --git a/weechat/python/autoload/upside_down.py b/weechat/python/autoload/upside_down.py new file mode 120000 index 0000000..fb007ad --- /dev/null +++ b/weechat/python/autoload/upside_down.py @@ -0,0 +1 @@ +../upside_down.py \ No newline at end of file diff --git a/weechat/python/autoload/weeget.py b/weechat/python/autoload/weeget.py new file mode 100644 index 0000000..8622ef6 --- /dev/null +++ b/weechat/python/autoload/weeget.py @@ -0,0 +1,980 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2009-2012 Sebastien Helleu +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +# +# WeeChat scripts manager. +# (this script requires WeeChat >= 0.3.0 and python >= 2.6) +# +# History: +# +# 2012-03-09, Sebastien Helleu : +# version 1.8: fix reload of config file +# 2012-02-27, Sebastien Helleu : +# version 1.7: add support of scheme scripts +# 2012-02-05, Sebastien Helleu : +# version 1.6: use URL transfer from API (for WeeChat >= 0.3.7) +# 2012-01-03, Sebastien Helleu : +# version 1.5: make script compatible with Python 3.x +# 2011-03-25, Sebastien Helleu : +# version 1.4: add completion with installed scripts for action "remove" +# 2011-03-10, Sebastien Helleu : +# version 1.3: add script extension in script name completion and a new +# completion with tags for actions "list" and "listinstalled" +# 2011-02-13, Sebastien Helleu : +# version 1.2: use new help format for command arguments +# 2010-11-08, Sebastien Helleu : +# version 1.1: get python 2.x binary for hook_process (fix problem +# when python 3.x is default python version, requires +# WeeChat >= 0.3.4) +# 2010-02-22, Blake Winton : +# version 1.0: add action "listinstalled" for command /weeget +# 2010-01-25, Sebastien Helleu : +# version 0.9: fix "running" status of scripts with /weeget check +# 2009-09-30, Sebastien Helleu : +# version 0.8: fix bugs and add missing info in "/weeget show", +# display warning if url for plugins.xml.gz is old site +# 2009-09-07, Sebastien Helleu : +# version 0.7: update weechat site with new URL +# 2009-05-02, Sebastien Helleu : +# version 0.6: sync with last API changes +# 2009-04-15, Sebastien Helleu : +# version 0.5: display missing module(s) when import failed +# 2009-04-11, Sebastien Helleu : +# version 0.4: use new completion for command arguments +# 2009-04-07, Sebastien Helleu : +# version 0.3: fix bug with install/upgrade when weeget is updated with +# other scripts: ensure that weeget is always the last +# installed script +# 2009-04-07, Sebastien Helleu : +# version 0.2: add author's mail in script description +# 2009-04-05, Sebastien Helleu : +# version 0.1: initial release +# + +SCRIPT_NAME = "weeget" +SCRIPT_AUTHOR = "Sebastien Helleu " +SCRIPT_VERSION = "1.8" +SCRIPT_LICENSE = "GPL3" +SCRIPT_DESC = "WeeChat scripts manager" + +SCRIPT_COMMAND = "weeget" + +import_ok = True + +try: + import weechat +except ImportError: + print("This script must be run under WeeChat.") + print("Get WeeChat now at: http://www.weechat.org/") + import_ok = False + +try: + import sys, os, stat, time, gzip, hashlib, xml.dom.minidom +except ImportError as message: + print("Missing package(s) for %s: %s" % (SCRIPT_NAME, message)) + import_ok = False + +CONFIG_FILE_NAME = "wg" + +SCRIPT_EXTENSION = { + "perl" : "pl", + "python": "py", + "ruby" : "rb", + "lua" : "lua", + "tcl" : "tcl", + "guile" : "scm", +} + +# timeout for download of plugins.xml.gz +TIMEOUT_UPDATE = 60 * 1000 + +# timeout for download of a script +TIMEOUT_SCRIPT = 60 * 1000 + +# config file and options +wg_config_file = "" +wg_config_option = {} + +# action (install, remove, ..) and arguments +wg_action = "" +wg_action_args = "" + +# loaded scripts +wg_loaded_scripts = {} + +# hook process and stdout +wg_hook_process = { "update": "", "script": "" } +wg_stdout = { "update": "", "script": "" } + +# scripts read from plugins.xml.gz +wg_scripts = {} + +# list of script to install, and script currently installing +wg_scripts_to_install = [] +wg_current_script_install = {} + +# =================================[ config ]================================= + +def wg_config_init(): + """ + Initialization of configuration file. + Sections: color, scripts. + """ + global wg_config_file, wg_config_option + wg_config_file = weechat.config_new(CONFIG_FILE_NAME, + "wg_config_reload_cb", "") + if wg_config_file == "": + return + + # section "color" + section_color = weechat.config_new_section( + wg_config_file, "color", 0, 0, "", "", "", "", "", "", "", "", "", "") + if section_color == "": + weechat.config_free(wg_config_file) + return + wg_config_option["color_script"] = weechat.config_new_option( + wg_config_file, section_color, + "script", "color", "Color for script names", "", 0, 0, + "cyan", "cyan", 0, "", "", "", "", "", "") + wg_config_option["color_installed"] = weechat.config_new_option( + wg_config_file, section_color, + "installed", "color", "Color for \"installed\" indicator", "", 0, 0, + "yellow", "yellow", 0, "", "", "", "", "", "") + wg_config_option["color_running"] = weechat.config_new_option( + wg_config_file, section_color, + "running", "color", "Color for \"running\" indicator", "", 0, 0, + "lightgreen", "lightgreen", 0, "", "", "", "", "", "") + wg_config_option["color_obsolete"] = weechat.config_new_option( + wg_config_file, section_color, + "obsolete", "color", "Color for \"obsolete\" indicator", "", 0, 0, + "lightmagenta", "lightmagenta", 0, "", "", "", "", "", "") + wg_config_option["color_unknown"] = weechat.config_new_option( + wg_config_file, section_color, + "unknown", "color", "Color for \"unknown status\" indicator", "", 0, 0, + "lightred", "lightred", 0, "", "", "", "", "", "") + wg_config_option["color_language"] = weechat.config_new_option( + wg_config_file, section_color, + "language", "color", "Color for language names", "", 0, 0, + "lightblue", "lightblue", 0, "", "", "", "", "", "") + + # section "scripts" + section_scripts = weechat.config_new_section( + wg_config_file, "scripts", 0, 0, "", "", "", "", "", "", "", "", "", "") + if section_scripts == "": + weechat.config_free(wg_config_file) + return + wg_config_option["scripts_url"] = weechat.config_new_option( + wg_config_file, section_scripts, + "url", "string", "URL for file with list of plugins", "", 0, 0, + "http://www.weechat.org/files/plugins.xml.gz", + "http://www.weechat.org/files/plugins.xml.gz", 0, "", "", "", "", "", "") + wg_config_option["scripts_dir"] = weechat.config_new_option( + wg_config_file, section_scripts, + "dir", "string", "Local cache directory for" + SCRIPT_NAME, "", 0, 0, + "%h/" + SCRIPT_NAME, "%h/" + SCRIPT_NAME, 0, "", "", "", "", "", "") + wg_config_option["scripts_cache_expire"] = weechat.config_new_option( + wg_config_file, section_scripts, + "cache_expire", "integer", "Local cache expiration time, in minutes " + "(-1 = never expires, 0 = always expires)", "", + -1, 60*24*365, "60", "60", 0, "", "", "", "", "", "") + +def wg_config_reload_cb(data, config_file): + """ Reload configuration file. """ + return weechat.config_reload(config_file) + +def wg_config_read(): + """ Read configuration file. """ + global wg_config_file + return weechat.config_read(wg_config_file) + +def wg_config_write(): + """ Write configuration file. """ + global wg_config_file + return weechat.config_write(wg_config_file) + +def wg_config_color(color): + """ Get a color from configuration. """ + global wg_config_option + option = wg_config_option.get("color_" + color, "") + if option == "": + return "" + return weechat.color(weechat.config_string(option)) + +def wg_config_get_dir(): + """ Return weeget directory, with expanded WeeChat home dir. """ + global wg_config_option + return weechat.config_string( + wg_config_option["scripts_dir"]).replace("%h", + weechat.info_get("weechat_dir", "")) + +def wg_config_create_dir(): + """ Create weeget directory. """ + dir = wg_config_get_dir() + if not os.path.isdir(dir): + os.makedirs(dir, mode=0o700) + +def wg_config_get_cache_filename(): + """ Get local cache filename, based on URL. """ + global wg_config_option + return wg_config_get_dir() + os.sep + \ + os.path.basename(weechat.config_string(wg_config_option["scripts_url"])) + +# =============================[ download file ]============================== + +def wg_download_file(url, filename, timeout, callback, callback_data): + """Download a file with an URL. Return hook_process created.""" + version = weechat.info_get("version_number", "") or 0 + if int(version) >= 0x00030700: + return weechat.hook_process_hashtable("url:%s" % url, + { "file_out": filename }, + timeout, + callback, callback_data) + else: + script = [ "import sys", + "try:", + " if sys.version_info >= (3,):", + " import urllib.request", + " response = urllib.request.urlopen('%s')" % url, + " else:", + " import urllib2", + " response = urllib2.urlopen(urllib2.Request('%s'))" % url, + " f = open('%s', 'wb')" % filename, + " f.write(response.read())", + " response.close()", + " f.close()", + "except Exception as e:", + " print('error:' + str(e))" ] + return weechat.hook_process("python -c \"%s\"" % "\n".join(script), + timeout, + callback, callback_data) + +# ================================[ scripts ]================================= + +def wg_search_script_by_name(name): + """ + Search a script in list by name. + Name can be short name ('weeget') or full name ('weeget.py'). + """ + global wg_scripts + for id, script in wg_scripts.items(): + if script["name"] == name or script["full_name"] == name: + return script + return None + +def wg_get_loaded_scripts(): + """ + Get python dictionary with loaded scripts. + Keys are filenames and values are path to script, for example: + 'weeget.py': '/home/xxx/.weechat/python/weeget.py' + """ + global wg_loaded_scripts + wg_loaded_scripts = {} + for language in SCRIPT_EXTENSION.keys(): + infolist = weechat.infolist_get(language + "_script", "", "") + while weechat.infolist_next(infolist): + filename = weechat.infolist_string(infolist, "filename") + if filename != "": + wg_loaded_scripts[os.path.basename(filename)] = filename + weechat.infolist_free(infolist) + +def wg_is_local_script_loaded(filename): + """ Check if a script filename (like 'python/weeget.py') is loaded. """ + global wg_loaded_scripts + filename2 = filename + if filename2.startswith("autoload/"): + filename2 = filename2[9:] + for name, path in wg_loaded_scripts.items(): + if path.endswith(filename) or path.endswith(filename2): + return True + return False + +def wg_get_local_script_status(script): + """ + Check if a script is installed. + 'script' is a dictionary retrieved from scripts xml list. + """ + global wg_loaded_scripts + status = { "installed": "", "obsolete": "", "running": "" } + local_dir = weechat.info_get("weechat_dir", "") + os.sep + script["language"] + local_name = local_dir + os.sep + "autoload" + os.sep + script["full_name"] + if not os.path.isfile(local_name): + local_name = local_dir + os.sep + script["full_name"] + if os.path.isfile(local_name): + status["installed"] = "1" + f = open(local_name, "rb") + md5 = hashlib.md5() + md5.update(f.read()) + f.close() + local_md5 = md5.hexdigest() + if local_md5 != script["md5sum"]: + status["obsolete"] = "1" + if script["full_name"] in wg_loaded_scripts.keys(): + status["running"] = "1" + return status + +def wg_get_local_scripts(): + """ + Get list of all local scripts (in languages and autoload dirs). + Return a dictionary with language as key and list of paths as value, + with autoloaded scripts at beginning of list, for example: + { 'perl': [ 'autoload/buffers.pl', + 'autoload/weetris.pl', + 'beep.pl', + 'launcher.pl' ], + 'python': [ 'autoload/weeget.py', + 'go.py', + 'vdm.py' ] + } + """ + files = {} + for language in SCRIPT_EXTENSION.keys(): + files[language] = [] + autoloaded_files = [] + rootdir = weechat.info_get("weechat_dir", "") + os.sep + language + for root, dirs, listfiles in os.walk(rootdir): + if root == rootdir: + files[language] = listfiles + elif root == rootdir + os.sep + "autoload": + autoloaded_files = listfiles + for file in autoloaded_files: + if file in files[language]: + files[language].remove(file) + files[language].insert(0, "autoload" + os.sep + file) + return files + +def wg_get_local_scripts_status(): + """ + Return list of all local scripts with status (unknown/obsolete/running). + For example: + [ 'perl/weetris.pl': { 'unknown': '', 'obsolete': '1', 'running': '' }, + 'python/weeget.py': { 'unknown': '', 'obsolete': '', 'running': '1' } + ] + """ + local_scripts_status = [] + local_scripts = wg_get_local_scripts() + if len(local_scripts) > 0: + for language, files in local_scripts.items(): + for file in files: + script_status = { "unknown": "", "obsolete": "", "running": "" } + name_with_ext = os.path.basename(file) + script = wg_search_script_by_name(os.path.basename(file)) + if script == None: + script_status["unknown"] = "1" + else: + status = wg_get_local_script_status(script) + if status["obsolete"]: + script_status["obsolete"] = "1" + if wg_is_local_script_loaded(file): + script_status["running"] = "1" + local_scripts_status.append((language + os.sep + file, + script_status)) + return local_scripts_status + +def wg_search_scripts(search): + """ Search word in scripts, return list of matching scripts. """ + global wg_scripts + if search == "": + return wg_scripts + scripts_matching = {} + for id, script in wg_scripts.items(): + if script["name"].lower().find(search) >= 0 \ + or script["language"].lower().find(search) >= 0 \ + or script["desc_en"].lower().find(search) >= 0 \ + or script["desc_fr"].lower().find(search) >= 0 \ + or script["tags"].lower().find(search) >= 0: + scripts_matching[id] = script + return scripts_matching + +def wg_list_scripts(search, installed=False): + """ + List all scripts (with optional search string). + If installed == True, then list only installed scripts. + For each script, display status (installed/running/new version available), + name of script, language and description. + For example: + ir buffers pl Sidebar with list of buffers. + i N go py Quick jump to buffers. + i weetris pl Tetris-like game. + """ + global wg_scripts + search = search.strip().lower() + scripts_matching = wg_search_scripts(search) + if len(scripts_matching) == 0: + weechat.prnt("", "%s: no script found" % SCRIPT_NAME) + else: + weechat.prnt("", "") + if search != "": + if installed: + weechat.prnt("", "Scripts installed matching \"%s\":" % search) + else: + weechat.prnt("", "Scripts for WeeChat %s matching \"%s\":" + % (weechat.info_get("version", ""), + search)) + else: + if installed: + weechat.prnt("", "Scripts installed:") + else: + weechat.prnt("", "Scripts for WeeChat %s:" + % weechat.info_get("version", "")) + sorted_scripts = sorted(scripts_matching.items(), + key=lambda s: s[1]["name"]) + length_max_name = 0 + for item in sorted_scripts: + length = len(item[1]["name"]) + if length > length_max_name: + length_max_name = length + str_format = "%%s%%s%%s%%s%%s%%s%%s %%s%%-%ds %%s%%-3s %%s%%s" \ + % length_max_name + for item in sorted_scripts: + script = item[1] + str_installed = " " + str_running = " " + str_obsolete = " " + status = wg_get_local_script_status(script) + if installed and not status["installed"]: + continue + if status["installed"]: + str_installed = "i" + if status["running"]: + str_running = "r" + if status["obsolete"]: + str_obsolete = "N" + weechat.prnt("", str_format + % (wg_config_color("installed"), + str_installed, + wg_config_color("running"), + str_running, + wg_config_color("obsolete"), + str_obsolete, + weechat.color("chat"), + wg_config_color("script"), + script["name"], + wg_config_color("language"), + SCRIPT_EXTENSION[script["language"]], + weechat.color("chat"), + script["desc_en"])) + +def wg_show_script(name): + """ + Show detailed info about a script (in repository). + For example: + Script: weeget.py, version 0.7, license: GPL3 + Author: Sebastien Helleu + Status: installed, running + Date: added: 2009-04-05, updated: 2009-09-07 + URL: http://www.weechat.org/files/scripts/weeget.py + MD5: 4b0458dd5cc5c9a09ba8078f89830869 + Desc: Scripts manager. + Tags: scripts + Requires: python 2.5 + Min: 0.3.0 + """ + if len(wg_scripts) == 0: + return + script = wg_search_script_by_name(name) + if script == None: + weechat.prnt("", "%s: script \"%s%s%s\" not found" + % (SCRIPT_NAME, + wg_config_color("script"), + name, + weechat.color("chat"))) + else: + weechat.prnt("", "") + weechat.prnt("", " Script: %s%s%s, version %s, license: %s" + % (wg_config_color("script"), + script["full_name"], + weechat.color("chat"), + script["version"], + script["license"])) + weechat.prnt("", " Author: %s <%s>" % (script["author"], script["mail"])) + status = wg_get_local_script_status(script) + str_status = "not installed" + if status["installed"]: + str_status = "installed" + if status["running"]: + str_status += ", running" + else: + str_status += ", not running" + if status["obsolete"]: + str_status += " (new version available)" + weechat.prnt("", " Status: %s" % str_status) + date_added = script.get("added", "")[:10] + str_updated = script.get("updated", "") + if str_updated != "": + date_updated = script["updated"][:10] + if date_updated == "0000-00-00" or date_updated == date_added: + str_updated = "" + if str_updated != "": + weechat.prnt("", " Date: added: %s, updated: %s" + % (date_added, date_updated)) + else: + weechat.prnt("", " Date: added: %s" % date_added) + weechat.prnt("", " URL: %s" % script.get("url", "")) + weechat.prnt("", " MD5: %s" % script.get("md5sum", "")) + weechat.prnt("", " Desc: %s" % script.get("desc_en", "")) + weechat.prnt("", " Tags: %s" % script.get("tags", "")) + str_requires = script.get("requirements", "") + if str_requires == "": + str_requires = "(nothing)" + weechat.prnt("", "Requires: %s" % str_requires) + vmin = script.get("min_weechat", "") + vmax = script.get("max_weechat", "") + if vmin != "": + weechat.prnt("", " Min: %s" % vmin) + if vmax != "": + weechat.prnt("", " Max: %s" % vmax) + +def wg_install_next_script(): + """ + Install first script in list wg_scripts_to_install and remove it from + list. + """ + global wg_scripts, wg_scripts_to_install, wg_current_script_install + global wg_hook_process + if len(wg_scripts) == 0: + return + # be sure weeget is ALWAYS last script to install/update + # otherwise we'll lose end of list when weeget is unloaded by WeeChat + if SCRIPT_NAME in wg_scripts_to_install: + wg_scripts_to_install.remove(SCRIPT_NAME) + wg_scripts_to_install.append(SCRIPT_NAME) + # loop until a script is installed, or end if list is empty + while len(wg_scripts_to_install) > 0: + name = wg_scripts_to_install.pop(0) + script = wg_search_script_by_name(name) + if script == None: + weechat.prnt("", "%s: script \"%s%s%s\" not found" + % (SCRIPT_NAME, + wg_config_color("script"), + name, + weechat.color("chat"))) + else: + status = wg_get_local_script_status(script) + if status["installed"] and not status["obsolete"]: + weechat.prnt("", + "%s: script \"%s%s%s\" is already " + "installed and up to date" + % (SCRIPT_NAME, + wg_config_color("script"), + script["full_name"], + weechat.color("chat"))) + else: + weechat.prnt("", "%s: downloading \"%s%s%s\"..." + % (SCRIPT_NAME, + wg_config_color("script"), + script["full_name"], + weechat.color("chat"))) + if wg_hook_process["script"] != "": + weechat.unhook(wg_hook_process["script"]) + wg_hook_process["script"] = "" + wg_current_script_install = script + filename = wg_config_get_dir() + os.sep + script["full_name"] + wg_hook_process["script"] = wg_download_file(script["url"], filename, TIMEOUT_SCRIPT, + "wg_process_script_cb", "") + # this function will be called again when script will be + # downloaded + return + +def wg_install_scripts(names): + """ Install scripts. """ + global wg_scripts_to_install + for name in names.split(" "): + wg_scripts_to_install.append(name) + wg_install_next_script() + +def wg_process_script_cb(data, command, rc, stdout, stderr): + """ Callback when reading a script from website. """ + global wg_hook_process, wg_stdout, wg_current_script_install, wg_loaded_scripts + if stdout != "": + wg_stdout["script"] += stdout + if stderr != "": + wg_stdout["script"] += stderr + if int(rc) >= 0: + if wg_stdout["script"].startswith("error:"): + weechat.prnt("", "%s%s: error downloading script (%s)" + % (weechat.prefix("error"), SCRIPT_NAME, + wg_stdout["update"][6:].strip())) + else: + # ask C plugin to install/load script + weechat.hook_signal_send(wg_current_script_install["language"] + "_script_install", + weechat.WEECHAT_HOOK_SIGNAL_STRING, + wg_config_get_dir() + os.sep + wg_current_script_install["full_name"]) + wg_hook_process["script"] = "" + wg_install_next_script() + return weechat.WEECHAT_RC_OK + +def wg_check_scripts(): + """ + Check status of local script(s). + For each script found, display status (unknown/running/new version available). + For example: + r python/autoload/vdm.py + ?r python/autoload/dummy.py + rN python/shell.py + perl/buffers.pl + """ + local_scripts_status = wg_get_local_scripts_status() + if len(local_scripts_status) == 0: + return + weechat.prnt("", "") + weechat.prnt("", "Local scripts:") + for file, status in local_scripts_status: + str_unknown = " " + str_running = " " + str_obsolete = " " + if status["unknown"]: + str_unknown = "?" + if status["running"]: + str_running = "r" + if status["obsolete"]: + str_obsolete = "N" + weechat.prnt("", "%s%s%s%s%s%s%s %s%s%s%s" + % (wg_config_color("unknown"), str_unknown, + wg_config_color("running"), str_running, + wg_config_color("obsolete"), str_obsolete, + weechat.color("chat"), + os.path.dirname(file), + os.sep, + wg_config_color("script"), + os.path.basename(file))) + +def wg_upgrade_scripts(): + """ Upgrade scripts. """ + global wg_scripts, wg_scripts_to_install + if len(wg_scripts) == 0: + return + scripts_to_upgrade = [] + for id, script in wg_scripts.items(): + status = wg_get_local_script_status(script) + if status["installed"] and status["obsolete"]: + scripts_to_upgrade.append(script["name"]) + if len(scripts_to_upgrade) == 0: + weechat.prnt("", "%s: all scripts are up to date" % SCRIPT_NAME) + else: + wg_scripts_to_install.extend(scripts_to_upgrade) + wg_install_next_script() + +def wg_remove_scripts(names): + """ Remove scripts. """ + if len(wg_scripts) == 0: + return + list_names = names.split(" ") + scripts_to_remove = {} + for language in SCRIPT_EXTENSION.keys(): + scripts_to_remove[language] = [] + for name in list_names: + script = wg_search_script_by_name(name) + if script == None: + weechat.prnt("", "%s: script \"%s%s%s\" not found" + % (SCRIPT_NAME, + wg_config_color("script"), + name, + weechat.color("chat"))) + else: + if script["full_name"] not in scripts_to_remove[script["language"]]: + scripts_to_remove[script["language"]].append(script["full_name"]) + for language in SCRIPT_EXTENSION.keys(): + if len(scripts_to_remove[language]) > 0: + # ask C plugin to remove script file(s) + weechat.hook_signal_send(language + "_script_remove", + weechat.WEECHAT_HOOK_SIGNAL_STRING, + ",".join(scripts_to_remove[language])) + +# ==================================[ xml ]=================================== + +def wg_execute_action(): + """ Execute action. """ + global wg_action, wg_action_args, wg_loaded_scripts + if wg_action != "": + wg_get_loaded_scripts() + if wg_action == "list": + wg_list_scripts(wg_action_args) + elif wg_action == "listinstalled": + wg_list_scripts(wg_action_args, installed=True) + elif wg_action == "show": + wg_show_script(wg_action_args) + elif wg_action == "install": + wg_install_scripts(wg_action_args) + elif wg_action == "check": + wg_check_scripts() + elif wg_action == "upgrade": + wg_upgrade_scripts() + elif wg_action == "remove": + wg_remove_scripts(wg_action_args) + else: + weechat.prnt("", "%s%s: unknown action \"%s\"" + % (weechat.prefix("error"), SCRIPT_NAME, wg_action)) + + # reset action + wg_action = "" + wg_action_args = "" + wg_loaded_scripts = {} + +def wg_check_version(script): + """ Check if a script is designed for current running WeeChat version.""" + version = weechat.info_get("version", "") + version = version.split("-", 1)[0] + vmin = script.get("min_weechat", "") + vmax = script.get("max_weechat", "") + if vmin != "" and version < vmin: + return False + if vmax != "" and version > vmax: + return False + return True + +def wg_parse_xml(): + """ + Parse XML scripts list and return dictionary with list, with key 'id'. + Example of item return in dictionary : + '119': { 'name' : 'weeget', + 'version' : '0.1', + 'url' : 'http://www.weechat.org/files/scripts/weeget.py', + 'language' : 'python', + 'license' : 'GPL3', + 'md5sum' : 'd500714fc19b0e10cc4e339e70739e4ad500714fc19b0e10cc4e339e70739e4a', + 'tags' : 'scripts', + 'desc_en' : 'Scripts manager.', + 'desc_fr' : 'Gestionnaire de scripts.', + 'requirements': 'python 2.5', + 'min_weechat' : '0.3.0', + 'max_weechat' : '', + 'author' : 'FlashCode', + 'mail' : 'flashcode [at] flashtux [dot] org', + 'added' : '2009-04-05 22:39:18', + 'updated' : '0000-00-00 00:00:00' } + """ + global wg_scripts, wg_action, wg_action_args + wg_scripts = {} + try: + f = gzip.open(wg_config_get_cache_filename(), "rb") + string = f.read() + f.close() + except: + weechat.prnt("", "%s%s: unable to read xml file" + % (weechat.prefix("error"), SCRIPT_NAME)) + else: + try: + dom = xml.dom.minidom.parseString(string) + except: + weechat.prnt("", + "%s%s: unable to parse xml list of scripts" + % (weechat.prefix("error"), SCRIPT_NAME)) + # discard action + wg_action = "" + wg_action_args = "" + else: + for scriptNode in dom.getElementsByTagName("plugin"): + id = scriptNode.getAttribute("id") + script = {} + for node in scriptNode.childNodes: + if node.nodeType == node.ELEMENT_NODE: + if node.firstChild != None: + nodename = node.nodeName + value = node.firstChild.data + if sys.version_info < (3,): + # python 2.x: convert unicode to str (in python 3.x, id and text are already strings) + nodename = nodename.encode("utf-8") + value = value.encode("utf-8") + script[nodename] = value + if script["language"] in SCRIPT_EXTENSION: + script["full_name"] = script["name"] + "." + SCRIPT_EXTENSION[script["language"]] + if wg_check_version(script): + wg_scripts[id] = script + wg_execute_action() + +def wg_process_update_cb(data, command, rc, stdout, stderr): + """ Callback when reading XML cache file from website. """ + global wg_hook_process, wg_stdout, wg_scripts + if stdout != "": + wg_stdout["update"] += stdout + if stderr != "": + wg_stdout["update"] += stderr + if int(rc) >= 0: + if wg_stdout["update"].startswith("error:"): + weechat.prnt("", "%s%s: error downloading scripts (%s)" + % (weechat.prefix("error"), SCRIPT_NAME, + wg_stdout["update"][6:].strip())) + else: + weechat.prnt("", "%s: scripts downloaded" % SCRIPT_NAME) + wg_parse_xml() + wg_hook_process["update"] = "" + return weechat.WEECHAT_RC_OK + +def wg_update_cache(): + """ Download list of scripts and update local cache. """ + global wg_config_option, wg_hook_process, wg_stdout + # get data from website, via hook_process + if wg_hook_process["update"] != "": + weechat.unhook(wg_hook_process["update"]) + wg_hook_process["update"] = "" + weechat.prnt("", "%s: downloading list of scripts..." % SCRIPT_NAME) + wg_stdout["update"] = "" + wg_config_create_dir() + url = weechat.config_string(wg_config_option["scripts_url"]) + filename = wg_config_get_cache_filename() + wg_hook_process["update"] = wg_download_file(url, filename, TIMEOUT_UPDATE, + "wg_process_update_cb", "") + +def wg_read_scripts(download_list=True): + """ Read scripts list (download list if needed and asked). """ + global wg_scripts + cache_file = wg_config_get_cache_filename() + if os.path.isfile(cache_file): + # check if local cache file is too old + cache_expire = weechat.config_integer(wg_config_option["scripts_cache_expire"]) * 60 + if cache_expire >= 0: + diff_time = time.time() - os.stat(cache_file)[stat.ST_MTIME] + if download_list and diff_time >= cache_expire: + os.unlink(cache_file) + wg_scripts.clear() + if len(wg_scripts) > 0: + wg_execute_action() + else: + if os.path.isfile(cache_file): + wg_parse_xml() + elif download_list: + wg_update_cache() + +# ================================[ command ]================================= + +def wg_cmd(data, buffer, args): + """ Callback for /weeget command. """ + global wg_action, wg_action_args + if args == "": + weechat.command("", "/help %s" % SCRIPT_COMMAND) + return weechat.WEECHAT_RC_OK + argv = args.strip().split(" ", 1) + if len(argv) == 0: + return weechat.WEECHAT_RC_OK + + wg_action = "" + wg_action_args = "" + + # check arguments + if len(argv) < 2: + if argv[0] == "show" or \ + argv[0] == "install" or \ + argv[0] == "remove": + weechat.prnt("", "%s: too few arguments for action \"%s\"" + % (SCRIPT_NAME, argv[0])) + return weechat.WEECHAT_RC_OK + + # execute asked action + if argv[0] == "update": + wg_update_cache() + else: + wg_action = argv[0] + wg_action_args = "" + if len(argv) > 1: + wg_action_args = argv[1] + wg_read_scripts() + + return weechat.WEECHAT_RC_OK + +def wg_completion_scripts_cb(data, completion_item, buffer, completion): + """ Complete with known script names, for command '/weeget'. """ + global wg_scripts + wg_read_scripts(download_list=False) + if len(wg_scripts) > 0: + for id, script in wg_scripts.items(): + weechat.hook_completion_list_add(completion, script["full_name"], + 0, weechat.WEECHAT_LIST_POS_SORT) + return weechat.WEECHAT_RC_OK + +def wg_completion_scripts_installed_cb(data, completion_item, buffer, completion): + """ Complete with names of scripts installed, for command '/weeget'. """ + global wg_scripts + wg_read_scripts(download_list=False) + if len(wg_scripts) > 0: + for id, script in wg_scripts.items(): + status = wg_get_local_script_status(script) + if status["installed"]: + weechat.hook_completion_list_add(completion, script["full_name"], + 0, weechat.WEECHAT_LIST_POS_SORT) + return weechat.WEECHAT_RC_OK + +def wg_completion_scripts_tags_cb(data, completion_item, buffer, completion): + """ Complete with known tags, for command '/weeget'. """ + global wg_scripts + wg_read_scripts(download_list=False) + if len(wg_scripts) > 0: + for id, script in wg_scripts.items(): + if script["tags"]: + for tag in script["tags"].split(","): + weechat.hook_completion_list_add(completion, tag, + 0, weechat.WEECHAT_LIST_POS_SORT) + return weechat.WEECHAT_RC_OK + +# ==================================[ main ]================================== + +if __name__ == "__main__" and import_ok: + if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, + SCRIPT_DESC, "wg_unload_script", ""): + wg_config_init() + wg_config_read() + if weechat.config_string(wg_config_option["scripts_url"]).find("weechat.flashtux.org") >= 0: + weechat.prnt("", "%sWarning: old site still used in URL for plugins.xml.gz, you should do: /unset wg.scripts.url" + % weechat.prefix("error")) + str_installed = wg_config_color("installed") + "i" + weechat.color("chat") + str_unknown = wg_config_color("unknown") + "?" + weechat.color("chat") + str_running = wg_config_color("running") + "r" + weechat.color("chat") + str_obsolete = wg_config_color("obsolete") + "N" + weechat.color("chat") + weechat.hook_command(SCRIPT_COMMAND, + "WeeChat scripts manager", + "list|listinstalled [|] || show + + diff --git a/vim/plugin/LargeFile.vim b/vim/plugin/LargeFile.vim new file mode 100644 index 0000000..9f6551e --- /dev/null +++ b/vim/plugin/LargeFile.vim @@ -0,0 +1,80 @@ +" LargeFile: Sets up an autocmd to make editing large files work with celerity +" Author: Charles E. Campbell, Jr. +" Date: Sep 23, 2008 +" Version: 4 +" GetLatestVimScripts: 1506 1 :AutoInstall: LargeFile.vim + +" --------------------------------------------------------------------- +" Load Once: {{{1 +if exists("g:loaded_LargeFile") || &cp + finish +endif +let g:loaded_LargeFile = "v4" +let s:keepcpo = &cpo +set cpo&vim + +" --------------------------------------------------------------------- +" Commands: {{{1 +com! Unlarge call s:Unlarge() +com! -bang Large call s:LargeFile(0,expand("%")) + +" --------------------------------------------------------------------- +" Options: {{{1 +if !exists("g:LargeFile") + let g:LargeFile= 20 " in megabytes +endif + +" --------------------------------------------------------------------- +" LargeFile Autocmd: {{{1 +" for large files: turns undo, syntax highlighting, undo off etc +" (based on vimtip#611) +augroup LargeFile + au! + au BufReadPre * call LargeFile(0,expand("")) + au BufReadPost * + \ if &ch < 2 && (getfsize(expand("")) >= g:LargeFile*1024*1024 || getfsize(expand("")) == -2) + \| echomsg "***note*** handling a large file" + \| endif +augroup END + +" --------------------------------------------------------------------- +" s:LargeFile: {{{2 +fun! s:LargeFile(force,fname) +" call Dfunc("LargeFile(force=".a:force." fname<".a:fname.">)") + if a:force || getfsize(a:fname) >= g:LargeFile*1024*1024 || getfsize(a:fname) <= -2 + syn clear + let b:eikeep = &ei + let b:ulkeep = &ul + let b:bhkeep = &bh + let b:fdmkeep= &fdm + let b:swfkeep= &swf + set ei=FileType + setlocal noswf bh=unload fdm=manual ul=-1 + let fname=escape(substitute(a:fname,'\','/','g'),' ') + exe "au LargeFile BufEnter ".fname." set ul=-1" + exe "au LargeFile BufLeave ".fname." let &ul=".b:ulkeep."|set ei=".b:eikeep + exe "au LargeFile BufUnload ".fname." au! LargeFile * ". fname + echomsg "***note*** handling a large file" + endif +" call Dret("s:LargeFile") +endfun + +" --------------------------------------------------------------------- +" s:Unlarge: this function will undo what the LargeFile autocmd does {{{2 +fun! s:Unlarge() +" call Dfunc("s:Unlarge()") + if exists("b:eikeep") |let &ei = b:eikeep |endif + if exists("b:ulkeep") |let &ul = b:ulkeep |endif + if exists("b:bhkeep") |let &bh = b:bhkeep |endif + if exists("b:fdmkeep")|let &fdm = b:fdmkeep|endif + if exists("b:swfkeep")|let &swf = b:swfkeep|endif + syn on + doau FileType +" call Dret("s:Unlarge") +endfun + +" --------------------------------------------------------------------- +" Restore: {{{1 +let &cpo= s:keepcpo +unlet s:keepcpo +" vim: ts=4 fdm=marker diff --git a/vimrc b/vimrc index d88bac3..5ce3d57 100755 --- a/vimrc +++ b/vimrc @@ -80,6 +80,7 @@ set backspace=indent,eol,start " load the plugin and indent settings for the detected filetype filetype plugin indent on +filetype plugin on " Opens an edit command with the path of the currently edited file filled in " Normal mode: e diff --git a/zshrc b/zshrc index 85e83ef..696cce6 100644 --- a/zshrc +++ b/zshrc @@ -17,7 +17,7 @@ export ZSH_THEME="ben-prose" # DISABLE_LS_COLORS="true" # Uncomment following line if you want to disable autosetting terminal title. -# DISABLE_AUTO_TITLE="true" +DISABLE_AUTO_TITLE="true" # Uncomment following line if you want disable red dots displayed while waiting for completion # DISABLE_COMPLETION_WAITING_DOTS="true" @@ -56,10 +56,12 @@ alias rspec="rspec --color" #Screeninator and RVM scripts [[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm +bindkey -v + # # End of the custom things from my bash profile. # There's probably a more "zsh-ish" way of doing these, but I have no time. # # Customize to your needs... -export PATH=/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin +export PATH=/usr/local/share/npm/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin -- cgit From 64bb1bce986ea027679febb5d6a91c64cc815368 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:36:57 -0600 Subject: Update the stuff --- ben-prose.zsh-theme | 11 +- vim/.backup/.htaccess.swp | Bin 0 -> 12288 bytes vim/ftplugin/javascript/jslint.vim | 307 ++ vim/ftplugin/javascript/jslint/jslint-core.js | 6392 +++++++++++++++++++++++++ vim/ftplugin/javascript/jslint/runjslint.js | 103 + vim/ftplugin/javascript/jslint/runjslint.wsf | 48 + vim/plugin/LargeFile.vim | 80 + vimrc | 1 + zshrc | 6 +- 9 files changed, 6944 insertions(+), 4 deletions(-) create mode 100644 vim/.backup/.htaccess.swp create mode 100755 vim/ftplugin/javascript/jslint.vim create mode 100644 vim/ftplugin/javascript/jslint/jslint-core.js create mode 100644 vim/ftplugin/javascript/jslint/runjslint.js create mode 100644 vim/ftplugin/javascript/jslint/runjslint.wsf create mode 100644 vim/plugin/LargeFile.vim diff --git a/ben-prose.zsh-theme b/ben-prose.zsh-theme index b6825ac..3573c24 100644 --- a/ben-prose.zsh-theme +++ b/ben-prose.zsh-theme @@ -18,6 +18,15 @@ function box_name { [ -f ~/.box-name ] && cat ~/.box-name || hostname -s } +function zle-line-init zle-keymap-select { + local return_status="%{$fg[red]%}%(?..✘)%{$reset_color%}" + RPS1="${${KEYMAP/vicmd/-- NORMAL --}/(main|viins)/-- INSERT --}${return_status}%{$reset_color%}" + RPS2=$RPS1 + zle reset-prompt +} +zle -N zle-line-init +zle -N zle-keymap-select + PROMPT=' %{$fg[red]%}%n%{$reset_color%} at %{$fg[yellow]%}$(box_name)%{$reset_color%} in %{$fg_bold[green]%}${PWD/#$HOME/~}%{$reset_color%}$(hg_prompt_info)$(git_prompt_info) %{$fg[black]%}$(rvm_info)%{$reset_color%} %(?,,%{${fg_bold[white]}%}[%?]%{$reset_color%} )$ ' @@ -28,5 +37,3 @@ ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[green]%}!" ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[green]%}?" ZSH_THEME_GIT_PROMPT_CLEAN="" -local return_status="%{$fg[red]%}%(?..✘)%{$reset_color%}" -RPROMPT='${return_status}%{$reset_color%}' diff --git a/vim/.backup/.htaccess.swp b/vim/.backup/.htaccess.swp new file mode 100644 index 0000000..5c0572a Binary files /dev/null and b/vim/.backup/.htaccess.swp differ diff --git a/vim/ftplugin/javascript/jslint.vim b/vim/ftplugin/javascript/jslint.vim new file mode 100755 index 0000000..2ce7605 --- /dev/null +++ b/vim/ftplugin/javascript/jslint.vim @@ -0,0 +1,307 @@ + +" Global Options +" +" Enable/Disable highlighting of errors in source. +" Default is Enable +" To disable the highlighting put the line +" let g:JSLintHighlightErrorLine = 0 +" in your .vimrc +" +if exists("b:did_jslint_plugin") + finish +else + let b:did_jslint_plugin = 1 +endif + +let s:install_dir = expand(':p:h') + +au BufLeave call s:JSLintClear() + +au BufEnter call s:JSLint() +au InsertLeave call s:JSLint() +"au InsertEnter call s:JSLint() +au BufWritePost call s:JSLint() + +" due to http://tech.groups.yahoo.com/group/vimdev/message/52115 +if(!has("win32") || v:version>702) + au CursorHold call s:JSLint() + au CursorHoldI call s:JSLint() + + au CursorHold call s:GetJSLintMessage() +endif + +au CursorMoved call s:GetJSLintMessage() + +if !exists("g:JSLintHighlightErrorLine") + let g:JSLintHighlightErrorLine = 1 +endif + +if !exists("*s:JSLintUpdate") + function s:JSLintUpdate() + silent call s:JSLint() + call s:GetJSLintMessage() + endfunction +endif + +if !exists(":JSLintUpdate") + command JSLintUpdate :call s:JSLintUpdate() +endif +if !exists(":JSLintToggle") + command JSLintToggle exec ":let b:jslint_disabled = exists('b:jslint_disabled') ? b:jslint_disabled ? 0 : 1 : 1" | + \ echo 'JSLint ' . ['enabled', 'disabled'][b:jslint_disabled] . '.' +endif + +noremap dd dd:JSLintUpdate +noremap dw dw:JSLintUpdate +noremap u u:JSLintUpdate +noremap :JSLintUpdate + +" Set up command and parameters +if has("win32") + let s:runjslint_ext = 'js' + if exists("%JS_CMD%") + let s:cmd = "$JS_CMD" + elseif executable('node') + let s:cmd = "node" + else + let s:cmd = 'cscript /NoLogo ' + let s:runjslint_ext = 'wsf' + endif +else + let s:runjslint_ext = 'js' + if exists("$JS_CMD") + let s:cmd = "$JS_CMD" + elseif executable('node') + let s:cmd = 'node' + elseif executable('nodejs') + let s:cmd = 'nodejs' + elseif executable('/System/Library/Frameworks/JavaScriptCore.framework/Resources/jsc') + let s:cmd = '/System/Library/Frameworks/JavaScriptCore.framework/Resources/jsc' + elseif executable('js') + let s:cmd = 'js' + else + echoerr('No JS interpreter found. Checked for jsc, js (spidermonkey), and node') + endif +endif +let s:plugin_path = s:install_dir . "/jslint/" +if has('win32') + let s:plugin_path = substitute(s:plugin_path, '/', '\', 'g') +endif +if has('win32') + let s:cmd = 'cmd.exe /C "cd /d "' . s:plugin_path . '" && ' . s:cmd . ' "' . s:plugin_path . 'runjslint.' . s:runjslint_ext . '""' +else + let s:cmd = 'cd "' . s:plugin_path . '" && ' . s:cmd . ' "' . s:plugin_path . 'runjslint.' . s:runjslint_ext . '"' +endif + +let s:jslintrc_file = expand('~/.jslintrc') +if filereadable(s:jslintrc_file) + let s:jslintrc = readfile(s:jslintrc_file) +else + let s:jslintrc = [] +end + +" load .jslintrc file from the current (pwd) directory if exists +let s:localrc_file = fnamemodify(".", ":p") . '/.jslintrc' +if filereadable(s:localrc_file) + let s:localrc = readfile(s:localrc_file) + let s:jslintrc = s:jslintrc + s:localrc +endif +" load .jslintrc file from the directory where the file is if exists +let s:file_dir_file = expand('%:p:h') . '/.jslintrc' +if filereadable(s:file_dir_file) + let s:filedir_rc = readfile(s:file_dir_file) + let s:jslintrc = s:jslintrc + s:filedir_rc +endif + +" WideMsg() prints [long] message up to (&columns-1) length +" guaranteed without "Press Enter" prompt. +if !exists("*s:WideMsg") + function s:WideMsg(msg) + let x=&ruler | let y=&showcmd + set noruler noshowcmd + redraw + echo a:msg + let &ruler=x | let &showcmd=y + endfun +endif + + +function! s:JSLintClear() + " Delete previous matches + let s:matches = getmatches() + for s:matchId in s:matches + if s:matchId['group'] == 'JSLintError' + call matchdelete(s:matchId['id']) + endif + endfor + let b:matched = [] + let b:matchedlines = {} + let b:cleared = 1 +endfunction + +function! s:JSLint() + if exists("b:jslint_disabled") && b:jslint_disabled == 1 + return + endif + + highlight link JSLintError SpellBad + + if exists("b:cleared") + if b:cleared == 0 + call s:JSLintClear() + endif + let b:cleared = 1 + endif + + let b:matched = [] + let b:matchedlines = {} + + " Detect range + if a:firstline == a:lastline + " Skip a possible shebang line, e.g. for node.js script. + if getline(1)[0:1] == "#!" + let b:firstline = 2 + else + let b:firstline = 1 + endif + let b:lastline = '$' + else + let b:firstline = a:firstline + let b:lastline = a:lastline + endif + + let b:qf_list = [] + let b:qf_window_count = -1 + + let lines = join(s:jslintrc + getline(b:firstline, b:lastline), "\n") + if len(lines) == 0 + return + endif + if has('win32') || has('win64') + let b:jslint_output = system(s:cmd, lines . "\n") + else + let old_shell = &shell + let &shell = '/bin/bash' + let b:jslint_output = system(s:cmd, lines . "\n") + let &shell = old_shell + endif + if v:shell_error + echoerr b:jslint_output + echoerr 'could not invoke JSLint!' + let b:jslint_disabled = 1 + end + + for error in split(b:jslint_output, "\n") + " Match {line}:{char}:{message} + let b:parts = matchlist(error, '\v(\d+):(\d+):([A-Z]+):(.*)') + if !empty(b:parts) + let l:line = b:parts[1] + (b:firstline - 1 - len(s:jslintrc)) " Get line relative to selection + let l:errorMessage = b:parts[4] + + if l:line < 1 + echoerr 'error in jslintrc, line ' . b:parts[1] . ', character ' . b:parts[2] . ': ' . l:errorMessage + else + " Store the error for an error under the cursor + let s:matchDict = {} + let s:matchDict['lineNum'] = l:line + let s:matchDict['message'] = l:errorMessage + let b:matchedlines[l:line] = s:matchDict + if b:parts[3] == 'ERROR' + let l:errorType = 'E' + else + let l:errorType = 'W' + endif + if g:JSLintHighlightErrorLine == 1 + let s:mID = matchadd('JSLintError', '\v%' . l:line . 'l\S.*(\S|$)') + endif + " Add line to match list + call add(b:matched, s:matchDict) + + " Store the error for the quickfix window + let l:qf_item = {} + let l:qf_item.bufnr = bufnr('%') + let l:qf_item.filename = expand('%') + let l:qf_item.lnum = l:line + let l:qf_item.text = l:errorMessage + let l:qf_item.type = l:errorType + + " Add line to quickfix list + call add(b:qf_list, l:qf_item) + endif + endif + endfor + + if exists("s:jslint_qf") + " if jslint quickfix window is already created, reuse it + call s:ActivateJSLintQuickFixWindow() + call setqflist(b:qf_list, 'r') + else + " one jslint quickfix window for all buffers + call setqflist(b:qf_list, '') + let s:jslint_qf = s:GetQuickFixStackCount() + endif + let b:cleared = 0 +endfunction + +let b:showing_message = 0 + +if !exists("*s:GetJSLintMessage") + function s:GetJSLintMessage() + let s:cursorPos = getpos(".") + + " Bail if RunJSLint hasn't been called yet + if !exists('b:matchedlines') + return + endif + + if has_key(b:matchedlines, s:cursorPos[1]) + let s:jslintMatch = get(b:matchedlines, s:cursorPos[1]) + call s:WideMsg(s:jslintMatch['message']) + let b:showing_message = 1 + return + endif + + if b:showing_message == 1 + echo + let b:showing_message = 0 + endif + endfunction +endif + +if !exists("*s:GetQuickFixStackCount") + function s:GetQuickFixStackCount() + let l:stack_count = 0 + try + silent colder 9 + catch /E380:/ + endtry + + try + for i in range(9) + silent cnewer + let l:stack_count = l:stack_count + 1 + endfor + catch /E381:/ + return l:stack_count + endtry + endfunction +endif + +if !exists("*s:ActivateJSLintQuickFixWindow") + function s:ActivateJSLintQuickFixWindow() + try + silent colder 9 " go to the bottom of quickfix stack + catch /E380:/ + catch /E788:/ + endtry + + if s:jslint_qf > 0 + try + exe "silent cnewer " . s:jslint_qf + catch /E381:/ + echoerr "Could not activate JSLint Quickfix Window." + endtry + endif + endfunction +endif + diff --git a/vim/ftplugin/javascript/jslint/jslint-core.js b/vim/ftplugin/javascript/jslint/jslint-core.js new file mode 100644 index 0000000..c8e5c41 --- /dev/null +++ b/vim/ftplugin/javascript/jslint/jslint-core.js @@ -0,0 +1,6392 @@ +// jslint.js +// 2012-02-23 + +// Copyright (c) 2002 Douglas Crockford (www.JSLint.com) + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// The Software shall be used for Good, not Evil. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +// WARNING: JSLint will hurt your feelings. + +// JSLINT is a global function. It takes two parameters. + +// var myResult = JSLINT(source, option); + +// The first parameter is either a string or an array of strings. If it is a +// string, it will be split on '\n' or '\r'. If it is an array of strings, it +// is assumed that each string represents one line. The source can be a +// JavaScript text, or HTML text, or a JSON text, or a CSS text. + +// The second parameter is an optional object of options that control the +// operation of JSLINT. Most of the options are booleans: They are all +// optional and have a default value of false. One of the options, predef, +// can be an array of names, which will be used to declare global variables, +// or an object whose keys are used as global names, with a boolean value +// that determines if they are assignable. + +// If it checks out, JSLINT returns true. Otherwise, it returns false. + +// If false, you can inspect JSLINT.errors to find out the problems. +// JSLINT.errors is an array of objects containing these properties: + +// { +// line : The line (relative to 0) at which the lint was found +// character : The character (relative to 0) at which the lint was found +// reason : The problem +// evidence : The text line in which the problem occurred +// raw : The raw message before the details were inserted +// a : The first detail +// b : The second detail +// c : The third detail +// d : The fourth detail +// } + +// If a stopping error was found, a null will be the last element of the +// JSLINT.errors array. A stopping error means that JSLint was not confident +// enough to continue. It does not necessarily mean that the error was +// especially heinous. + +// You can request a Function Report, which shows all of the functions +// and the parameters and vars that they use. This can be used to find +// implied global variables and other problems. The report is in HTML and +// can be inserted in an HTML . + +// var myReport = JSLINT.report(errors_only); + +// If errors_only is true, then the report will be limited to only errors. + +// You can request a data structure that contains JSLint's results. + +// var myData = JSLINT.data(); + +// It returns a structure with this form: + +// { +// errors: [ +// { +// line: NUMBER, +// character: NUMBER, +// reason: STRING, +// evidence: STRING +// } +// ], +// functions: [ +// { +// name: STRING, +// line: NUMBER, +// last: NUMBER, +// params: [ +// { +// string: STRING +// } +// ], +// closure: [ +// STRING +// ], +// var: [ +// STRING +// ], +// exception: [ +// STRING +// ], +// outer: [ +// STRING +// ], +// unused: [ +// STRING +// ], +// undef: [ +// STRING +// ], +// global: [ +// STRING +// ], +// label: [ +// STRING +// ] +// } +// ], +// globals: [ +// STRING +// ], +// member: { +// STRING: NUMBER +// }, +// urls: [ +// STRING +// ], +// json: BOOLEAN +// } + +// Empty arrays will not be included. + +// You can obtain the parse tree that JSLint constructed while parsing. The +// latest tree is kept in JSLINT.tree. A nice stringication can be produced +// with + +// JSON.stringify(JSLINT.tree, [ +// 'string', 'arity', 'name', 'first', +// 'second', 'third', 'block', 'else' +// ], 4)); + +// JSLint provides three directives. They look like slashstar comments, and +// allow for setting options, declaring global variables, and establishing a +// set of allowed property names. + +// These directives respect function scope. + +// The jslint directive is a special comment that can set one or more options. +// The current option set is + +// anon true, if the space may be omitted in anonymous function declarations +// bitwise true, if bitwise operators should be allowed +// browser true, if the standard browser globals should be predefined +// cap true, if upper case HTML should be allowed +// 'continue' true, if the continuation statement should be tolerated +// css true, if CSS workarounds should be tolerated +// debug true, if debugger statements should be allowed +// devel true, if logging should be allowed (console, alert, etc.) +// eqeq true, if == should be allowed +// es5 true, if ES5 syntax should be allowed +// evil true, if eval should be allowed +// forin true, if for in statements need not filter +// fragment true, if HTML fragments should be allowed +// indent the indentation factor +// maxerr the maximum number of errors to allow +// maxlen the maximum length of a source line +// newcap true, if constructor names capitalization is ignored +// node true, if Node.js globals should be predefined +// nomen true, if names may have dangling _ +// on true, if HTML event handlers should be allowed +// passfail true, if the scan should stop on first error +// plusplus true, if increment/decrement should be allowed +// properties true, if all property names must be declared with /*properties*/ +// regexp true, if the . should be allowed in regexp literals +// rhino true, if the Rhino environment globals should be predefined +// undef true, if variables can be declared out of order +// unparam true, if unused parameters should be tolerated +// sloppy true, if the 'use strict'; pragma is optional +// sub true, if all forms of subscript notation are tolerated +// vars true, if multiple var statements per function should be allowed +// white true, if sloppy whitespace is tolerated +// widget true if the Yahoo Widgets globals should be predefined +// windows true, if MS Windows-specific globals should be predefined + +// For example: + +/*jslint + evil: true, nomen: true, regexp: true +*/ + +// The properties directive declares an exclusive list of property names. +// Any properties named in the program that are not in the list will +// produce a warning. + +// For example: + +/*properties + '\b', '\t', '\n', '\f', '\r', '!=', '!==', '"', '%', '\'', '(arguments)', + '(begin)', '(breakage)', '(context)', '(error)', '(identifier)', '(line)', + '(loopage)', '(name)', '(params)', '(scope)', '(token)', '(vars)', '(verb)', + '*', '+', '-', '/', '<', '<=', '==', '===', '>', '>=', ADSAFE, + Array, Date, Function, Object, '\\', a, a_label, a_not_allowed, + a_not_defined, a_scope, abbr, acronym, address, adsafe, adsafe_a, + adsafe_autocomplete, adsafe_bad_id, adsafe_div, adsafe_fragment, adsafe_go, + adsafe_html, adsafe_id, adsafe_id_go, adsafe_lib, adsafe_lib_second, + adsafe_missing_id, adsafe_name_a, adsafe_placement, adsafe_prefix_a, + adsafe_script, adsafe_source, adsafe_subscript_a, adsafe_tag, all, + already_defined, and, anon, applet, apply, approved, area, arity, article, + aside, assign, assign_exception, assignment_function_expression, at, + attribute_case_a, audio, autocomplete, avoid_a, b, background, + 'background-attachment', 'background-color', 'background-image', + 'background-position', 'background-repeat', bad_assignment, bad_color_a, + bad_constructor, bad_entity, bad_html, bad_id_a, bad_in_a, bad_invocation, + bad_name_a, bad_new, bad_number, bad_operand, bad_style, bad_type, bad_url_a, + bad_wrap, base, bdo, big, bitwise, block, blockquote, body, border, + 'border-bottom', 'border-bottom-color', 'border-bottom-left-radius', + 'border-bottom-right-radius', 'border-bottom-style', 'border-bottom-width', + 'border-collapse', 'border-color', 'border-left', 'border-left-color', + 'border-left-style', 'border-left-width', 'border-radius', 'border-right', + 'border-right-color', 'border-right-style', 'border-right-width', + 'border-spacing', 'border-style', 'border-top', 'border-top-color', + 'border-top-left-radius', 'border-top-right-radius', 'border-top-style', + 'border-top-width', 'border-width', bottom, br, braille, browser, button, c, + call, canvas, cap, caption, 'caption-side', center, charAt, charCodeAt, + character, cite, clear, clip, closure, cm, code, col, colgroup, color, + combine_var, command, conditional_assignment, confusing_a, confusing_regexp, + constructor_name_a, content, continue, control_a, 'counter-increment', + 'counter-reset', create, css, cursor, d, dangerous_comment, dangling_a, data, + datalist, dd, debug, del, deleted, details, devel, dfn, dialog, dir, + direction, display, disrupt, div, dl, dt, duplicate_a, edge, edition, else, + em, embed, embossed, empty, 'empty-cells', empty_block, empty_case, + empty_class, entityify, eqeq, errors, es5, eval, evidence, evil, ex, + exception, exec, expected_a, expected_a_at_b_c, expected_a_b, + expected_a_b_from_c_d, expected_at_a, expected_attribute_a, + expected_attribute_value_a, expected_class_a, expected_fraction_a, + expected_id_a, expected_identifier_a, expected_identifier_a_reserved, + expected_lang_a, expected_linear_a, expected_media_a, expected_name_a, + expected_nonstandard_style_attribute, expected_number_a, expected_operator_a, + expected_percent_a, expected_positive_a, expected_pseudo_a, + expected_selector_a, expected_small_a, expected_space_a_b, expected_string_a, + expected_style_attribute, expected_style_pattern, expected_tagname_a, + expected_type_a, f, fieldset, figure, filter, first, flag, float, floor, + font, 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', + 'font-style', 'font-variant', 'font-weight', footer, forEach, for_if, forin, + form, fragment, frame, frameset, from, fromCharCode, fud, funct, function, + function_block, function_eval, function_loop, function_statement, + function_strict, functions, global, globals, h1, h2, h3, h4, h5, h6, + handheld, hasOwnProperty, head, header, height, hgroup, hr, + 'hta:application', html, html_confusion_a, html_handlers, i, id, identifier, + identifier_function, iframe, img, immed, implied_evil, in, indent, indexOf, + infix_in, init, input, ins, insecure_a, isAlpha, isArray, isDigit, isNaN, + join, jslint, json, kbd, keygen, keys, label, label_a_b, labeled, lang, lbp, + leading_decimal_a, led, left, legend, length, 'letter-spacing', li, lib, + line, 'line-height', link, 'list-style', 'list-style-image', + 'list-style-position', 'list-style-type', map, margin, 'margin-bottom', + 'margin-left', 'margin-right', 'margin-top', mark, 'marker-offset', match, + 'max-height', 'max-width', maxerr, maxlen, member, menu, message, meta, + meter, 'min-height', 'min-width', missing_a, missing_a_after_b, + missing_option, missing_property, missing_space_a_b, missing_url, + missing_use_strict, mixed, mm, mode, move_invocation, move_var, n, name, + name_function, nav, nested_comment, newcap, node, noframes, nomen, noscript, + not, not_a_constructor, not_a_defined, not_a_function, not_a_label, + not_a_scope, not_greater, nud, number, object, octal_a, ol, on, opacity, + open, optgroup, option, outer, outline, 'outline-color', 'outline-style', + 'outline-width', output, overflow, 'overflow-x', 'overflow-y', p, padding, + 'padding-bottom', 'padding-left', 'padding-right', 'padding-top', + 'page-break-after', 'page-break-before', param, parameter_a_get_b, + parameter_arguments_a, parameter_set_a, params, paren, parent, passfail, pc, + plusplus, pop, position, postscript, pre, predef, print, progress, + projection, properties, prototype, pt, push, px, q, quote, quotes, r, radix, + range, raw, read_only, reason, redefinition_a, regexp, replace, report, + reserved, reserved_a, rhino, right, rp, rt, ruby, safe, samp, scanned_a_b, + screen, script, search, second, section, select, shift, slash_equal, slice, + sloppy, small, sort, source, span, speech, split, src, statement_block, + stopping, strange_loop, strict, string, strong, style, styleproperty, sub, + subscript, substr, sup, supplant, t, table, 'table-layout', tag_a_in_b, + tbody, td, test, 'text-align', 'text-decoration', 'text-indent', + 'text-shadow', 'text-transform', textarea, tfoot, th, thead, third, thru, + time, title, toLowerCase, toString, toUpperCase, token, too_long, too_many, + top, tr, trailing_decimal_a, tree, tt, tty, tv, type, u, ul, unclosed, + unclosed_comment, unclosed_regexp, undef, undefined, unescaped_a, + unexpected_a, unexpected_char_a_b, unexpected_comment, unexpected_else, + unexpected_property_a, unexpected_space_a_b, 'unicode-bidi', + unnecessary_initialize, unnecessary_use, unparam, unreachable_a_b, + unrecognized_style_attribute_a, unrecognized_tag_a, unsafe, unused, url, + urls, use_array, use_braces, use_charAt, use_object, use_or, use_param, + used_before_a, var, var_a_not, vars, 'vertical-align', video, visibility, + was, weird_assignment, weird_condition, weird_new, weird_program, + weird_relation, weird_ternary, white, 'white-space', widget, width, windows, + 'word-spacing', 'word-wrap', wrap, wrap_immediate, wrap_regexp, + write_is_wrong, writeable, 'z-index' +*/ + +// The global directive is used to declare global variables that can +// be accessed by the program. If a declaration is true, then the variable +// is writeable. Otherwise, it is read-only. + +// We build the application inside a function so that we produce only a single +// global variable. That function will be invoked immediately, and its return +// value is the JSLINT function itself. That function is also an object that +// can contain data and other functions. + +var JSLINT = (function () { + 'use strict'; + + function array_to_object(array, value) { + +// Make an object from an array of keys and a common value. + + var i, length = array.length, object = {}; + for (i = 0; i < length; i += 1) { + object[array[i]] = value; + } + return object; + } + + + var adsafe_id, // The widget's ADsafe id. + adsafe_may, // The widget may load approved scripts. + adsafe_top, // At the top of the widget script. + adsafe_went, // ADSAFE.go has been called. + allowed_option = { + anon : true, + bitwise : true, + browser : true, + cap : true, + 'continue': true, + css : true, + debug : true, + devel : true, + eqeq : true, + es5 : true, + evil : true, + forin : true, + fragment : true, + indent : 10, + maxerr : 1000, + maxlen : 256, + newcap : true, + node : true, + nomen : true, + on : true, + passfail : true, + plusplus : true, + properties: true, + regexp : true, + rhino : true, + undef : true, + unparam : true, + sloppy : true, + sub : true, + vars : true, + white : true, + widget : true, + windows : true + }, + anonname, // The guessed name for anonymous functions. + approved, // ADsafe approved urls. + +// These are operators that should not be used with the ! operator. + + bang = { + '<' : true, + '<=' : true, + '==' : true, + '===': true, + '!==': true, + '!=' : true, + '>' : true, + '>=' : true, + '+' : true, + '-' : true, + '*' : true, + '/' : true, + '%' : true + }, + +// These are property names that should not be permitted in the safe subset. + + banned = array_to_object([ + 'arguments', 'callee', 'caller', 'constructor', 'eval', 'prototype', + 'stack', 'unwatch', 'valueOf', 'watch' + ], true), + begin, // The root token + +// browser contains a set of global names that are commonly provided by a +// web browser environment. + + browser = array_to_object([ + 'clearInterval', 'clearTimeout', 'document', 'event', 'frames', + 'history', 'Image', 'localStorage', 'location', 'name', 'navigator', + 'Option', 'parent', 'screen', 'sessionStorage', 'setInterval', + 'setTimeout', 'Storage', 'window', 'XMLHttpRequest' + ], false), + +// bundle contains the text messages. + + bundle = { + a_label: "'{a}' is a statement label.", + a_not_allowed: "'{a}' is not allowed.", + a_not_defined: "'{a}' is not defined.", + a_scope: "'{a}' used out of scope.", + adsafe_a: "ADsafe violation: '{a}'.", + adsafe_autocomplete: "ADsafe autocomplete violation.", + adsafe_bad_id: "ADSAFE violation: bad id.", + adsafe_div: "ADsafe violation: Wrap the widget in a div.", + adsafe_fragment: "ADSAFE: Use the fragment option.", + adsafe_go: "ADsafe violation: Misformed ADSAFE.go.", + adsafe_html: "Currently, ADsafe does not operate on whole HTML " + + "documents. It operates on
fragments and .js files.", + adsafe_id: "ADsafe violation: id does not match.", + adsafe_id_go: "ADsafe violation: Missing ADSAFE.id or ADSAFE.go.", + adsafe_lib: "ADsafe lib violation.", + adsafe_lib_second: "ADsafe: The second argument to lib must be a function.", + adsafe_missing_id: "ADSAFE violation: missing ID_.", + adsafe_name_a: "ADsafe name violation: '{a}'.", + adsafe_placement: "ADsafe script placement violation.", + adsafe_prefix_a: "ADsafe violation: An id must have a '{a}' prefix", + adsafe_script: "ADsafe script violation.", + adsafe_source: "ADsafe unapproved script source.", + adsafe_subscript_a: "ADsafe subscript '{a}'.", + adsafe_tag: "ADsafe violation: Disallowed tag '{a}'.", + already_defined: "'{a}' is already defined.", + and: "The '&&' subexpression should be wrapped in parens.", + assign_exception: "Do not assign to the exception parameter.", + assignment_function_expression: "Expected an assignment or " + + "function call and instead saw an expression.", + attribute_case_a: "Attribute '{a}' not all lower case.", + avoid_a: "Avoid '{a}'.", + bad_assignment: "Bad assignment.", + bad_color_a: "Bad hex color '{a}'.", + bad_constructor: "Bad constructor.", + bad_entity: "Bad entity.", + bad_html: "Bad HTML string", + bad_id_a: "Bad id: '{a}'.", + bad_in_a: "Bad for in variable '{a}'.", + bad_invocation: "Bad invocation.", + bad_name_a: "Bad name: '{a}'.", + bad_new: "Do not use 'new' for side effects.", + bad_number: "Bad number '{a}'.", + bad_operand: "Bad operand.", + bad_style: "Bad style.", + bad_type: "Bad type.", + bad_url_a: "Bad url '{a}'.", + bad_wrap: "Do not wrap function literals in parens unless they " + + "are to be immediately invoked.", + combine_var: "Combine this with the previous 'var' statement.", + conditional_assignment: "Expected a conditional expression and " + + "instead saw an assignment.", + confusing_a: "Confusing use of '{a}'.", + confusing_regexp: "Confusing regular expression.", + constructor_name_a: "A constructor name '{a}' should start with " + + "an uppercase letter.", + control_a: "Unexpected control character '{a}'.", + css: "A css file should begin with @charset 'UTF-8';", + dangling_a: "Unexpected dangling '_' in '{a}'.", + dangerous_comment: "Dangerous comment.", + deleted: "Only properties should be deleted.", + duplicate_a: "Duplicate '{a}'.", + empty_block: "Empty block.", + empty_case: "Empty case.", + empty_class: "Empty class.", + es5: "This is an ES5 feature.", + evil: "eval is evil.", + expected_a: "Expected '{a}'.", + expected_a_b: "Expected '{a}' and instead saw '{b}'.", + expected_a_b_from_c_d: "Expected '{a}' to match '{b}' from line " + + "{c} and instead saw '{d}'.", + expected_at_a: "Expected an at-rule, and instead saw @{a}.", + expected_a_at_b_c: "Expected '{a}' at column {b}, not column {c}.", + expected_attribute_a: "Expected an attribute, and instead saw [{a}].", + expected_attribute_value_a: "Expected an attribute value and " + + "instead saw '{a}'.", + expected_class_a: "Expected a class, and instead saw .{a}.", + expected_fraction_a: "Expected a number between 0 and 1 and " + + "instead saw '{a}'", + expected_id_a: "Expected an id, and instead saw #{a}.", + expected_identifier_a: "Expected an identifier and instead saw '{a}'.", + expected_identifier_a_reserved: "Expected an identifier and " + + "instead saw '{a}' (a reserved word).", + expected_linear_a: "Expected a linear unit and instead saw '{a}'.", + expected_lang_a: "Expected a lang code, and instead saw :{a}.", + expected_media_a: "Expected a CSS media type, and instead saw '{a}'.", + expected_name_a: "Expected a name and instead saw '{a}'.", + expected_nonstandard_style_attribute: "Expected a non-standard " + + "style attribute and instead saw '{a}'.", + expected_number_a: "Expected a number and instead saw '{a}'.", + expected_operator_a: "Expected an operator and instead saw '{a}'.", + expected_percent_a: "Expected a percentage and instead saw '{a}'", + expected_positive_a: "Expected a positive number and instead saw '{a}'", + expected_pseudo_a: "Expected a pseudo, and instead saw :{a}.", + expected_selector_a: "Expected a CSS selector, and instead saw {a}.", + expected_small_a: "Expected a small positive integer and instead saw '{a}'", + expected_space_a_b: "Expected exactly one space between '{a}' and '{b}'.", + expected_string_a: "Expected a string and instead saw {a}.", + expected_style_attribute: "Excepted a style attribute, and instead saw '{a}'.", + expected_style_pattern: "Expected a style pattern, and instead saw '{a}'.", + expected_tagname_a: "Expected a tagName, and instead saw {a}.", + expected_type_a: "Expected a type, and instead saw {a}.", + for_if: "The body of a for in should be wrapped in an if " + + "statement to filter unwanted properties from the prototype.", + function_block: "Function statements should not be placed in blocks. " + + "Use a function expression or move the statement to the top of " + + "the outer function.", + function_eval: "The Function constructor is eval.", + function_loop: "Don't make functions within a loop.", + function_statement: "Function statements are not invocable. " + + "Wrap the whole function invocation in parens.", + function_strict: "Use the function form of 'use strict'.", + html_confusion_a: "HTML confusion in regular expression '<{a}'.", + html_handlers: "Avoid HTML event handlers.", + identifier_function: "Expected an identifier in an assignment " + + "and instead saw a function invocation.", + implied_evil: "Implied eval is evil. Pass a function instead of a string.", + infix_in: "Unexpected 'in'. Compare with undefined, or use the " + + "hasOwnProperty method instead.", + insecure_a: "Insecure '{a}'.", + isNaN: "Use the isNaN function to compare with NaN.", + label_a_b: "Label '{a}' on '{b}' statement.", + lang: "lang is deprecated.", + leading_decimal_a: "A leading decimal point can be confused with a dot: '.{a}'.", + missing_a: "Missing '{a}'.", + missing_a_after_b: "Missing '{a}' after '{b}'.", + missing_option: "Missing option value.", + missing_property: "Missing property name.", + missing_space_a_b: "Missing space between '{a}' and '{b}'.", + missing_url: "Missing url.", + missing_use_strict: "Missing 'use strict' statement.", + mixed: "Mixed spaces and tabs.", + move_invocation: "Move the invocation into the parens that " + + "contain the function.", + move_var: "Move 'var' declarations to the top of the function.", + name_function: "Missing name in function statement.", + nested_comment: "Nested comment.", + not: "Nested not.", + not_a_constructor: "Do not use {a} as a constructor.", + not_a_defined: "'{a}' has not been fully defined yet.", + not_a_function: "'{a}' is not a function.", + not_a_label: "'{a}' is not a label.", + not_a_scope: "'{a}' is out of scope.", + not_greater: "'{a}' should not be greater than '{b}'.", + octal_a: "Don't use octal: '{a}'. Use '\\u....' instead.", + parameter_arguments_a: "Do not mutate parameter '{a}' when using 'arguments'.", + parameter_a_get_b: "Unexpected parameter '{a}' in get {b} function.", + parameter_set_a: "Expected parameter (value) in set {a} function.", + radix: "Missing radix parameter.", + read_only: "Read only.", + redefinition_a: "Redefinition of '{a}'.", + reserved_a: "Reserved name '{a}'.", + scanned_a_b: "{a} ({b}% scanned).", + slash_equal: "A regular expression literal can be confused with '/='.", + statement_block: "Expected to see a statement and instead saw a block.", + stopping: "Stopping. ", + strange_loop: "Strange loop.", + strict: "Strict violation.", + subscript: "['{a}'] is better written in dot notation.", + tag_a_in_b: "A '<{a}>' must be within '<{b}>'.", + too_long: "Line too long.", + too_many: "Too many errors.", + trailing_decimal_a: "A trailing decimal point can be confused " + + "with a dot: '.{a}'.", + type: "type is unnecessary.", + unclosed: "Unclosed string.", + unclosed_comment: "Unclosed comment.", + unclosed_regexp: "Unclosed regular expression.", + unescaped_a: "Unescaped '{a}'.", + unexpected_a: "Unexpected '{a}'.", + unexpected_char_a_b: "Unexpected character '{a}' in {b}.", + unexpected_comment: "Unexpected comment.", + unexpected_else: "Unexpected 'else' after 'return'.", + unexpected_property_a: "Unexpected /*property*/ '{a}'.", + unexpected_space_a_b: "Unexpected space between '{a}' and '{b}'.", + unnecessary_initialize: "It is not necessary to initialize '{a}' " + + "to 'undefined'.", + unnecessary_use: "Unnecessary 'use strict'.", + unreachable_a_b: "Unreachable '{a}' after '{b}'.", + unrecognized_style_attribute_a: "Unrecognized style attribute '{a}'.", + unrecognized_tag_a: "Unrecognized tag '<{a}>'.", + unsafe: "Unsafe character.", + url: "JavaScript URL.", + use_array: "Use the array literal notation [].", + use_braces: "Spaces are hard to count. Use {{a}}.", + use_charAt: "Use the charAt method.", + use_object: "Use the object literal notation {}.", + use_or: "Use the || operator.", + use_param: "Use a named parameter.", + used_before_a: "'{a}' was used before it was defined.", + var_a_not: "Variable {a} was not declared correctly.", + weird_assignment: "Weird assignment.", + weird_condition: "Weird condition.", + weird_new: "Weird construction. Delete 'new'.", + weird_program: "Weird program.", + weird_relation: "Weird relation.", + weird_ternary: "Weird ternary.", + wrap_immediate: "Wrap an immediate function invocation in parentheses " + + "to assist the reader in understanding that the expression " + + "is the result of a function, and not the function itself.", + wrap_regexp: "Wrap the /regexp/ literal in parens to " + + "disambiguate the slash operator.", + write_is_wrong: "document.write can be a form of eval." + }, + comments_off, + css_attribute_data, + css_any, + + css_colorData = array_to_object([ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", + "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", + "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", + "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", + "darkred", "darksalmon", "darkseagreen", "darkslateblue", + "darkslategray", "darkturquoise", "darkviolet", "deeppink", + "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", + "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", + "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", + "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", + "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgreen", + "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", + "lightslategray", "lightsteelblue", "lightyellow", "lime", + "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", + "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", + "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", + "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", + "orange", "orangered", "orchid", "palegoldenrod", "palegreen", + "paleturquoise", "palevioletred", "papayawhip", "peachpuff", + "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", + "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", + "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", + "snow", "springgreen", "steelblue", "tan", "teal", "thistle", + "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", + "yellow", "yellowgreen", + + "activeborder", "activecaption", "appworkspace", "background", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", + "captiontext", "graytext", "highlight", "highlighttext", + "inactiveborder", "inactivecaption", "inactivecaptiontext", + "infobackground", "infotext", "menu", "menutext", "scrollbar", + "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "window", "windowframe", + "windowtext" + ], true), + + css_border_style, + css_break, + + css_lengthData = { + '%': true, + 'cm': true, + 'em': true, + 'ex': true, + 'in': true, + 'mm': true, + 'pc': true, + 'pt': true, + 'px': true + }, + + css_media, + css_overflow, + + descapes = { + 'b': '\b', + 't': '\t', + 'n': '\n', + 'f': '\f', + 'r': '\r', + '"': '"', + '/': '/', + '\\': '\\' + }, + + devel = array_to_object([ + 'alert', 'confirm', 'console', 'Debug', 'opera', 'prompt', 'WSH' + ], false), + directive, + escapes = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '\'': '\\\'', + '"' : '\\"', + '/' : '\\/', + '\\': '\\\\' + }, + + funct, // The current function, including the labels used in + // the function, as well as (breakage), + // (context), (loopage), (name), (params), (token), + // (vars), (verb) + + functionicity = [ + 'closure', 'exception', 'global', 'label', 'outer', 'undef', + 'unused', 'var' + ], + + functions, // All of the functions + global_funct, // The global body + global_scope, // The global scope + html_tag = { + a: {}, + abbr: {}, + acronym: {}, + address: {}, + applet: {}, + area: {empty: true, parent: ' map '}, + article: {}, + aside: {}, + audio: {}, + b: {}, + base: {empty: true, parent: ' head '}, + bdo: {}, + big: {}, + blockquote: {}, + body: {parent: ' html noframes '}, + br: {empty: true}, + button: {}, + canvas: {parent: ' body p div th td '}, + caption: {parent: ' table '}, + center: {}, + cite: {}, + code: {}, + col: {empty: true, parent: ' table colgroup '}, + colgroup: {parent: ' table '}, + command: {parent: ' menu '}, + datalist: {}, + dd: {parent: ' dl '}, + del: {}, + details: {}, + dialog: {}, + dfn: {}, + dir: {}, + div: {}, + dl: {}, + dt: {parent: ' dl '}, + em: {}, + embed: {}, + fieldset: {}, + figure: {}, + font: {}, + footer: {}, + form: {}, + frame: {empty: true, parent: ' frameset '}, + frameset: {parent: ' html frameset '}, + h1: {}, + h2: {}, + h3: {}, + h4: {}, + h5: {}, + h6: {}, + head: {parent: ' html '}, + header: {}, + hgroup: {}, + hr: {empty: true}, + 'hta:application': + {empty: true, parent: ' head '}, + html: {parent: '*'}, + i: {}, + iframe: {}, + img: {empty: true}, + input: {empty: true}, + ins: {}, + kbd: {}, + keygen: {}, + label: {}, + legend: {parent: ' details fieldset figure '}, + li: {parent: ' dir menu ol ul '}, + link: {empty: true, parent: ' head '}, + map: {}, + mark: {}, + menu: {}, + meta: {empty: true, parent: ' head noframes noscript '}, + meter: {}, + nav: {}, + noframes: {parent: ' html body '}, + noscript: {parent: ' body head noframes '}, + object: {}, + ol: {}, + optgroup: {parent: ' select '}, + option: {parent: ' optgroup select '}, + output: {}, + p: {}, + param: {empty: true, parent: ' applet object '}, + pre: {}, + progress: {}, + q: {}, + rp: {}, + rt: {}, + ruby: {}, + samp: {}, + script: {empty: true, parent: ' body div frame head iframe p pre span '}, + section: {}, + select: {}, + small: {}, + span: {}, + source: {}, + strong: {}, + style: {parent: ' head ', empty: true}, + sub: {}, + sup: {}, + table: {}, + tbody: {parent: ' table '}, + td: {parent: ' tr '}, + textarea: {}, + tfoot: {parent: ' table '}, + th: {parent: ' tr '}, + thead: {parent: ' table '}, + time: {}, + title: {parent: ' head '}, + tr: {parent: ' table tbody thead tfoot '}, + tt: {}, + u: {}, + ul: {}, + 'var': {}, + video: {} + }, + + ids, // HTML ids + in_block, + indent, + itself, // JSLint itself + json_mode, + lex, // the tokenizer + lines, + lookahead, + node = array_to_object([ + 'Buffer', 'clearInterval', 'clearTimeout', 'console', 'exports', + 'global', 'module', 'process', 'querystring', 'require', + 'setInterval', 'setTimeout', '__dirname', '__filename' + ], false), + node_js, + numbery = array_to_object(['indexOf', 'lastIndexOf', 'search'], true), + next_token, + option, + predefined, // Global variables defined by option + prereg, + prev_token, + property, + regexp_flag = array_to_object(['g', 'i', 'm'], true), + return_this = function return_this() { + return this; + }, + rhino = array_to_object([ + 'defineClass', 'deserialize', 'gc', 'help', 'load', 'loadClass', + 'print', 'quit', 'readFile', 'readUrl', 'runCommand', 'seal', + 'serialize', 'spawn', 'sync', 'toint32', 'version' + ], false), + + scope, // An object containing an object for each variable in scope + semicolon_coda = array_to_object([';', '"', '\'', ')'], true), + src, + stack, + +// standard contains the global names that are provided by the +// ECMAScript standard. + + standard = array_to_object([ + 'Array', 'Boolean', 'Date', 'decodeURI', 'decodeURIComponent', + 'encodeURI', 'encodeURIComponent', 'Error', 'eval', 'EvalError', + 'Function', 'isFinite', 'isNaN', 'JSON', 'Math', 'Number', + 'Object', 'parseInt', 'parseFloat', 'RangeError', 'ReferenceError', + 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError' + ], false), + + strict_mode, + syntax = {}, + tab, + token, + urls, + var_mode, + warnings, + +// widget contains the global names which are provided to a Yahoo +// (fna Konfabulator) widget. + + widget = array_to_object([ + 'alert', 'animator', 'appleScript', 'beep', 'bytesToUIString', + 'Canvas', 'chooseColor', 'chooseFile', 'chooseFolder', + 'closeWidget', 'COM', 'convertPathToHFS', 'convertPathToPlatform', + 'CustomAnimation', 'escape', 'FadeAnimation', 'filesystem', 'Flash', + 'focusWidget', 'form', 'FormField', 'Frame', 'HotKey', 'Image', + 'include', 'isApplicationRunning', 'iTunes', 'konfabulatorVersion', + 'log', 'md5', 'MenuItem', 'MoveAnimation', 'openURL', 'play', + 'Point', 'popupMenu', 'preferenceGroups', 'preferences', 'print', + 'prompt', 'random', 'Rectangle', 'reloadWidget', 'ResizeAnimation', + 'resolvePath', 'resumeUpdates', 'RotateAnimation', 'runCommand', + 'runCommandInBg', 'saveAs', 'savePreferences', 'screen', + 'ScrollBar', 'showWidgetPreferences', 'sleep', 'speak', 'Style', + 'suppressUpdates', 'system', 'tellWidget', 'Text', 'TextArea', + 'Timer', 'unescape', 'updateNow', 'URL', 'Web', 'widget', 'Window', + 'XMLDOM', 'XMLHttpRequest', 'yahooCheckLogin', 'yahooLogin', + 'yahooLogout' + ], true), + + windows = array_to_object([ + 'ActiveXObject', 'CScript', 'Debug', 'Enumerator', 'System', + 'VBArray', 'WScript', 'WSH' + ], false), + +// xmode is used to adapt to the exceptions in html parsing. +// It can have these states: +// '' .js script file +// 'html' +// 'outer' +// 'script' +// 'style' +// 'scriptstring' +// 'styleproperty' + + xmode, + xquote, + +// Regular expressions. Some of these are stupidly long. + +// unsafe comment or string + ax = /@cc|<\/?|script|\]\s*\]|<\s*!|</i, +// carriage return, carriage return linefeed, or linefeed + crlfx = /\r\n?|\n/, +// unsafe characters that are silently deleted by one or more browsers + cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/, +// query characters for ids + dx = /[\[\]\/\\"'*<>.&:(){}+=#]/, +// html token + hx = /^\s*(['"=>\/&#]|<(?:\/|\!(?:--)?)?|[a-zA-Z][a-zA-Z0-9_\-:]*|[0-9]+|--)/, +// identifier + ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/, +// javascript url + jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i, +// star slash + lx = /\*\/|\/\*/, +// characters in strings that need escapement + nx = /[\u0000-\u001f'\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, +// outer html token + ox = /[>&]|<[\/!]?|--/, +// attributes characters + qx = /[^a-zA-Z0-9+\-_\/ ]/, +// style + sx = /^\s*([{}:#%.=,>+\[\]@()"';]|[*$\^~]=|[a-zA-Z_][a-zA-Z0-9_\-]*|[0-9]+|<\/|\/\*)/, + ssx = /^\s*([@#!"'};:\-%.=,+\[\]()*_]|[a-zA-Z][a-zA-Z0-9._\-]*|\/\*?|\d+(?:\.\d+)?|<\/)/, +// token + tx = /^\s*([(){}\[\]\?.,:;'"~#@`]|={1,3}|\/(\*(jslint|properties|property|members?|globals?)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|[\^%]=?|&[&=]?|\|[|=]?|>{1,3}=?|<(?:[\/=!]|\!(\[|--)?|<=?)?|\!={0,2}|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+(?:[xX][0-9a-fA-F]+|\.[0-9]*)?(?:[eE][+\-]?[0-9]+)?)/, +// url badness + ux = /&|\+|\u00AD|\.\.|\/\*|%[^;]|base64|url|expression|data|mailto|script/i, + + rx = { + outer: hx, + html: hx, + style: sx, + styleproperty: ssx + }; + + + function F() {} // Used by Object.create + +// Provide critical ES5 functions to ES3. + + if (typeof Array.prototype.filter !== 'function') { + Array.prototype.filter = function (f) { + var i, length = this.length, result = [], value; + for (i = 0; i < length; i += 1) { + try { + value = this[i]; + if (f(value)) { + result.push(value); + } + } catch (ignore) { + } + } + return result; + }; + } + + if (typeof Array.prototype.forEach !== 'function') { + Array.prototype.forEach = function (f) { + var i, length = this.length; + for (i = 0; i < length; i += 1) { + try { + f(this[i]); + } catch (ignore) { + } + } + }; + } + + if (typeof Array.isArray !== 'function') { + Array.isArray = function (o) { + return Object.prototype.toString.apply(o) === '[object Array]'; + }; + } + + if (!Object.prototype.hasOwnProperty.call(Object, 'create')) { + Object.create = function (o) { + F.prototype = o; + return new F(); + }; + } + + if (typeof Object.keys !== 'function') { + Object.keys = function (o) { + var array = [], key; + for (key in o) { + if (Object.prototype.hasOwnProperty.call(o, key)) { + array.push(key); + } + } + return array; + }; + } + + if (typeof String.prototype.entityify !== 'function') { + String.prototype.entityify = function () { + return this + .replace(/&/g, '&') + .replace(//g, '>'); + }; + } + + if (typeof String.prototype.isAlpha !== 'function') { + String.prototype.isAlpha = function () { + return (this >= 'a' && this <= 'z\uffff') || + (this >= 'A' && this <= 'Z\uffff'); + }; + } + + if (typeof String.prototype.isDigit !== 'function') { + String.prototype.isDigit = function () { + return (this >= '0' && this <= '9'); + }; + } + + if (typeof String.prototype.supplant !== 'function') { + String.prototype.supplant = function (o) { + return this.replace(/\{([^{}]*)\}/g, function (a, b) { + var replacement = o[b]; + return typeof replacement === 'string' || + typeof replacement === 'number' ? replacement : a; + }); + }; + } + + + function sanitize(a) { + +// Escapify a troublesome character. + + return escapes[a] || + '\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4); + } + + + function add_to_predefined(group) { + Object.keys(group).forEach(function (name) { + predefined[name] = group[name]; + }); + } + + + function assume() { + if (!option.safe) { + if (option.rhino) { + add_to_predefined(rhino); + option.rhino = false; + } + if (option.devel) { + add_to_predefined(devel); + option.devel = false; + } + if (option.browser) { + add_to_predefined(browser); + option.browser = false; + } + if (option.windows) { + add_to_predefined(windows); + option.windows = false; + } + if (option.node) { + add_to_predefined(node); + option.node = false; + node_js = true; + } + if (option.widget) { + add_to_predefined(widget); + option.widget = false; + } + } + } + + +// Produce an error warning. + + function artifact(tok) { + if (!tok) { + tok = next_token; + } + return tok.number || tok.string; + } + + function quit(message, line, character) { + throw { + name: 'JSLintError', + line: line, + character: character, + message: bundle.scanned_a_b.supplant({ + a: message, + b: Math.floor((line / lines.length) * 100) + }) + }; + } + + function warn(message, offender, a, b, c, d) { + var character, line, warning; + offender = offender || next_token; // ~~ + line = offender.line || 0; + character = offender.from || 0; + warning = { + id: '(error)', + raw: bundle[message] || message, + evidence: lines[line - 1] || '', + line: line, + character: character, + a: a || (offender.id === '(number)' + ? String(offender.number) + : offender.string), + b: b, + c: c, + d: d + }; + warning.reason = warning.raw.supplant(warning); + JSLINT.errors.push(warning); + if (option.passfail) { + quit(bundle.stopping, line, character); + } + warnings += 1; + if (warnings >= option.maxerr) { + quit(bundle.too_many, line, character); + } + return warning; + } + + function warn_at(message, line, character, a, b, c, d) { + return warn(message, { + line: line, + from: character + }, a, b, c, d); + } + + function stop(message, offender, a, b, c, d) { + var warning = warn(message, offender, a, b, c, d); + quit(bundle.stopping, warning.line, warning.character); + } + + function stop_at(message, line, character, a, b, c, d) { + return stop(message, { + line: line, + from: character + }, a, b, c, d); + } + + function expected_at(at) { + if (!option.white && next_token.from !== at) { + warn('expected_a_at_b_c', next_token, '', at, + next_token.from); + } + } + + function aint(it, name, expected) { + if (it[name] !== expected) { + warn('expected_a_b', it, expected, it[name]); + return true; + } + return false; + } + + +// lexical analysis and token construction + + lex = (function lex() { + var character, c, from, length, line, pos, source_row; + +// Private lex methods + + function next_line() { + var at; + if (line >= lines.length) { + return false; + } + character = 1; + source_row = lines[line]; + line += 1; + at = source_row.search(/ \t/); + if (at >= 0) { + warn_at('mixed', line, at + 1); + } + source_row = source_row.replace(/\t/g, tab); + at = source_row.search(cx); + if (at >= 0) { + warn_at('unsafe', line, at); + } + if (option.maxlen && option.maxlen < source_row.length) { + warn_at('too_long', line, source_row.length); + } + return true; + } + +// Produce a token object. The token inherits from a syntax symbol. + + function it(type, value) { + var id, the_token; + if (type === '(string)' || type === '(range)') { + if (jx.test(value)) { + warn_at('url', line, from); + } + } + the_token = Object.create(syntax[( + type === '(punctuator)' || (type === '(identifier)' && + Object.prototype.hasOwnProperty.call(syntax, value)) + ? value + : type + )] || syntax['(error)']); + if (type === '(identifier)') { + the_token.identifier = true; + if (value === '__iterator__' || value === '__proto__') { + stop_at('reserved_a', line, from, value); + } else if (!option.nomen && + (value.charAt(0) === '_' || + value.charAt(value.length - 1) === '_')) { + warn_at('dangling_a', line, from, value); + } + } + if (type === '(number)') { + the_token.number = +value; + } else if (value !== undefined) { + the_token.string = String(value); + } + the_token.line = line; + the_token.from = from; + the_token.thru = character; + id = the_token.id; + prereg = id && ( + ('(,=:[!&|?{};'.indexOf(id.charAt(id.length - 1)) >= 0) || + id === 'return' || id === 'case' + ); + return the_token; + } + + function match(x) { + var exec = x.exec(source_row), first; + if (exec) { + length = exec[0].length; + first = exec[1]; + c = first.charAt(0); + source_row = source_row.slice(length); + from = character + length - first.length; + character += length; + return first; + } + } + + function string(x) { + var c, pos = 0, r = '', result; + + function hex(n) { + var i = parseInt(source_row.substr(pos + 1, n), 16); + pos += n; + if (i >= 32 && i <= 126 && + i !== 34 && i !== 92 && i !== 39) { + warn_at('unexpected_a', line, character, '\\'); + } + character += n; + c = String.fromCharCode(i); + } + + if (json_mode && x !== '"') { + warn_at('expected_a', line, character, '"'); + } + + if (xquote === x || (xmode === 'scriptstring' && !xquote)) { + return it('(punctuator)', x); + } + + for (;;) { + while (pos >= source_row.length) { + pos = 0; + if (xmode !== 'html' || !next_line()) { + stop_at('unclosed', line, from); + } + } + c = source_row.charAt(pos); + if (c === x) { + character += 1; + source_row = source_row.slice(pos + 1); + result = it('(string)', r); + result.quote = x; + return result; + } + if (c < ' ') { + if (c === '\n' || c === '\r') { + break; + } + warn_at('control_a', line, character + pos, + source_row.slice(0, pos)); + } else if (c === xquote) { + warn_at('bad_html', line, character + pos); + } else if (c === '<') { + if (option.safe && xmode === 'html') { + warn_at('adsafe_a', line, character + pos, c); + } else if (source_row.charAt(pos + 1) === '/' && (xmode || option.safe)) { + warn_at('expected_a_b', line, character, + '<\\/', '= '0' && c <= '7' ? 'octal_a' : 'unexpected_a', + line, character, '\\' + c); + } else { + c = descapes[c]; + } + } + } + } + r += c; + character += 1; + pos += 1; + } + } + + function number(snippet) { + var digit; + if (xmode !== 'style' && xmode !== 'styleproperty' && + source_row.charAt(0).isAlpha()) { + warn_at('expected_space_a_b', + line, character, c, source_row.charAt(0)); + } + if (c === '0') { + digit = snippet.charAt(1); + if (digit.isDigit()) { + if (token.id !== '.' && xmode !== 'styleproperty') { + warn_at('unexpected_a', line, character, snippet); + } + } else if (json_mode && (digit === 'x' || digit === 'X')) { + warn_at('unexpected_a', line, character, '0x'); + } + } + if (snippet.slice(snippet.length - 1) === '.') { + warn_at('trailing_decimal_a', line, character, snippet); + } + if (xmode !== 'style') { + digit = +snippet; + if (!isFinite(digit)) { + warn_at('bad_number', line, character, snippet); + } + snippet = digit; + } + return it('(number)', snippet); + } + + function comment(snippet) { + if (comments_off || src || (xmode && xmode !== 'script' && + xmode !== 'style' && xmode !== 'styleproperty')) { + warn_at('unexpected_comment', line, character); + } else if (xmode === 'script' && /<\//i.test(source_row)) { + warn_at('unexpected_a', line, character, '<\/'); + } else if (option.safe && ax.test(snippet)) { + warn_at('dangerous_comment', line, character); + } + } + + function regexp() { + var b, + bit, + captures = 0, + depth = 0, + flag = '', + high, + letter, + length = 0, + low, + potential, + quote, + result; + for (;;) { + b = true; + c = source_row.charAt(length); + length += 1; + switch (c) { + case '': + stop_at('unclosed_regexp', line, from); + return; + case '/': + if (depth > 0) { + warn_at('unescaped_a', line, from + length, '/'); + } + c = source_row.slice(0, length - 1); + potential = Object.create(regexp_flag); + for (;;) { + letter = source_row.charAt(length); + if (potential[letter] !== true) { + break; + } + potential[letter] = false; + length += 1; + flag += letter; + } + if (source_row.charAt(length).isAlpha()) { + stop_at('unexpected_a', line, from, source_row.charAt(length)); + } + character += length; + source_row = source_row.slice(length); + quote = source_row.charAt(0); + if (quote === '/' || quote === '*') { + stop_at('confusing_regexp', line, from); + } + result = it('(regexp)', c); + result.flag = flag; + return result; + case '\\': + c = source_row.charAt(length); + if (c < ' ') { + warn_at('control_a', line, from + length, String(c)); + } else if (c === '<') { + warn_at(bundle.unexpected_a, line, from + length, '\\'); + } + length += 1; + break; + case '(': + depth += 1; + b = false; + if (source_row.charAt(length) === '?') { + length += 1; + switch (source_row.charAt(length)) { + case ':': + case '=': + case '!': + length += 1; + break; + default: + warn_at(bundle.expected_a_b, line, from + length, + ':', source_row.charAt(length)); + } + } else { + captures += 1; + } + break; + case '|': + b = false; + break; + case ')': + if (depth === 0) { + warn_at('unescaped_a', line, from + length, ')'); + } else { + depth -= 1; + } + break; + case ' ': + pos = 1; + while (source_row.charAt(length) === ' ') { + length += 1; + pos += 1; + } + if (pos > 1) { + warn_at('use_braces', line, from + length, pos); + } + break; + case '[': + c = source_row.charAt(length); + if (c === '^') { + length += 1; + if (!option.regexp) { + warn_at('insecure_a', line, from + length, c); + } else if (source_row.charAt(length) === ']') { + stop_at('unescaped_a', line, from + length, '^'); + } + } + bit = false; + if (c === ']') { + warn_at('empty_class', line, from + length - 1); + bit = true; + } +klass: do { + c = source_row.charAt(length); + length += 1; + switch (c) { + case '[': + case '^': + warn_at('unescaped_a', line, from + length, c); + bit = true; + break; + case '-': + if (bit) { + bit = false; + } else { + warn_at('unescaped_a', line, from + length, '-'); + bit = true; + } + break; + case ']': + if (!bit) { + warn_at('unescaped_a', line, from + length - 1, '-'); + } + break klass; + case '\\': + c = source_row.charAt(length); + if (c < ' ') { + warn_at(bundle.control_a, line, from + length, String(c)); + } else if (c === '<') { + warn_at(bundle.unexpected_a, line, from + length, '\\'); + } + length += 1; + bit = true; + break; + case '/': + warn_at('unescaped_a', line, from + length - 1, '/'); + bit = true; + break; + case '<': + if (xmode === 'script') { + c = source_row.charAt(length); + if (c === '!' || c === '/') { + warn_at(bundle.html_confusion_a, line, + from + length, c); + } + } + bit = true; + break; + default: + bit = true; + } + } while (c); + break; + case '.': + if (!option.regexp) { + warn_at('insecure_a', line, from + length, c); + } + break; + case ']': + case '?': + case '{': + case '}': + case '+': + case '*': + warn_at('unescaped_a', line, from + length, c); + break; + case '<': + if (xmode === 'script') { + c = source_row.charAt(length); + if (c === '!' || c === '/') { + warn_at(bundle.html_confusion_a, line, from + length, c); + } + } + break; + } + if (b) { + switch (source_row.charAt(length)) { + case '?': + case '+': + case '*': + length += 1; + if (source_row.charAt(length) === '?') { + length += 1; + } + break; + case '{': + length += 1; + c = source_row.charAt(length); + if (c < '0' || c > '9') { + warn_at(bundle.expected_number_a, line, + from + length, c); + } + length += 1; + low = +c; + for (;;) { + c = source_row.charAt(length); + if (c < '0' || c > '9') { + break; + } + length += 1; + low = +c + (low * 10); + } + high = low; + if (c === ',') { + length += 1; + high = Infinity; + c = source_row.charAt(length); + if (c >= '0' && c <= '9') { + length += 1; + high = +c; + for (;;) { + c = source_row.charAt(length); + if (c < '0' || c > '9') { + break; + } + length += 1; + high = +c + (high * 10); + } + } + } + if (source_row.charAt(length) !== '}') { + warn_at(bundle.expected_a_b, line, from + length, + '}', c); + } else { + length += 1; + } + if (source_row.charAt(length) === '?') { + length += 1; + } + if (low > high) { + warn_at(bundle.not_greater, line, from + length, + low, high); + } + break; + } + } + } + c = source_row.slice(0, length - 1); + character += length; + source_row = source_row.slice(length); + return it('(regexp)', c); + } + +// Public lex methods + + return { + init: function (source) { + if (typeof source === 'string') { + lines = source.split(crlfx); + } else { + lines = source; + } + line = 0; + next_line(); + from = 1; + }, + + range: function (begin, end) { + var c, value = ''; + from = character; + if (source_row.charAt(0) !== begin) { + stop_at('expected_a_b', line, character, begin, + source_row.charAt(0)); + } + for (;;) { + source_row = source_row.slice(1); + character += 1; + c = source_row.charAt(0); + switch (c) { + case '': + stop_at('missing_a', line, character, c); + break; + case end: + source_row = source_row.slice(1); + character += 1; + return it('(range)', value); + case xquote: + case '\\': + warn_at('unexpected_a', line, character, c); + break; + } + value += c; + } + }, + +// token -- this is called by advance to get the next token. + + token: function () { + var c, i, snippet; + + for (;;) { + while (!source_row) { + if (!next_line()) { + return it('(end)'); + } + } + while (xmode === 'outer') { + i = source_row.search(ox); + if (i === 0) { + break; + } else if (i > 0) { + character += 1; + source_row = source_row.slice(i); + break; + } else { + if (!next_line()) { + return it('(end)', ''); + } + } + } + snippet = match(rx[xmode] || tx); + if (!snippet) { + if (source_row) { + if (source_row.charAt(0) === ' ') { + if (!option.white) { + warn_at('unexpected_a', line, character, + '(space)'); + } + character += 1; + source_row = ''; + } else { + stop_at('unexpected_a', line, character, + source_row.charAt(0)); + } + } + } else { + +// identifier + + c = snippet.charAt(0); + if (c.isAlpha() || c === '_' || c === '$') { + return it('(identifier)', snippet); + } + +// number + + if (c.isDigit()) { + return number(snippet); + } + switch (snippet) { + +// string + + case '"': + case "'": + return string(snippet); + +// // comment + + case '//': + comment(source_row); + source_row = ''; + break; + +// /* comment + + case '/*': + for (;;) { + i = source_row.search(lx); + if (i >= 0) { + break; + } + comment(source_row); + if (!next_line()) { + stop_at('unclosed_comment', line, character); + } + } + comment(source_row.slice(0, i)); + character += i + 2; + if (source_row.charAt(i) === '/') { + stop_at('nested_comment', line, character); + } + source_row = source_row.slice(i + 2); + break; + + case '': + break; +// / + case '/': + if (token.id === '/=') { + stop_at( + bundle.slash_equal, + line, + from + ); + } + return prereg + ? regexp() + : it('(punctuator)', snippet); + +// punctuator + + case ''); + } + character += 3; + source_row = source_row.slice(i + 3); + break; + case '#': + if (xmode === 'html' || xmode === 'styleproperty') { + for (;;) { + c = source_row.charAt(0); + if ((c < '0' || c > '9') && + (c < 'a' || c > 'f') && + (c < 'A' || c > 'F')) { + break; + } + character += 1; + source_row = source_row.slice(1); + snippet += c; + } + if (snippet.length !== 4 && snippet.length !== 7) { + warn_at('bad_color_a', line, + from + length, snippet); + } + return it('(color)', snippet); + } + return it('(punctuator)', snippet); + + default: + if (xmode === 'outer' && c === '&') { + character += 1; + source_row = source_row.slice(1); + for (;;) { + c = source_row.charAt(0); + character += 1; + source_row = source_row.slice(1); + if (c === ';') { + break; + } + if (!((c >= '0' && c <= '9') || + (c >= 'a' && c <= 'z') || + c === '#')) { + stop_at('bad_entity', line, from + length, + character); + } + } + break; + } + return it('(punctuator)', snippet); + } + } + } + } + }; + }()); + + + function add_label(token, kind, name) { + +// Define the symbol in the current function in the current scope. + + name = name || token.string; + +// Global variables cannot be created in the safe subset. If a global variable +// already exists, do nothing. If it is predefined, define it. + + if (funct === global_funct) { + if (option.safe) { + warn('adsafe_a', token, name); + } + if (typeof global_funct[name] !== 'string') { + token.writeable = typeof predefined[name] === 'boolean' + ? predefined[name] + : true; + token.funct = funct; + global_scope[name] = token; + } + if (kind === 'becoming') { + kind = 'var'; + } + +// Ordinary variables. + + } else { + +// Warn if the variable already exists. + + if (typeof funct[name] === 'string') { + if (funct[name] === 'undef') { + if (!option.undef) { + warn('used_before_a', token, name); + } + kind = 'var'; + } else { + warn('already_defined', token, name); + } + } else { + +// Add the symbol to the current function. + + token.funct = funct; + token.writeable = true; + scope[name] = token; + } + } + funct[name] = kind; + } + + + function peek(distance) { + +// Peek ahead to a future token. The distance is how far ahead to look. The +// default is the next token. + + var found, slot = 0; + + distance = distance || 0; + while (slot <= distance) { + found = lookahead[slot]; + if (!found) { + found = lookahead[slot] = lex.token(); + } + slot += 1; + } + return found; + } + + + function advance(id, match) { + +// Produce the next token, also looking for programming errors. + + if (indent) { + +// If indentation checking was requested, then inspect all of the line breakings. +// The var statement is tricky because the names might be aligned or not. We +// look at the first line break after the var to determine the programmer's +// intention. + + if (var_mode && next_token.line !== token.line) { + if ((var_mode !== indent || !next_token.edge) && + next_token.from === indent.at - + (next_token.edge ? option.indent : 0)) { + var dent = indent; + for (;;) { + dent.at -= option.indent; + if (dent === var_mode) { + break; + } + dent = dent.was; + } + dent.open = false; + } + var_mode = null; + } + if (next_token.id === '?' && indent.mode === ':' && + token.line !== next_token.line) { + indent.at -= option.indent; + } + if (indent.open) { + +// If the token is an edge. + + if (next_token.edge) { + if (next_token.edge === 'label') { + expected_at(1); + } else if (next_token.edge === 'case' || indent.mode === 'statement') { + expected_at(indent.at - option.indent); + } else if (indent.mode !== 'array' || next_token.line !== token.line) { + expected_at(indent.at); + } + +// If the token is not an edge, but is the first token on the line. + + } else if (next_token.line !== token.line) { + if (next_token.from < indent.at + (indent.mode === + 'expression' ? 0 : option.indent)) { + expected_at(indent.at + option.indent); + } + indent.wrap = true; + } + } else if (next_token.line !== token.line) { + if (next_token.edge) { + expected_at(indent.at); + } else { + indent.wrap = true; + if (indent.mode === 'statement' || indent.mode === 'var') { + expected_at(indent.at + option.indent); + } else if (next_token.from < indent.at + (indent.mode === + 'expression' ? 0 : option.indent)) { + expected_at(indent.at + option.indent); + } + } + } + } + + switch (token.id) { + case '(number)': + if (next_token.id === '.') { + warn('trailing_decimal_a'); + } + break; + case '-': + if (next_token.id === '-' || next_token.id === '--') { + warn('confusing_a'); + } + break; + case '+': + if (next_token.id === '+' || next_token.id === '++') { + warn('confusing_a'); + } + break; + } + if (token.id === '(string)' || token.identifier) { + anonname = token.string; + } + + if (id && next_token.id !== id) { + if (match) { + warn('expected_a_b_from_c_d', next_token, id, + match.id, match.line, artifact()); + } else if (!next_token.identifier || next_token.string !== id) { + warn('expected_a_b', next_token, id, artifact()); + } + } + prev_token = token; + token = next_token; + next_token = lookahead.shift() || lex.token(); + } + + + function advance_identifier(string) { + if (next_token.identifier && next_token.string === string) { + advance(); + } else { + warn('expected_a_b', next_token, string, artifact()); + } + } + + + function do_safe() { + if (option.adsafe) { + option.safe = true; + } + if (option.safe) { + option.browser = + option['continue'] = + option.css = + option.debug = + option.devel = + option.evil = + option.forin = + option.newcap = + option.nomen = + option.on = + option.rhino = + option.sloppy = + option.sub = + option.undef = + option.widget = + option.windows = false; + + + delete predefined.Array; + delete predefined.Date; + delete predefined.Function; + delete predefined.Object; + delete predefined['eval']; + + add_to_predefined({ + ADSAFE: false, + lib: false + }); + } + } + + + function do_globals() { + var name, writeable; + for (;;) { + if (next_token.id !== '(string)' && !next_token.identifier) { + return; + } + name = next_token.string; + advance(); + writeable = false; + if (next_token.id === ':') { + advance(':'); + switch (next_token.id) { + case 'true': + writeable = predefined[name] !== false; + advance('true'); + break; + case 'false': + advance('false'); + break; + default: + stop('unexpected_a'); + } + } + predefined[name] = writeable; + if (next_token.id !== ',') { + return; + } + advance(','); + } + } + + + function do_jslint() { + var name, value; + while (next_token.id === '(string)' || next_token.identifier) { + name = next_token.string; + if (!allowed_option[name]) { + stop('unexpected_a'); + } + advance(); + if (next_token.id !== ':') { + stop('expected_a_b', next_token, ':', artifact()); + } + advance(':'); + if (typeof allowed_option[name] === 'number') { + value = next_token.number; + if (value > allowed_option[name] || value <= 0 || + Math.floor(value) !== value) { + stop('expected_small_a'); + } + option[name] = value; + } else { + if (next_token.id === 'true') { + option[name] = true; + } else if (next_token.id === 'false') { + option[name] = false; + } else { + stop('unexpected_a'); + } + } + advance(); + if (next_token.id === ',') { + advance(','); + } + } + assume(); + } + + + function do_properties() { + var name; + option.properties = true; + for (;;) { + if (next_token.id !== '(string)' && !next_token.identifier) { + return; + } + name = next_token.string; + advance(); + if (next_token.id === ':') { + for (;;) { + advance(); + if (next_token.id !== '(string)' && !next_token.identifier) { + break; + } + } + } + property[name] = 0; + if (next_token.id !== ',') { + return; + } + advance(','); + } + } + + + directive = function directive() { + var command = this.id, + old_comments_off = comments_off, + old_indent = indent; + comments_off = true; + indent = null; + if (next_token.line === token.line && next_token.from === token.thru) { + warn('missing_space_a_b', next_token, artifact(token), artifact()); + } + if (lookahead.length > 0) { + warn('unexpected_a', this); + } + switch (command) { + case '/*properties': + case '/*property': + case '/*members': + case '/*member': + do_properties(); + break; + case '/*jslint': + if (option.safe) { + warn('adsafe_a', this); + } + do_jslint(); + break; + case '/*globals': + case '/*global': + if (option.safe) { + warn('adsafe_a', this); + } + do_globals(); + break; + default: + stop('unexpected_a', this); + } + comments_off = old_comments_off; + advance('*/'); + indent = old_indent; + }; + + +// Indentation intention + + function edge(mode) { + next_token.edge = indent ? indent.open && (mode || 'edge') : ''; + } + + + function step_in(mode) { + var open; + if (typeof mode === 'number') { + indent = { + at: +mode, + open: true, + was: indent + }; + } else if (!indent) { + indent = { + at: 1, + mode: 'statement', + open: true + }; + } else if (mode === 'statement') { + indent = { + at: indent.at, + open: true, + was: indent + }; + } else { + open = mode === 'var' || next_token.line !== token.line; + indent = { + at: (open || mode === 'control' + ? indent.at + option.indent + : indent.at) + (indent.wrap ? option.indent : 0), + mode: mode, + open: open, + was: indent + }; + if (mode === 'var' && open) { + var_mode = indent; + } + } + } + + function step_out(id, symbol) { + if (id) { + if (indent && indent.open) { + indent.at -= option.indent; + edge(); + } + advance(id, symbol); + } + if (indent) { + indent = indent.was; + } + } + +// Functions for conformance of whitespace. + + function one_space(left, right) { + left = left || token; + right = right || next_token; + if (right.id !== '(end)' && !option.white && + (token.line !== right.line || + token.thru + 1 !== right.from)) { + warn('expected_space_a_b', right, artifact(token), artifact(right)); + } + } + + function one_space_only(left, right) { + left = left || token; + right = right || next_token; + if (right.id !== '(end)' && (left.line !== right.line || + (!option.white && left.thru + 1 !== right.from))) { + warn('expected_space_a_b', right, artifact(left), artifact(right)); + } + } + + function no_space(left, right) { + left = left || token; + right = right || next_token; + if ((!option.white || xmode === 'styleproperty' || xmode === 'style') && + left.thru !== right.from && left.line === right.line) { + warn('unexpected_space_a_b', right, artifact(left), artifact(right)); + } + } + + function no_space_only(left, right) { + left = left || token; + right = right || next_token; + if (right.id !== '(end)' && (left.line !== right.line || + (!option.white && left.thru !== right.from))) { + warn('unexpected_space_a_b', right, artifact(left), artifact(right)); + } + } + + function spaces(left, right) { + if (!option.white) { + left = left || token; + right = right || next_token; + if (left.thru === right.from && left.line === right.line) { + warn('missing_space_a_b', right, artifact(left), artifact(right)); + } + } + } + + function comma() { + if (next_token.id !== ',') { + warn_at('expected_a_b', token.line, token.thru, ',', artifact()); + } else { + if (!option.white) { + no_space_only(); + } + advance(','); + spaces(); + } + } + + + function semicolon() { + if (next_token.id !== ';') { + warn_at('expected_a_b', token.line, token.thru, ';', artifact()); + } else { + if (!option.white) { + no_space_only(); + } + advance(';'); + if (semicolon_coda[next_token.id] !== true) { + spaces(); + } + } + } + + function use_strict() { + if (next_token.string === 'use strict') { + if (strict_mode) { + warn('unnecessary_use'); + } + edge(); + advance(); + semicolon(); + strict_mode = true; + option.newcap = false; + option.undef = false; + return true; + } + return false; + } + + + function are_similar(a, b) { + if (a === b) { + return true; + } + if (Array.isArray(a)) { + if (Array.isArray(b) && a.length === b.length) { + var i; + for (i = 0; i < a.length; i += 1) { + if (!are_similar(a[i], b[i])) { + return false; + } + } + return true; + } + return false; + } + if (Array.isArray(b)) { + return false; + } + if (a.id === '(number)' && b.id === '(number)') { + return a.number === b.number; + } + if (a.arity === b.arity && a.string === b.string) { + switch (a.arity) { + case 'prefix': + case 'suffix': + case undefined: + return a.id === b.id && are_similar(a.first, b.first); + case 'infix': + return are_similar(a.first, b.first) && + are_similar(a.second, b.second); + case 'ternary': + return are_similar(a.first, b.first) && + are_similar(a.second, b.second) && + are_similar(a.third, b.third); + case 'function': + case 'regexp': + return false; + default: + return true; + } + } else { + if (a.id === '.' && b.id === '[' && b.arity === 'infix') { + return a.second.string === b.second.string && b.second.id === '(string)'; + } + if (a.id === '[' && a.arity === 'infix' && b.id === '.') { + return a.second.string === b.second.string && a.second.id === '(string)'; + } + } + return false; + } + + +// This is the heart of JSLINT, the Pratt parser. In addition to parsing, it +// is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is +// like .nud except that it is only used on the first token of a statement. +// Having .fud makes it much easier to define statement-oriented languages like +// JavaScript. I retained Pratt's nomenclature. + +// .nud Null denotation +// .fud First null denotation +// .led Left denotation +// lbp Left binding power +// rbp Right binding power + +// They are elements of the parsing method called Top Down Operator Precedence. + + function expression(rbp, initial) { + +// rbp is the right binding power. +// initial indicates that this is the first expression of a statement. + + var left; + if (next_token.id === '(end)') { + stop('unexpected_a', token, next_token.id); + } + advance(); + if (option.safe && scope[token.string] && + scope[token.string] === global_scope[token.string] && + (next_token.id !== '(' && next_token.id !== '.')) { + warn('adsafe_a', token); + } + if (initial) { + anonname = 'anonymous'; + funct['(verb)'] = token.string; + } + if (initial === true && token.fud) { + left = token.fud(); + } else { + if (token.nud) { + left = token.nud(); + } else { + if (next_token.id === '(number)' && token.id === '.') { + warn('leading_decimal_a', token, artifact()); + advance(); + return token; + } + stop('expected_identifier_a', token, token.id); + } + while (rbp < next_token.lbp) { + advance(); + if (token.led) { + left = token.led(left); + } else { + stop('expected_operator_a', token, token.id); + } + } + } + return left; + } + + +// Functional constructors for making the symbols that will be inherited by +// tokens. + + function symbol(s, p) { + var x = syntax[s]; + if (!x || typeof x !== 'object') { + syntax[s] = x = { + id: s, + lbp: p || 0, + string: s + }; + } + return x; + } + + function postscript(x) { + x.postscript = true; + return x; + } + + function ultimate(s) { + var x = symbol(s, 0); + x.from = 1; + x.thru = 1; + x.line = 0; + x.edge = 'edge'; + s.string = s; + return postscript(x); + } + + + function stmt(s, f) { + var x = symbol(s); + x.identifier = x.reserved = true; + x.fud = f; + return x; + } + + function labeled_stmt(s, f) { + var x = stmt(s, f); + x.labeled = true; + } + + function disrupt_stmt(s, f) { + var x = stmt(s, f); + x.disrupt = true; + } + + + function reserve_name(x) { + var c = x.id.charAt(0); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { + x.identifier = x.reserved = true; + } + return x; + } + + + function prefix(s, f) { + var x = symbol(s, 150); + reserve_name(x); + x.nud = typeof f === 'function' + ? f + : function () { + if (s === 'typeof') { + one_space(); + } else { + no_space_only(); + } + this.first = expression(150); + this.arity = 'prefix'; + if (this.id === '++' || this.id === '--') { + if (!option.plusplus) { + warn('unexpected_a', this); + } else if ((!this.first.identifier || this.first.reserved) && + this.first.id !== '.' && this.first.id !== '[') { + warn('bad_operand', this); + } + } + return this; + }; + return x; + } + + + function type(s, t, nud) { + var x = symbol(s); + x.arity = t; + if (nud) { + x.nud = nud; + } + return x; + } + + + function reserve(s, f) { + var x = symbol(s); + x.identifier = x.reserved = true; + if (typeof f === 'function') { + x.nud = f; + } + return x; + } + + + function constant(name) { + var x = reserve(name); + x.string = name; + x.nud = return_this; + return x; + } + + + function reservevar(s, v) { + return reserve(s, function () { + if (typeof v === 'function') { + v(this); + } + return this; + }); + } + + + function infix(s, p, f, w) { + var x = symbol(s, p); + reserve_name(x); + x.led = function (left) { + this.arity = 'infix'; + if (!w) { + spaces(prev_token, token); + spaces(); + } + if (!option.bitwise && this.bitwise) { + warn('unexpected_a', this); + } + if (typeof f === 'function') { + return f(left, this); + } + this.first = left; + this.second = expression(p); + return this; + }; + return x; + } + + function expected_relation(node, message) { + if (node.assign) { + warn(message || bundle.conditional_assignment, node); + } + return node; + } + + function expected_condition(node, message) { + switch (node.id) { + case '[': + case '-': + if (node.arity !== 'infix') { + warn(message || bundle.weird_condition, node); + } + break; + case 'false': + case 'function': + case 'Infinity': + case 'NaN': + case 'null': + case 'true': + case 'undefined': + case 'void': + case '(number)': + case '(regexp)': + case '(string)': + case '{': + warn(message || bundle.weird_condition, node); + break; + case '(': + if (node.first.id === '.' && numbery[node.first.second.string] === true) { + warn(message || bundle.weird_condition, node); + } + break; + } + return node; + } + + function check_relation(node) { + switch (node.arity) { + case 'prefix': + switch (node.id) { + case '{': + case '[': + warn('unexpected_a', node); + break; + case '!': + warn('confusing_a', node); + break; + } + break; + case 'function': + case 'regexp': + warn('unexpected_a', node); + break; + default: + if (node.id === 'NaN') { + warn('isNaN', node); + } + } + return node; + } + + + function relation(s, eqeq) { + return infix(s, 100, function (left, that) { + check_relation(left); + if (eqeq && !option.eqeq) { + warn('expected_a_b', that, eqeq, that.id); + } + var right = expression(100); + if (are_similar(left, right) || + ((left.id === '(string)' || left.id === '(number)') && + (right.id === '(string)' || right.id === '(number)'))) { + warn('weird_relation', that); + } + that.first = left; + that.second = check_relation(right); + return that; + }); + } + + + function assignop(s, op) { + var x = infix(s, 20, function (left, that) { + var l; + that.first = left; + if (left.identifier) { + if (scope[left.string]) { + if (scope[left.string].writeable === false) { + warn('read_only', left); + } + } else { + stop('read_only'); + } + if (funct['(params)']) { + funct['(params)'].forEach(function (value) { + if (value.string === left.string) { + value.assign = true; + } + }); + } + } else if (option.safe) { + l = left; + do { + if (typeof predefined[l.string] === 'boolean') { + warn('adsafe_a', l); + } + l = l.first; + } while (l); + } + if (left === syntax['function']) { + warn('identifier_function', token); + } + if (left.id === '.' || left.id === '[') { + if (!left.first || left.first.string === 'arguments') { + warn('bad_assignment', that); + } + } else if (left.identifier) { + if (!left.reserved && funct[left.string] === 'exception') { + warn('assign_exception', left); + } + } else { + warn('bad_assignment', that); + } + that.second = expression(19); + if (that.id === '=' && are_similar(that.first, that.second)) { + warn('weird_assignment', that); + } + return that; + }); + x.assign = true; + if (op) { + if (syntax[op].bitwise) { + x.bitwise = true; + } + } + return x; + } + + + function bitwise(s, p) { + var x = infix(s, p, 'number'); + x.bitwise = true; + return x; + } + + + function suffix(s) { + var x = symbol(s, 150); + x.led = function (left) { + no_space_only(prev_token, token); + if (!option.plusplus) { + warn('unexpected_a', this); + } else if ((!left.identifier || left.reserved) && + left.id !== '.' && left.id !== '[') { + warn('bad_operand', this); + } + this.first = left; + this.arity = 'suffix'; + return this; + }; + return x; + } + + + function optional_identifier() { + if (next_token.identifier) { + advance(); + if (option.safe && banned[token.string]) { + warn('adsafe_a', token); + } else if (token.reserved && !option.es5) { + warn('expected_identifier_a_reserved', token); + } + return token.string; + } + } + + + function identifier() { + var i = optional_identifier(); + if (!i) { + stop(token.id === 'function' && next_token.id === '(' + ? 'name_function' + : 'expected_identifier_a'); + } + return i; + } + + + function statement() { + + var label, old_scope = scope, the_statement; + +// We don't like the empty statement. + + if (next_token.id === ';') { + warn('unexpected_a'); + semicolon(); + return; + } + +// Is this a labeled statement? + + if (next_token.identifier && !next_token.reserved && peek().id === ':') { + edge('label'); + label = next_token; + advance(); + advance(':'); + scope = Object.create(old_scope); + add_label(label, 'label'); + if (next_token.labeled !== true) { + warn('label_a_b', next_token, label.string, artifact()); + } else if (jx.test(label.string + ':')) { + warn('url', label); + } else if (funct === global_funct) { + stop('unexpected_a', token); + } + next_token.label = label; + } + +// Parse the statement. + + if (token.id !== 'else') { + edge(); + } + step_in('statement'); + the_statement = expression(0, true); + if (the_statement) { + +// Look for the final semicolon. + + if (the_statement.arity === 'statement') { + if (the_statement.id === 'switch' || + (the_statement.block && the_statement.id !== 'do')) { + spaces(); + } else { + semicolon(); + } + } else { + +// If this is an expression statement, determine if it is acceptable. +// We do not like +// new Blah(); +// statments. If it is to be used at all, new should only be used to make +// objects, not side effects. The expression statements we do like do +// assignment or invocation or delete. + + if (the_statement.id === '(') { + if (the_statement.first.id === 'new') { + warn('bad_new'); + } + } else if (!the_statement.assign && + the_statement.id !== 'delete' && + the_statement.id !== '++' && + the_statement.id !== '--') { + warn('assignment_function_expression', token); + } + semicolon(); + } + } + step_out(); + scope = old_scope; + return the_statement; + } + + + function statements() { + var array = [], disruptor, the_statement; + +// A disrupt statement may not be followed by any other statement. +// If the last statement is disrupt, then the sequence is disrupt. + + while (next_token.postscript !== true) { + if (next_token.id === ';') { + warn('unexpected_a', next_token); + semicolon(); + } else { + if (next_token.string === 'use strict') { + if ((!node_js && xmode !== 'script') || funct !== global_funct || array.length > 0) { + warn('function_strict'); + } + use_strict(); + } + if (disruptor) { + warn('unreachable_a_b', next_token, next_token.string, + disruptor.string); + disruptor = null; + } + the_statement = statement(); + if (the_statement) { + array.push(the_statement); + if (the_statement.disrupt) { + disruptor = the_statement; + array.disrupt = true; + } + } + } + } + return array; + } + + + function block(ordinary) { + +// array block is array sequence of statements wrapped in braces. +// ordinary is false for function bodies and try blocks. +// ordinary is true for if statements, while, etc. + + var array, + curly = next_token, + old_in_block = in_block, + old_scope = scope, + old_strict_mode = strict_mode; + + in_block = ordinary; + scope = Object.create(scope); + spaces(); + if (next_token.id === '{') { + advance('{'); + step_in(); + if (!ordinary && !use_strict() && !old_strict_mode && + !option.sloppy && funct['(context)'] === global_funct) { + warn('missing_use_strict'); + } + array = statements(); + strict_mode = old_strict_mode; + step_out('}', curly); + } else if (!ordinary) { + stop('expected_a_b', next_token, '{', artifact()); + } else { + warn('expected_a_b', next_token, '{', artifact()); + array = [statement()]; + array.disrupt = array[0].disrupt; + } + funct['(verb)'] = null; + scope = old_scope; + in_block = old_in_block; + if (ordinary && array.length === 0) { + warn('empty_block'); + } + return array; + } + + + function tally_property(name) { + if (option.properties && typeof property[name] !== 'number') { + warn('unexpected_property_a', token, name); + } + if (typeof property[name] === 'number') { + property[name] += 1; + } else { + property[name] = 1; + } + } + + +// ECMAScript parser + + syntax['(identifier)'] = { + id: '(identifier)', + lbp: 0, + identifier: true, + nud: function () { + var name = this.string, + variable = scope[name], + site, + writeable; + +// If the variable is not in scope, then we may have an undeclared variable. +// Check the predefined list. If it was predefined, create the global +// variable. + + if (typeof variable !== 'object') { + writeable = predefined[name]; + if (typeof writeable === 'boolean') { + global_scope[name] = variable = { + string: name, + writeable: writeable, + funct: global_funct + }; + global_funct[name] = 'var'; + +// But if the variable is not in scope, and is not predefined, and if we are not +// in the global scope, then we have an undefined variable error. + + } else { + if (!option.undef) { + warn('used_before_a', token); + } + scope[name] = variable = { + string: name, + writeable: true, + funct: funct + }; + funct[name] = 'undef'; + } + + } + site = variable.funct; + +// The name is in scope and defined in the current function. + + if (funct === site) { + +// Change 'unused' to 'var', and reject labels. + + switch (funct[name]) { + case 'becoming': + warn('unexpected_a', token); + funct[name] = 'var'; + break; + case 'unused': + funct[name] = 'var'; + break; + case 'unparam': + funct[name] = 'parameter'; + break; + case 'unction': + funct[name] = 'function'; + break; + case 'label': + warn('a_label', token, name); + break; + } + +// If the name is already defined in the current +// function, but not as outer, then there is a scope error. + + } else { + switch (funct[name]) { + case 'closure': + case 'function': + case 'var': + case 'unused': + warn('a_scope', token, name); + break; + case 'label': + warn('a_label', token, name); + break; + case 'outer': + case 'global': + break; + default: + +// If the name is defined in an outer function, make an outer entry, and if +// it was unused, make it var. + + switch (site[name]) { + case 'becoming': + case 'closure': + case 'function': + case 'parameter': + case 'unction': + case 'unused': + case 'var': + site[name] = 'closure'; + funct[name] = site === global_funct + ? 'global' + : 'outer'; + break; + case 'unparam': + site[name] = 'parameter'; + funct[name] = 'outer'; + break; + case 'undef': + funct[name] = 'undef'; + break; + case 'label': + warn('a_label', token, name); + break; + } + } + } + return this; + }, + led: function () { + stop('expected_operator_a'); + } + }; + +// Build the syntax table by declaring the syntactic elements. + + type('(array)', 'array'); + type('(color)', 'color'); + type('(function)', 'function'); + type('(number)', 'number', return_this); + type('(object)', 'object'); + type('(string)', 'string', return_this); + type('(boolean)', 'boolean', return_this); + type('(range)', 'range'); + type('(regexp)', 'regexp', return_this); + + ultimate('(begin)'); + ultimate('(end)'); + ultimate('(error)'); + postscript(symbol(''); + postscript(symbol('}')); + symbol(')'); + symbol(']'); + postscript(symbol('"')); + postscript(symbol('\'')); + symbol(';'); + symbol(':'); + symbol(','); + symbol('#'); + symbol('@'); + symbol('*/'); + postscript(reserve('case')); + reserve('catch'); + postscript(reserve('default')); + reserve('else'); + reserve('finally'); + + reservevar('arguments', function (x) { + if (strict_mode && funct === global_funct) { + warn('strict', x); + } else if (option.safe) { + warn('adsafe_a', x); + } + funct['(arguments)'] = true; + }); + reservevar('eval', function (x) { + if (option.safe) { + warn('adsafe_a', x); + } + }); + constant('false', 'boolean'); + constant('Infinity', 'number'); + constant('NaN', 'number'); + constant('null', ''); + reservevar('this', function (x) { + if (option.safe) { + warn('adsafe_a', x); + } else if (strict_mode && funct['(token)'].arity === 'statement' && + funct['(name)'].charAt(0) > 'Z') { + warn('strict', x); + } + }); + constant('true', 'boolean'); + constant('undefined', ''); + + infix('?', 30, function (left, that) { + step_in('?'); + that.first = expected_condition(expected_relation(left)); + that.second = expression(0); + spaces(); + step_out(); + var colon = next_token; + advance(':'); + step_in(':'); + spaces(); + that.third = expression(10); + that.arity = 'ternary'; + if (are_similar(that.second, that.third)) { + warn('weird_ternary', colon); + } else if (are_similar(that.first, that.second)) { + warn('use_or', that); + } + step_out(); + return that; + }); + + infix('||', 40, function (left, that) { + function paren_check(that) { + if (that.id === '&&' && !that.paren) { + warn('and', that); + } + return that; + } + + that.first = paren_check(expected_condition(expected_relation(left))); + that.second = paren_check(expected_relation(expression(40))); + if (are_similar(that.first, that.second)) { + warn('weird_condition', that); + } + return that; + }); + + infix('&&', 50, function (left, that) { + that.first = expected_condition(expected_relation(left)); + that.second = expected_relation(expression(50)); + if (are_similar(that.first, that.second)) { + warn('weird_condition', that); + } + return that; + }); + + prefix('void', function () { + this.first = expression(0); + this.arity = 'prefix'; + if (option.es5) { + warn('expected_a_b', this, 'undefined', 'void'); + } else if (this.first.number !== 0) { + warn('expected_a_b', this.first, '0', artifact(this.first)); + } + return this; + }); + + bitwise('|', 70); + bitwise('^', 80); + bitwise('&', 90); + + relation('==', '==='); + relation('==='); + relation('!=', '!=='); + relation('!=='); + relation('<'); + relation('>'); + relation('<='); + relation('>='); + + bitwise('<<', 120); + bitwise('>>', 120); + bitwise('>>>', 120); + + infix('in', 120, function (left, that) { + warn('infix_in', that); + that.left = left; + that.right = expression(130); + return that; + }); + infix('instanceof', 120); + infix('+', 130, function (left, that) { + if (left.id === '(number)') { + if (left.number === 0) { + warn('unexpected_a', left, '0'); + } + } else if (left.id === '(string)') { + if (left.string === '') { + warn('expected_a_b', left, 'String', '\'\''); + } + } + var right = expression(130); + if (right.id === '(number)') { + if (right.number === 0) { + warn('unexpected_a', right, '0'); + } + } else if (right.id === '(string)') { + if (right.string === '') { + warn('expected_a_b', right, 'String', '\'\''); + } + } + if (left.id === right.id) { + if (left.id === '(string)' || left.id === '(number)') { + if (left.id === '(string)') { + left.string += right.string; + if (jx.test(left.string)) { + warn('url', left); + } + } else { + left.number += right.number; + } + left.thru = right.thru; + return left; + } + } + that.first = left; + that.second = right; + return that; + }); + prefix('+', 'num'); + prefix('+++', function () { + warn('confusing_a', token); + this.first = expression(150); + this.arity = 'prefix'; + return this; + }); + infix('+++', 130, function (left) { + warn('confusing_a', token); + this.first = left; + this.second = expression(130); + return this; + }); + infix('-', 130, function (left, that) { + if ((left.id === '(number)' && left.number === 0) || left.id === '(string)') { + warn('unexpected_a', left); + } + var right = expression(130); + if ((right.id === '(number)' && right.number === 0) || right.id === '(string)') { + warn('unexpected_a', right); + } + if (left.id === right.id && left.id === '(number)') { + left.number -= right.number; + left.thru = right.thru; + return left; + } + that.first = left; + that.second = right; + return that; + }); + prefix('-'); + prefix('---', function () { + warn('confusing_a', token); + this.first = expression(150); + this.arity = 'prefix'; + return this; + }); + infix('---', 130, function (left) { + warn('confusing_a', token); + this.first = left; + this.second = expression(130); + return this; + }); + infix('*', 140, function (left, that) { + if ((left.id === '(number)' && (left.number === 0 || left.number === 1)) || left.id === '(string)') { + warn('unexpected_a', left); + } + var right = expression(140); + if ((right.id === '(number)' && (right.number === 0 || right.number === 1)) || right.id === '(string)') { + warn('unexpected_a', right); + } + if (left.id === right.id && left.id === '(number)') { + left.number *= right.number; + left.thru = right.thru; + return left; + } + that.first = left; + that.second = right; + return that; + }); + infix('/', 140, function (left, that) { + if ((left.id === '(number)' && left.number === 0) || left.id === '(string)') { + warn('unexpected_a', left); + } + var right = expression(140); + if ((right.id === '(number)' && (right.number === 0 || right.number === 1)) || right.id === '(string)') { + warn('unexpected_a', right); + } + if (left.id === right.id && left.id === '(number)') { + left.number /= right.number; + left.thru = right.thru; + return left; + } + that.first = left; + that.second = right; + return that; + }); + infix('%', 140, function (left, that) { + if ((left.id === '(number)' && (left.number === 0 || left.number === 1)) || left.id === '(string)') { + warn('unexpected_a', left); + } + var right = expression(140); + if ((right.id === '(number)' && right.number === 0) || right.id === '(string)') { + warn('unexpected_a', right); + } + if (left.id === right.id && left.id === '(number)') { + left.number %= right.number; + left.thru = right.thru; + return left; + } + that.first = left; + that.second = right; + return that; + }); + + suffix('++'); + prefix('++'); + + suffix('--'); + prefix('--'); + prefix('delete', function () { + one_space(); + var p = expression(0); + if (!p || (p.id !== '.' && p.id !== '[')) { + warn('deleted'); + } + this.first = p; + return this; + }); + + + prefix('~', function () { + no_space_only(); + if (!option.bitwise) { + warn('unexpected_a', this); + } + expression(150); + return this; + }); + prefix('!', function () { + no_space_only(); + this.first = expected_condition(expression(150)); + this.arity = 'prefix'; + if (bang[this.first.id] === true || this.first.assign) { + warn('confusing_a', this); + } + return this; + }); + prefix('typeof', null); + prefix('new', function () { + one_space(); + var c = expression(160), n, p, v; + this.first = c; + if (c.id !== 'function') { + if (c.identifier) { + switch (c.string) { + case 'Object': + warn('use_object', token); + break; + case 'Array': + if (next_token.id === '(') { + p = next_token; + p.first = this; + advance('('); + if (next_token.id !== ')') { + n = expression(0); + p.second = [n]; + if (n.id !== '(number)' || next_token.id === ',') { + warn('use_array', p); + } + while (next_token.id === ',') { + advance(','); + p.second.push(expression(0)); + } + } else { + warn('use_array', token); + } + advance(')', p); + return p; + } + warn('use_array', token); + break; + case 'Number': + case 'String': + case 'Boolean': + case 'Math': + case 'JSON': + warn('not_a_constructor', c); + break; + case 'Function': + if (!option.evil) { + warn('function_eval'); + } + break; + case 'Date': + case 'RegExp': + case 'this': + break; + default: + if (c.id !== 'function') { + v = c.string.charAt(0); + if (!option.newcap && (v < 'A' || v > 'Z')) { + warn('constructor_name_a', token); + } + } + } + } else { + if (c.id !== '.' && c.id !== '[' && c.id !== '(') { + warn('bad_constructor', token); + } + } + } else { + warn('weird_new', this); + } + if (next_token.id !== '(') { + warn('missing_a', next_token, '()'); + } + return this; + }); + + infix('(', 160, function (left, that) { + var p; + if (indent && indent.mode === 'expression') { + no_space(prev_token, token); + } else { + no_space_only(prev_token, token); + } + if (!left.immed && left.id === 'function') { + warn('wrap_immediate'); + } + p = []; + if (left.identifier) { + if (left.string.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { + if (left.string !== 'Number' && left.string !== 'String' && + left.string !== 'Boolean' && left.string !== 'Date') { + if (left.string === 'Math' || left.string === 'JSON') { + warn('not_a_function', left); + } else if (left.string === 'Object') { + warn('use_object', token); + } else if (left.string === 'Array' || !option.newcap) { + warn('missing_a', left, 'new'); + } + } + } + } else if (left.id === '.') { + if (option.safe && left.first.string === 'Math' && + left.second === 'random') { + warn('adsafe_a', left); + } else if (left.second.string === 'split' && + left.first.id === '(string)') { + warn('use_array', left.second); + } + } + step_in(); + if (next_token.id !== ')') { + no_space(); + for (;;) { + edge(); + p.push(expression(10)); + if (next_token.id !== ',') { + break; + } + comma(); + } + } + no_space(); + step_out(')', that); + if (typeof left === 'object') { + if (left.string === 'parseInt' && p.length === 1) { + warn('radix', left); + } + if (!option.evil) { + if (left.string === 'eval' || left.string === 'Function' || + left.string === 'execScript') { + warn('evil', left); + } else if (p[0] && p[0].id === '(string)' && + (left.string === 'setTimeout' || + left.string === 'setInterval')) { + warn('implied_evil', left); + } + } + if (!left.identifier && left.id !== '.' && left.id !== '[' && + left.id !== '(' && left.id !== '&&' && left.id !== '||' && + left.id !== '?') { + warn('bad_invocation', left); + } + } + that.first = left; + that.second = p; + return that; + }, true); + + prefix('(', function () { + step_in('expression'); + no_space(); + edge(); + if (next_token.id === 'function') { + next_token.immed = true; + } + var value = expression(0); + value.paren = true; + no_space(); + step_out(')', this); + if (value.id === 'function') { + switch (next_token.id) { + case '(': + warn('move_invocation'); + break; + case '.': + case '[': + warn('unexpected_a'); + break; + default: + warn('bad_wrap', this); + } + } + return value; + }); + + infix('.', 170, function (left, that) { + no_space(prev_token, token); + no_space(); + var name = identifier(); + if (typeof name === 'string') { + tally_property(name); + } + that.first = left; + that.second = token; + if (left && left.string === 'arguments' && + (name === 'callee' || name === 'caller')) { + warn('avoid_a', left, 'arguments.' + name); + } else if (!option.evil && left && left.string === 'document' && + (name === 'write' || name === 'writeln')) { + warn('write_is_wrong', left); + } else if (option.adsafe) { + if (!adsafe_top && left.string === 'ADSAFE') { + if (name === 'id' || name === 'lib') { + warn('adsafe_a', that); + } else if (name === 'go') { + if (xmode !== 'script') { + warn('adsafe_a', that); + } else if (adsafe_went || next_token.id !== '(' || + peek(0).id !== '(string)' || + peek(0).string !== adsafe_id || + peek(1).id !== ',') { + stop('adsafe_a', that, 'go'); + } + adsafe_went = true; + adsafe_may = false; + } + } + adsafe_top = false; + } + if (!option.evil && (name === 'eval' || name === 'execScript')) { + warn('evil'); + } else if (option.safe) { + for (;;) { + if (banned[name] === true) { + warn('adsafe_a', token, name); + } + if (typeof predefined[left.string] !== 'boolean' || //// check for writeable + next_token.id === '(') { + break; + } + if (next_token.id !== '.') { + warn('adsafe_a', that); + break; + } + advance('.'); + token.first = that; + token.second = name; + that = token; + name = identifier(); + if (typeof name === 'string') { + tally_property(name); + } + } + } + return that; + }, true); + + infix('[', 170, function (left, that) { + var e, s; + no_space_only(prev_token, token); + no_space(); + step_in(); + edge(); + e = expression(0); + switch (e.id) { + case '(number)': + if (e.id === '(number)' && left.id === 'arguments') { + warn('use_param', left); + } + break; + case '(string)': + if (option.safe && (banned[e.string] || + e.string.charAt(0) === '_' || e.string.slice(-1) === '_')) { + warn('adsafe_subscript_a', e); + } else if (!option.evil && + (e.string === 'eval' || e.string === 'execScript')) { + warn('evil', e); + } else if (!option.sub && ix.test(e.string)) { + s = syntax[e.string]; + if (!s || !s.reserved) { + warn('subscript', e); + } + } + tally_property(e.string); + break; + default: + if (option.safe) { + warn('adsafe_subscript_a', e); + } + } + step_out(']', that); + no_space(prev_token, token); + that.first = left; + that.second = e; + return that; + }, true); + + prefix('[', function () { + this.arity = 'prefix'; + this.first = []; + step_in('array'); + while (next_token.id !== '(end)') { + while (next_token.id === ',') { + warn('unexpected_a', next_token); + advance(','); + } + if (next_token.id === ']') { + break; + } + indent.wrap = false; + edge(); + this.first.push(expression(10)); + if (next_token.id === ',') { + comma(); + if (next_token.id === ']' && !option.es5) { + warn('unexpected_a', token); + break; + } + } else { + break; + } + } + step_out(']', this); + return this; + }, 170); + + + function property_name() { + var id = optional_identifier(true); + if (!id) { + if (next_token.id === '(string)') { + id = next_token.string; + if (option.safe) { + if (banned[id]) { + warn('adsafe_a'); + } else if (id.charAt(0) === '_' || + id.charAt(id.length - 1) === '_') { + warn('dangling_a'); + } + } + advance(); + } else if (next_token.id === '(number)') { + id = next_token.number.toString(); + advance(); + } + } + return id; + } + + + function function_params() { + var id, paren = next_token, params = []; + advance('('); + step_in(); + no_space(); + if (next_token.id === ')') { + no_space(); + step_out(')', paren); + return params; + } + for (;;) { + edge(); + id = identifier(); + params.push(token); + add_label(token, option.unparam ? 'parameter' : 'unparam'); + if (next_token.id === ',') { + comma(); + } else { + no_space(); + step_out(')', paren); + return params; + } + } + } + + + + function do_function(func, name) { + var old_funct = funct, + old_option = option, + old_scope = scope; + funct = { + '(name)' : name || '\'' + (anonname || '').replace(nx, sanitize) + '\'', + '(line)' : next_token.line, + '(context)' : old_funct, + '(breakage)' : 0, + '(loopage)' : 0, + '(scope)' : scope, + '(token)' : func + }; + option = Object.create(old_option); + scope = Object.create(old_scope); + functions.push(funct); + func.name = name; + if (name) { + add_label(func, 'function', name); + } + func.writeable = false; + func.first = funct['(params)'] = function_params(); + one_space(); + func.block = block(false); + if (funct['(arguments)']) { + func.first.forEach(function (value) { + if (value.assign) { + warn('parameter_arguments_a', value, value.string); + } + }); + } + funct = old_funct; + option = old_option; + scope = old_scope; + } + + + assignop('='); + assignop('+=', '+'); + assignop('-=', '-'); + assignop('*=', '*'); + assignop('/=', '/').nud = function () { + stop('slash_equal'); + }; + assignop('%=', '%'); + assignop('&=', '&'); + assignop('|=', '|'); + assignop('^=', '^'); + assignop('<<=', '<<'); + assignop('>>=', '>>'); + assignop('>>>=', '>>>'); + + + prefix('{', function () { + var get, i, j, name, p, set, seen = {}; + this.arity = 'prefix'; + this.first = []; + step_in(); + while (next_token.id !== '}') { + indent.wrap = false; + +// JSLint recognizes the ES5 extension for get/set in object literals, +// but requires that they be used in pairs. + + edge(); + if (next_token.string === 'get' && peek().id !== ':') { + if (!option.es5) { + warn('es5'); + } + get = next_token; + advance('get'); + one_space_only(); + name = next_token; + i = property_name(); + if (!i) { + stop('missing_property'); + } + get.string = ''; + do_function(get); + if (funct['(loopage)']) { + warn('function_loop', get); + } + p = get.first; + if (p) { + warn('parameter_a_get_b', p[0], p[0].string, i); + } + comma(); + set = next_token; + spaces(); + edge(); + advance('set'); + set.string = ''; + one_space_only(); + j = property_name(); + if (i !== j) { + stop('expected_a_b', token, i, j || next_token.string); + } + do_function(set); + if (set.block.length === 0) { + warn('missing_a', token, 'throw'); + } + p = set.first; + if (!p || p.length !== 1) { + stop('parameter_set_a', set, 'value'); + } else if (p[0].string !== 'value') { + stop('expected_a_b', p[0], 'value', p[0].string); + } + name.first = [get, set]; + } else { + name = next_token; + i = property_name(); + if (typeof i !== 'string') { + stop('missing_property'); + } + advance(':'); + spaces(); + name.first = expression(10); + } + this.first.push(name); + if (seen[i] === true) { + warn('duplicate_a', next_token, i); + } + seen[i] = true; + tally_property(i); + if (next_token.id !== ',') { + break; + } + for (;;) { + comma(); + if (next_token.id !== ',') { + break; + } + warn('unexpected_a', next_token); + } + if (next_token.id === '}' && !option.es5) { + warn('unexpected_a', token); + } + } + step_out('}', this); + return this; + }); + + stmt('{', function () { + warn('statement_block'); + this.arity = 'statement'; + this.block = statements(); + this.disrupt = this.block.disrupt; + advance('}', this); + return this; + }); + + stmt('/*global', directive); + stmt('/*globals', directive); + stmt('/*jslint', directive); + stmt('/*member', directive); + stmt('/*members', directive); + stmt('/*property', directive); + stmt('/*properties', directive); + + stmt('var', function () { + +// JavaScript does not have block scope. It only has function scope. So, +// declaring a variable in a block can have unexpected consequences. + +// var.first will contain an array, the array containing name tokens +// and assignment tokens. + + var assign, id, name; + + if (funct['(vars)'] && !option.vars) { + warn('combine_var'); + } else if (funct !== global_funct) { + funct['(vars)'] = true; + } + this.arity = 'statement'; + this.first = []; + step_in('var'); + for (;;) { + name = next_token; + id = identifier(); + add_label(name, 'becoming'); + + if (next_token.id === '=') { + assign = next_token; + assign.first = name; + spaces(); + advance('='); + spaces(); + if (next_token.id === 'undefined') { + warn('unnecessary_initialize', token, id); + } + if (peek(0).id === '=' && next_token.identifier) { + stop('var_a_not'); + } + assign.second = expression(0); + assign.arity = 'infix'; + this.first.push(assign); + } else { + this.first.push(name); + } + if (funct[id] === 'becoming') { + funct[id] = 'unused'; + } + if (next_token.id !== ',') { + break; + } + comma(); + indent.wrap = false; + if (var_mode && next_token.line === token.line && + this.first.length === 1) { + var_mode = null; + indent.open = false; + indent.at -= option.indent; + } + spaces(); + edge(); + } + var_mode = null; + step_out(); + return this; + }); + + stmt('function', function () { + one_space(); + if (in_block) { + warn('function_block', token); + } + var name = next_token, id = identifier(); + add_label(name, 'unction'); + no_space(); + this.arity = 'statement'; + do_function(this, id); + if (next_token.id === '(' && next_token.line === token.line) { + stop('function_statement'); + } + return this; + }); + + prefix('function', function () { + if (!option.anon) { + one_space(); + } + var id = optional_identifier(); + if (id) { + no_space(); + } else { + id = ''; + } + do_function(this, id); + if (funct['(loopage)']) { + warn('function_loop'); + } + switch (next_token.id) { + case ';': + case '(': + case ')': + case ',': + case ']': + case '}': + case ':': + break; + case '.': + if (peek().string !== 'bind' || peek(1).id !== '(') { + warn('unexpected_a'); + } + break; + default: + stop('unexpected_a'); + } + this.arity = 'function'; + return this; + }); + + stmt('if', function () { + var paren = next_token; + one_space(); + advance('('); + step_in('control'); + no_space(); + edge(); + this.arity = 'statement'; + this.first = expected_condition(expected_relation(expression(0))); + no_space(); + step_out(')', paren); + one_space(); + this.block = block(true); + if (next_token.id === 'else') { + one_space(); + advance('else'); + one_space(); + this['else'] = next_token.id === 'if' || next_token.id === 'switch' + ? statement(true) + : block(true); + if (this['else'].disrupt && this.block.disrupt) { + this.disrupt = true; + } + } + return this; + }); + + stmt('try', function () { + +// try.first The catch variable +// try.second The catch clause +// try.third The finally clause +// try.block The try block + + var exception_variable, old_scope, paren; + if (option.adsafe) { + warn('adsafe_a', this); + } + one_space(); + this.arity = 'statement'; + this.block = block(false); + if (next_token.id === 'catch') { + one_space(); + advance('catch'); + one_space(); + paren = next_token; + advance('('); + step_in('control'); + no_space(); + edge(); + old_scope = scope; + scope = Object.create(old_scope); + exception_variable = next_token.string; + this.first = exception_variable; + if (!next_token.identifier) { + warn('expected_identifier_a', next_token); + } else { + add_label(next_token, 'exception'); + } + advance(); + no_space(); + step_out(')', paren); + one_space(); + this.second = block(false); + scope = old_scope; + } + if (next_token.id === 'finally') { + one_space(); + advance('finally'); + one_space(); + this.third = block(false); + } else if (!this.second) { + stop('expected_a_b', next_token, 'catch', artifact()); + } + return this; + }); + + labeled_stmt('while', function () { + one_space(); + var paren = next_token; + funct['(breakage)'] += 1; + funct['(loopage)'] += 1; + advance('('); + step_in('control'); + no_space(); + edge(); + this.arity = 'statement'; + this.first = expected_relation(expression(0)); + if (this.first.id !== 'true') { + expected_condition(this.first, bundle.unexpected_a); + } + no_space(); + step_out(')', paren); + one_space(); + this.block = block(true); + if (this.block.disrupt) { + warn('strange_loop', prev_token); + } + funct['(breakage)'] -= 1; + funct['(loopage)'] -= 1; + return this; + }); + + reserve('with'); + + labeled_stmt('switch', function () { + +// switch.first the switch expression +// switch.second the array of cases. A case is 'case' or 'default' token: +// case.first the array of case expressions +// case.second the array of statements +// If all of the arrays of statements are disrupt, then the switch is disrupt. + + var cases = [], + old_in_block = in_block, + particular, + the_case = next_token, + unbroken = true; + + function find_duplicate_case(value) { + if (are_similar(particular, value)) { + warn('duplicate_a', value); + } + } + + funct['(breakage)'] += 1; + one_space(); + advance('('); + no_space(); + step_in(); + this.arity = 'statement'; + this.first = expected_condition(expected_relation(expression(0))); + no_space(); + step_out(')', the_case); + one_space(); + advance('{'); + step_in(); + in_block = true; + this.second = []; + while (next_token.id === 'case') { + the_case = next_token; + cases.forEach(find_duplicate_case); + the_case.first = []; + the_case.arity = 'case'; + spaces(); + edge('case'); + advance('case'); + for (;;) { + one_space(); + particular = expression(0); + cases.forEach(find_duplicate_case); + cases.push(particular); + the_case.first.push(particular); + if (particular.id === 'NaN') { + warn('unexpected_a', particular); + } + no_space_only(); + advance(':'); + if (next_token.id !== 'case') { + break; + } + spaces(); + edge('case'); + advance('case'); + } + spaces(); + the_case.second = statements(); + if (the_case.second && the_case.second.length > 0) { + particular = the_case.second[the_case.second.length - 1]; + if (particular.disrupt) { + if (particular.id === 'break') { + unbroken = false; + } + } else { + warn('missing_a_after_b', next_token, 'break', 'case'); + } + } else { + warn('empty_case'); + } + this.second.push(the_case); + } + if (this.second.length === 0) { + warn('missing_a', next_token, 'case'); + } + if (next_token.id === 'default') { + spaces(); + the_case = next_token; + the_case.arity = 'case'; + edge('case'); + advance('default'); + no_space_only(); + advance(':'); + spaces(); + the_case.second = statements(); + if (the_case.second && the_case.second.length > 0) { + particular = the_case.second[the_case.second.length - 1]; + if (unbroken && particular.disrupt && particular.id !== 'break') { + this.disrupt = true; + } + } + this.second.push(the_case); + } + funct['(breakage)'] -= 1; + spaces(); + step_out('}', this); + in_block = old_in_block; + return this; + }); + + stmt('debugger', function () { + if (!option.debug) { + warn('unexpected_a', this); + } + this.arity = 'statement'; + return this; + }); + + labeled_stmt('do', function () { + funct['(breakage)'] += 1; + funct['(loopage)'] += 1; + one_space(); + this.arity = 'statement'; + this.block = block(true); + if (this.block.disrupt) { + warn('strange_loop', prev_token); + } + one_space(); + advance('while'); + var paren = next_token; + one_space(); + advance('('); + step_in(); + no_space(); + edge(); + this.first = expected_condition(expected_relation(expression(0)), bundle.unexpected_a); + no_space(); + step_out(')', paren); + funct['(breakage)'] -= 1; + funct['(loopage)'] -= 1; + return this; + }); + + labeled_stmt('for', function () { + + var blok, filter, ok = false, paren = next_token, value; + this.arity = 'statement'; + funct['(breakage)'] += 1; + funct['(loopage)'] += 1; + advance('('); + if (next_token.id === ';') { + no_space(); + advance(';'); + no_space(); + advance(';'); + no_space(); + advance(')'); + blok = block(true); + } else { + step_in('control'); + spaces(this, paren); + no_space(); + if (next_token.id === 'var') { + stop('move_var'); + } + edge(); + if (peek(0).id === 'in') { + this.forin = true; + value = next_token; + switch (funct[value.string]) { + case 'unused': + funct[value.string] = 'var'; + break; + case 'closure': + case 'var': + break; + default: + warn('bad_in_a', value); + } + advance(); + advance('in'); + this.first = value; + this.second = expression(20); + step_out(')', paren); + blok = block(true); + if (!option.forin) { + if (blok.length === 1 && typeof blok[0] === 'object' && + blok[0].string === 'if' && !blok[0]['else']) { + filter = blok[0].first; + while (filter.id === '&&') { + filter = filter.first; + } + switch (filter.id) { + case '===': + case '!==': + ok = filter.first.id === '[' + ? filter.first.first.string === this.second.string && + filter.first.second.string === this.first.string + : filter.first.id === 'typeof' && + filter.first.first.id === '[' && + filter.first.first.first.string === this.second.string && + filter.first.first.second.string === this.first.string; + break; + case '(': + ok = filter.first.id === '.' && (( + filter.first.first.string === this.second.string && + filter.first.second.string === 'hasOwnProperty' && + filter.second[0].string === this.first.string + ) || ( + filter.first.first.string === 'ADSAFE' && + filter.first.second.string === 'has' && + filter.second[0].string === this.second.string && + filter.second[1].string === this.first.string + ) || ( + filter.first.first.id === '.' && + filter.first.first.first.id === '.' && + filter.first.first.first.first.string === 'Object' && + filter.first.first.first.second.string === 'prototype' && + filter.first.first.second.string === 'hasOwnProperty' && + filter.first.second.string === 'call' && + filter.second[0].string === this.second.string && + filter.second[1].string === this.first.string + )); + break; + } + } + if (!ok) { + warn('for_if', this); + } + } + } else { + edge(); + this.first = []; + for (;;) { + this.first.push(expression(0, 'for')); + if (next_token.id !== ',') { + break; + } + comma(); + } + semicolon(); + edge(); + this.second = expected_relation(expression(0)); + if (this.second.id !== 'true') { + expected_condition(this.second, bundle.unexpected_a); + } + semicolon(token); + if (next_token.id === ';') { + stop('expected_a_b', next_token, ')', ';'); + } + this.third = []; + edge(); + for (;;) { + this.third.push(expression(0, 'for')); + if (next_token.id !== ',') { + break; + } + comma(); + } + no_space(); + step_out(')', paren); + one_space(); + blok = block(true); + } + } + if (blok.disrupt) { + warn('strange_loop', prev_token); + } + this.block = blok; + funct['(breakage)'] -= 1; + funct['(loopage)'] -= 1; + return this; + }); + + disrupt_stmt('break', function () { + var label = next_token.string; + this.arity = 'statement'; + if (funct['(breakage)'] === 0) { + warn('unexpected_a', this); + } + if (next_token.identifier && token.line === next_token.line) { + one_space_only(); + if (funct[label] !== 'label') { + warn('not_a_label', next_token); + } else if (scope[label].funct !== funct) { + warn('not_a_scope', next_token); + } + this.first = next_token; + advance(); + } + return this; + }); + + disrupt_stmt('continue', function () { + if (!option['continue']) { + warn('unexpected_a', this); + } + var label = next_token.string; + this.arity = 'statement'; + if (funct['(breakage)'] === 0) { + warn('unexpected_a', this); + } + if (next_token.identifier && token.line === next_token.line) { + one_space_only(); + if (funct[label] !== 'label') { + warn('not_a_label', next_token); + } else if (scope[label].funct !== funct) { + warn('not_a_scope', next_token); + } + this.first = next_token; + advance(); + } + return this; + }); + + disrupt_stmt('return', function () { + if (funct === global_funct && xmode !== 'scriptstring') { + warn('unexpected_a', this); + } + this.arity = 'statement'; + if (next_token.id !== ';' && next_token.line === token.line) { + one_space_only(); + if (next_token.id === '/' || next_token.id === '(regexp)') { + warn('wrap_regexp'); + } + this.first = expression(20); + } + if (peek(0).id === '}' && peek(1).id === 'else') { + warn('unexpected_else', this); + } + return this; + }); + + disrupt_stmt('throw', function () { + this.arity = 'statement'; + one_space_only(); + this.first = expression(20); + return this; + }); + + +// Superfluous reserved words + + reserve('class'); + reserve('const'); + reserve('enum'); + reserve('export'); + reserve('extends'); + reserve('import'); + reserve('super'); + +// Harmony reserved words + + reserve('implements'); + reserve('interface'); + reserve('let'); + reserve('package'); + reserve('private'); + reserve('protected'); + reserve('public'); + reserve('static'); + reserve('yield'); + + +// Parse JSON + + function json_value() { + + function json_object() { + var brace = next_token, object = {}; + advance('{'); + if (next_token.id !== '}') { + while (next_token.id !== '(end)') { + while (next_token.id === ',') { + warn('unexpected_a', next_token); + advance(','); + } + if (next_token.id !== '(string)') { + warn('expected_string_a'); + } + if (object[next_token.string] === true) { + warn('duplicate_a'); + } else if (next_token.string === '__proto__') { + warn('dangling_a'); + } else { + object[next_token.string] = true; + } + advance(); + advance(':'); + json_value(); + if (next_token.id !== ',') { + break; + } + advance(','); + if (next_token.id === '}') { + warn('unexpected_a', token); + break; + } + } + } + advance('}', brace); + } + + function json_array() { + var bracket = next_token; + advance('['); + if (next_token.id !== ']') { + while (next_token.id !== '(end)') { + while (next_token.id === ',') { + warn('unexpected_a', next_token); + advance(','); + } + json_value(); + if (next_token.id !== ',') { + break; + } + advance(','); + if (next_token.id === ']') { + warn('unexpected_a', token); + break; + } + } + } + advance(']', bracket); + } + + switch (next_token.id) { + case '{': + json_object(); + break; + case '[': + json_array(); + break; + case 'true': + case 'false': + case 'null': + case '(number)': + case '(string)': + advance(); + break; + case '-': + advance('-'); + no_space_only(); + advance('(number)'); + break; + default: + stop('unexpected_a'); + } + } + + +// CSS parsing. + + function css_name() { + if (next_token.identifier) { + advance(); + return true; + } + } + + + function css_number() { + if (next_token.id === '-') { + advance('-'); + no_space_only(); + } + if (next_token.id === '(number)') { + advance('(number)'); + return true; + } + } + + + function css_string() { + if (next_token.id === '(string)') { + advance(); + return true; + } + } + + function css_color() { + var i, number, paren, value; + if (next_token.identifier) { + value = next_token.string; + if (value === 'rgb' || value === 'rgba') { + advance(); + paren = next_token; + advance('('); + for (i = 0; i < 3; i += 1) { + if (i) { + comma(); + } + number = next_token.number; + if (next_token.id !== '(number)' || number < 0) { + warn('expected_positive_a', next_token); + advance(); + } else { + advance(); + if (next_token.id === '%') { + advance('%'); + if (number > 100) { + warn('expected_percent_a', token, number); + } + } else { + if (number > 255) { + warn('expected_small_a', token, number); + } + } + } + } + if (value === 'rgba') { + comma(); + number = next_token.number; + if (next_token.id !== '(number)' || number < 0 || number > 1) { + warn('expected_fraction_a', next_token); + } + advance(); + if (next_token.id === '%') { + warn('unexpected_a'); + advance('%'); + } + } + advance(')', paren); + return true; + } + if (css_colorData[next_token.string] === true) { + advance(); + return true; + } + } else if (next_token.id === '(color)') { + advance(); + return true; + } + return false; + } + + + function css_length() { + if (next_token.id === '-') { + advance('-'); + no_space_only(); + } + if (next_token.id === '(number)') { + advance(); + if (next_token.id !== '(string)' && + css_lengthData[next_token.string] === true) { + no_space_only(); + advance(); + } else if (+token.number !== 0) { + warn('expected_linear_a'); + } + return true; + } + return false; + } + + + function css_line_height() { + if (next_token.id === '-') { + advance('-'); + no_space_only(); + } + if (next_token.id === '(number)') { + advance(); + if (next_token.id !== '(string)' && + css_lengthData[next_token.string] === true) { + no_space_only(); + advance(); + } + return true; + } + return false; + } + + + function css_width() { + if (next_token.identifier) { + switch (next_token.string) { + case 'thin': + case 'medium': + case 'thick': + advance(); + return true; + } + } else { + return css_length(); + } + } + + + function css_margin() { + if (next_token.identifier) { + if (next_token.string === 'auto') { + advance(); + return true; + } + } else { + return css_length(); + } + } + + function css_attr() { + if (next_token.identifier && next_token.string === 'attr') { + advance(); + advance('('); + if (!next_token.identifier) { + warn('expected_name_a'); + } + advance(); + advance(')'); + return true; + } + return false; + } + + + function css_comma_list() { + while (next_token.id !== ';') { + if (!css_name() && !css_string()) { + warn('expected_name_a'); + } + if (next_token.id !== ',') { + return true; + } + comma(); + } + } + + + function css_counter() { + if (next_token.identifier && next_token.string === 'counter') { + advance(); + advance('('); + advance(); + if (next_token.id === ',') { + comma(); + if (next_token.id !== '(string)') { + warn('expected_string_a'); + } + advance(); + } + advance(')'); + return true; + } + if (next_token.identifier && next_token.string === 'counters') { + advance(); + advance('('); + if (!next_token.identifier) { + warn('expected_name_a'); + } + advance(); + if (next_token.id === ',') { + comma(); + if (next_token.id !== '(string)') { + warn('expected_string_a'); + } + advance(); + } + if (next_token.id === ',') { + comma(); + if (next_token.id !== '(string)') { + warn('expected_string_a'); + } + advance(); + } + advance(')'); + return true; + } + return false; + } + + + function css_radius() { + return css_length() && (next_token.id !== '(number)' || css_length()); + } + + + function css_shape() { + var i; + if (next_token.identifier && next_token.string === 'rect') { + advance(); + advance('('); + for (i = 0; i < 4; i += 1) { + if (!css_length()) { + warn('expected_number_a'); + break; + } + } + advance(')'); + return true; + } + return false; + } + + + function css_url() { + var c, url; + if (next_token.identifier && next_token.string === 'url') { + next_token = lex.range('(', ')'); + url = next_token.string; + c = url.charAt(0); + if (c === '"' || c === '\'') { + if (url.slice(-1) !== c) { + warn('bad_url_a'); + } else { + url = url.slice(1, -1); + if (url.indexOf(c) >= 0) { + warn('bad_url_a'); + } + } + } + if (!url) { + warn('missing_url'); + } + if (ux.test(url)) { + stop('bad_url_a'); + } + urls.push(url); + advance(); + return true; + } + return false; + } + + + css_any = [css_url, function () { + for (;;) { + if (next_token.identifier) { + switch (next_token.string.toLowerCase()) { + case 'url': + css_url(); + break; + case 'expression': + warn('unexpected_a'); + advance(); + break; + default: + advance(); + } + } else { + if (next_token.id === ';' || next_token.id === '!' || + next_token.id === '(end)' || next_token.id === '}') { + return true; + } + advance(); + } + } + }]; + + + function font_face() { + advance_identifier('font-family'); + advance(':'); + if (!css_name() && !css_string()) { + stop('expected_name_a'); + } + semicolon(); + advance_identifier('src'); + advance(':'); + while (true) { + if (next_token.string === 'local') { + advance_identifier('local'); + advance('('); + if (ux.test(next_token.string)) { + stop('bad_url_a'); + } + + if (!css_name() && !css_string()) { + stop('expected_name_a'); + } + advance(')'); + } else if (!css_url()) { + stop('expected_a_b', next_token, 'url', artifact()); + } + if (next_token.id !== ',') { + break; + } + comma(); + } + semicolon(); + } + + + css_border_style = [ + 'none', 'dashed', 'dotted', 'double', 'groove', + 'hidden', 'inset', 'outset', 'ridge', 'solid' + ]; + + css_break = [ + 'auto', 'always', 'avoid', 'left', 'right' + ]; + + css_media = { + 'all': true, + 'braille': true, + 'embossed': true, + 'handheld': true, + 'print': true, + 'projection': true, + 'screen': true, + 'speech': true, + 'tty': true, + 'tv': true + }; + + css_overflow = [ + 'auto', 'hidden', 'scroll', 'visible' + ]; + + css_attribute_data = { + background: [ + true, 'background-attachment', 'background-color', + 'background-image', 'background-position', 'background-repeat' + ], + 'background-attachment': ['scroll', 'fixed'], + 'background-color': ['transparent', css_color], + 'background-image': ['none', css_url], + 'background-position': [ + 2, [css_length, 'top', 'bottom', 'left', 'right', 'center'] + ], + 'background-repeat': [ + 'repeat', 'repeat-x', 'repeat-y', 'no-repeat' + ], + 'border': [true, 'border-color', 'border-style', 'border-width'], + 'border-bottom': [ + true, 'border-bottom-color', 'border-bottom-style', + 'border-bottom-width' + ], + 'border-bottom-color': css_color, + 'border-bottom-left-radius': css_radius, + 'border-bottom-right-radius': css_radius, + 'border-bottom-style': css_border_style, + 'border-bottom-width': css_width, + 'border-collapse': ['collapse', 'separate'], + 'border-color': ['transparent', 4, css_color], + 'border-left': [ + true, 'border-left-color', 'border-left-style', 'border-left-width' + ], + 'border-left-color': css_color, + 'border-left-style': css_border_style, + 'border-left-width': css_width, + 'border-radius': function () { + function count(separator) { + var n = 1; + if (separator) { + advance(separator); + } + if (!css_length()) { + return false; + } + while (next_token.id === '(number)') { + if (!css_length()) { + return false; + } + n += 1; + } + if (n > 4) { + warn('bad_style'); + } + return true; + } + + return count() && (next_token.id !== '/' || count('/')); + }, + 'border-right': [ + true, 'border-right-color', 'border-right-style', + 'border-right-width' + ], + 'border-right-color': css_color, + 'border-right-style': css_border_style, + 'border-right-width': css_width, + 'border-spacing': [2, css_length], + 'border-style': [4, css_border_style], + 'border-top': [ + true, 'border-top-color', 'border-top-style', 'border-top-width' + ], + 'border-top-color': css_color, + 'border-top-left-radius': css_radius, + 'border-top-right-radius': css_radius, + 'border-top-style': css_border_style, + 'border-top-width': css_width, + 'border-width': [4, css_width], + bottom: [css_length, 'auto'], + 'caption-side' : ['bottom', 'left', 'right', 'top'], + clear: ['both', 'left', 'none', 'right'], + clip: [css_shape, 'auto'], + color: css_color, + content: [ + 'open-quote', 'close-quote', 'no-open-quote', 'no-close-quote', + css_string, css_url, css_counter, css_attr + ], + 'counter-increment': [ + css_name, 'none' + ], + 'counter-reset': [ + css_name, 'none' + ], + cursor: [ + css_url, 'auto', 'crosshair', 'default', 'e-resize', 'help', 'move', + 'n-resize', 'ne-resize', 'nw-resize', 'pointer', 's-resize', + 'se-resize', 'sw-resize', 'w-resize', 'text', 'wait' + ], + direction: ['ltr', 'rtl'], + display: [ + 'block', 'compact', 'inline', 'inline-block', 'inline-table', + 'list-item', 'marker', 'none', 'run-in', 'table', 'table-caption', + 'table-cell', 'table-column', 'table-column-group', + 'table-footer-group', 'table-header-group', 'table-row', + 'table-row-group' + ], + 'empty-cells': ['show', 'hide'], + 'float': ['left', 'none', 'right'], + font: [ + 'caption', 'icon', 'menu', 'message-box', 'small-caption', + 'status-bar', true, 'font-size', 'font-style', 'font-weight', + 'font-family' + ], + 'font-family': css_comma_list, + 'font-size': [ + 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', + 'xx-large', 'larger', 'smaller', css_length + ], + 'font-size-adjust': ['none', css_number], + 'font-stretch': [ + 'normal', 'wider', 'narrower', 'ultra-condensed', + 'extra-condensed', 'condensed', 'semi-condensed', + 'semi-expanded', 'expanded', 'extra-expanded' + ], + 'font-style': [ + 'normal', 'italic', 'oblique' + ], + 'font-variant': [ + 'normal', 'small-caps' + ], + 'font-weight': [ + 'normal', 'bold', 'bolder', 'lighter', css_number + ], + height: [css_length, 'auto'], + left: [css_length, 'auto'], + 'letter-spacing': ['normal', css_length], + 'line-height': ['normal', css_line_height], + 'list-style': [ + true, 'list-style-image', 'list-style-position', 'list-style-type' + ], + 'list-style-image': ['none', css_url], + 'list-style-position': ['inside', 'outside'], + 'list-style-type': [ + 'circle', 'disc', 'square', 'decimal', 'decimal-leading-zero', + 'lower-roman', 'upper-roman', 'lower-greek', 'lower-alpha', + 'lower-latin', 'upper-alpha', 'upper-latin', 'hebrew', 'katakana', + 'hiragana-iroha', 'katakana-oroha', 'none' + ], + margin: [4, css_margin], + 'margin-bottom': css_margin, + 'margin-left': css_margin, + 'margin-right': css_margin, + 'margin-top': css_margin, + 'marker-offset': [css_length, 'auto'], + 'max-height': [css_length, 'none'], + 'max-width': [css_length, 'none'], + 'min-height': css_length, + 'min-width': css_length, + opacity: css_number, + outline: [true, 'outline-color', 'outline-style', 'outline-width'], + 'outline-color': ['invert', css_color], + 'outline-style': [ + 'dashed', 'dotted', 'double', 'groove', 'inset', 'none', + 'outset', 'ridge', 'solid' + ], + 'outline-width': css_width, + overflow: css_overflow, + 'overflow-x': css_overflow, + 'overflow-y': css_overflow, + padding: [4, css_length], + 'padding-bottom': css_length, + 'padding-left': css_length, + 'padding-right': css_length, + 'padding-top': css_length, + 'page-break-after': css_break, + 'page-break-before': css_break, + position: ['absolute', 'fixed', 'relative', 'static'], + quotes: [8, css_string], + right: [css_length, 'auto'], + 'table-layout': ['auto', 'fixed'], + 'text-align': ['center', 'justify', 'left', 'right'], + 'text-decoration': [ + 'none', 'underline', 'overline', 'line-through', 'blink' + ], + 'text-indent': css_length, + 'text-shadow': ['none', 4, [css_color, css_length]], + 'text-transform': ['capitalize', 'uppercase', 'lowercase', 'none'], + top: [css_length, 'auto'], + 'unicode-bidi': ['normal', 'embed', 'bidi-override'], + 'vertical-align': [ + 'baseline', 'bottom', 'sub', 'super', 'top', 'text-top', 'middle', + 'text-bottom', css_length + ], + visibility: ['visible', 'hidden', 'collapse'], + 'white-space': [ + 'normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap', 'inherit' + ], + width: [css_length, 'auto'], + 'word-spacing': ['normal', css_length], + 'word-wrap': ['break-word', 'normal'], + 'z-index': ['auto', css_number] + }; + + function style_attribute() { + var v; + while (next_token.id === '*' || next_token.id === '#' || + next_token.string === '_') { + if (!option.css) { + warn('unexpected_a'); + } + advance(); + } + if (next_token.id === '-') { + if (!option.css) { + warn('unexpected_a'); + } + advance('-'); + if (!next_token.identifier) { + warn('expected_nonstandard_style_attribute'); + } + advance(); + return css_any; + } + if (!next_token.identifier) { + warn('expected_style_attribute'); + } else { + if (Object.prototype.hasOwnProperty.call(css_attribute_data, + next_token.string)) { + v = css_attribute_data[next_token.string]; + } else { + v = css_any; + if (!option.css) { + warn('unrecognized_style_attribute_a'); + } + } + } + advance(); + return v; + } + + + function style_value(v) { + var i = 0, + n, + once, + match, + round, + start = 0, + vi; + switch (typeof v) { + case 'function': + return v(); + case 'string': + if (next_token.identifier && next_token.string === v) { + advance(); + return true; + } + return false; + } + for (;;) { + if (i >= v.length) { + return false; + } + vi = v[i]; + i += 1; + if (typeof vi === 'boolean') { + break; + } else if (typeof vi === 'number') { + n = vi; + vi = v[i]; + i += 1; + } else { + n = 1; + } + match = false; + while (n > 0) { + if (style_value(vi)) { + match = true; + n -= 1; + } else { + break; + } + } + if (match) { + return true; + } + } + start = i; + once = []; + for (;;) { + round = false; + for (i = start; i < v.length; i += 1) { + if (!once[i]) { + if (style_value(css_attribute_data[v[i]])) { + match = true; + round = true; + once[i] = true; + break; + } + } + } + if (!round) { + return match; + } + } + } + + function style_child() { + if (next_token.id === '(number)') { + advance(); + if (next_token.string === 'n' && next_token.identifier) { + no_space_only(); + advance(); + if (next_token.id === '+') { + no_space_only(); + advance('+'); + no_space_only(); + advance('(number)'); + } + } + return; + } + if (next_token.identifier && + (next_token.string === 'odd' || next_token.string === 'even')) { + advance(); + return; + } + warn('unexpected_a'); + } + + function substyle() { + var v; + for (;;) { + if (next_token.id === '}' || next_token.id === '(end)' || + (xquote && next_token.id === xquote)) { + return; + } + v = style_attribute(); + advance(':'); + if (next_token.identifier && next_token.string === 'inherit') { + advance(); + } else { + if (!style_value(v)) { + warn('unexpected_a'); + advance(); + } + } + if (next_token.id === '!') { + advance('!'); + no_space_only(); + if (next_token.identifier && next_token.string === 'important') { + advance(); + } else { + warn('expected_a_b', + next_token, 'important', artifact()); + } + } + if (next_token.id === '}' || next_token.id === xquote) { + warn('expected_a_b', next_token, ';', artifact()); + } else { + semicolon(); + } + } + } + + function style_selector() { + if (next_token.identifier) { + if (!Object.prototype.hasOwnProperty.call(html_tag, option.cap + ? next_token.string.toLowerCase() + : next_token.string)) { + warn('expected_tagname_a'); + } + advance(); + } else { + switch (next_token.id) { + case '>': + case '+': + advance(); + style_selector(); + break; + case ':': + advance(':'); + switch (next_token.string) { + case 'active': + case 'after': + case 'before': + case 'checked': + case 'disabled': + case 'empty': + case 'enabled': + case 'first-child': + case 'first-letter': + case 'first-line': + case 'first-of-type': + case 'focus': + case 'hover': + case 'last-child': + case 'last-of-type': + case 'link': + case 'only-of-type': + case 'root': + case 'target': + case 'visited': + advance_identifier(next_token.string); + break; + case 'lang': + advance_identifier('lang'); + advance('('); + if (!next_token.identifier) { + warn('expected_lang_a'); + } + advance(')'); + break; + case 'nth-child': + case 'nth-last-child': + case 'nth-last-of-type': + case 'nth-of-type': + advance_identifier(next_token.string); + advance('('); + style_child(); + advance(')'); + break; + case 'not': + advance_identifier('not'); + advance('('); + if (next_token.id === ':' && peek(0).string === 'not') { + warn('not'); + } + style_selector(); + advance(')'); + break; + default: + warn('expected_pseudo_a'); + } + break; + case '#': + advance('#'); + if (!next_token.identifier) { + warn('expected_id_a'); + } + advance(); + break; + case '*': + advance('*'); + break; + case '.': + advance('.'); + if (!next_token.identifier) { + warn('expected_class_a'); + } + advance(); + break; + case '[': + advance('['); + if (!next_token.identifier) { + warn('expected_attribute_a'); + } + advance(); + if (next_token.id === '=' || next_token.string === '~=' || + next_token.string === '$=' || + next_token.string === '|=' || + next_token.id === '*=' || + next_token.id === '^=') { + advance(); + if (next_token.id !== '(string)') { + warn('expected_string_a'); + } + advance(); + } + advance(']'); + break; + default: + stop('expected_selector_a'); + } + } + } + + function style_pattern() { + if (next_token.id === '{') { + warn('expected_style_pattern'); + } + for (;;) { + style_selector(); + if (next_token.id === '= 0) { + warn('unexpected_char_a_b', token, v.charAt(x), a); + } + ids[u] = true; + } else if (a === 'class' || a === 'type' || a === 'name') { + x = v.search(qx); + if (x >= 0) { + warn('unexpected_char_a_b', token, v.charAt(x), a); + } + ids[u] = true; + } else if (a === 'href' || a === 'background' || + a === 'content' || a === 'data' || + a.indexOf('src') >= 0 || a.indexOf('url') >= 0) { + if (option.safe && ux.test(v)) { + stop('bad_url_a', next_token, v); + } + urls.push(v); + } else if (a === 'for') { + if (option.adsafe) { + if (adsafe_id) { + if (v.slice(0, adsafe_id.length) !== adsafe_id) { + warn('adsafe_prefix_a', next_token, adsafe_id); + } else if (!/^[A-Z]+_[A-Z]+$/.test(v)) { + warn('adsafe_bad_id'); + } + } else { + warn('adsafe_bad_id'); + } + } + } else if (a === 'name') { + if (option.adsafe && v.indexOf('_') >= 0) { + warn('adsafe_name_a', next_token, v); + } + } + } + + function do_tag(name, attribute) { + var i, tag = html_tag[name], script, x; + src = false; + if (!tag) { + stop( + bundle.unrecognized_tag_a, + next_token, + name === name.toLowerCase() + ? name + : name + ' (capitalization error)' + ); + } + if (stack.length > 0) { + if (name === 'html') { + stop('unexpected_a', token, name); + } + x = tag.parent; + if (x) { + if (x.indexOf(' ' + stack[stack.length - 1].name + ' ') < 0) { + stop('tag_a_in_b', token, name, x); + } + } else if (!option.adsafe && !option.fragment) { + i = stack.length; + do { + if (i <= 0) { + stop('tag_a_in_b', token, name, 'body'); + } + i -= 1; + } while (stack[i].name !== 'body'); + } + } + switch (name) { + case 'div': + if (option.adsafe && stack.length === 1 && !adsafe_id) { + warn('adsafe_missing_id'); + } + break; + case 'script': + xmode = 'script'; + advance('>'); + if (attribute.lang) { + warn('lang', token); + } + if (option.adsafe && stack.length !== 1) { + warn('adsafe_placement', token); + } + if (attribute.src) { + if (option.adsafe && (!adsafe_may || !approved[attribute.src])) { + warn('adsafe_source', token); + } + } else { + step_in(next_token.from); + edge(); + use_strict(); + adsafe_top = true; + script = statements(); + +// JSLint is also the static analyzer for ADsafe. See www.ADsafe.org. + + if (option.adsafe) { + if (adsafe_went) { + stop('adsafe_script', token); + } + if (script.length !== 1 || + aint(script[0], 'id', '(') || + aint(script[0].first, 'id', '.') || + aint(script[0].first.first, 'string', 'ADSAFE') || + aint(script[0].second[0], 'string', adsafe_id)) { + stop('adsafe_id_go'); + } + switch (script[0].first.second.string) { + case 'id': + if (adsafe_may || adsafe_went || + script[0].second.length !== 1) { + stop('adsafe_id', next_token); + } + adsafe_may = true; + break; + case 'go': + if (adsafe_went) { + stop('adsafe_go'); + } + if (script[0].second.length !== 2 || + aint(script[0].second[1], 'id', 'function') || + !script[0].second[1].first || + aint(script[0].second[1].first[0], 'string', 'dom') || + script[0].second[1].first.length > 2 || + (script[0].second[1].first.length === 2 && + aint(script[0].second[1].first[1], 'string', 'lib'))) { + stop('adsafe_go', next_token); + } + adsafe_went = true; + break; + default: + stop('adsafe_id_go'); + } + } + indent = null; + } + xmode = 'html'; + advance(''); + styles(); + xmode = 'html'; + advance(''; + } + + function html() { + var attribute, attributes, is_empty, name, old_white = option.white, + quote, tag_name, tag, wmode; + xmode = 'html'; + xquote = ''; + stack = null; + for (;;) { + switch (next_token.string) { + case '<': + xmode = 'html'; + advance('<'); + attributes = {}; + tag_name = next_token; + name = tag_name.string; + advance_identifier(name); + if (option.cap) { + name = name.toLowerCase(); + } + tag_name.name = name; + if (!stack) { + stack = []; + do_begin(name); + } + tag = html_tag[name]; + if (typeof tag !== 'object') { + stop('unrecognized_tag_a', tag_name, name); + } + is_empty = tag.empty; + tag_name.type = name; + for (;;) { + if (next_token.id === '/') { + advance('/'); + if (next_token.id !== '>') { + warn('expected_a_b', next_token, '>', artifact()); + } + break; + } + if (next_token.id && next_token.id.charAt(0) === '>') { + break; + } + if (!next_token.identifier) { + if (next_token.id === '(end)' || next_token.id === '(error)') { + warn('expected_a_b', next_token, '>', artifact()); + } + warn('bad_name_a'); + } + option.white = false; + spaces(); + attribute = next_token.string; + option.white = old_white; + advance(); + if (!option.cap && attribute !== attribute.toLowerCase()) { + warn('attribute_case_a', token); + } + attribute = attribute.toLowerCase(); + xquote = ''; + if (Object.prototype.hasOwnProperty.call(attributes, attribute)) { + warn('duplicate_a', token, attribute); + } + if (attribute.slice(0, 2) === 'on') { + if (!option.on) { + warn('html_handlers'); + } + xmode = 'scriptstring'; + advance('='); + quote = next_token.id; + if (quote !== '"' && quote !== '\'') { + stop('expected_a_b', next_token, '"', artifact()); + } + xquote = quote; + wmode = option.white; + option.white = true; + advance(quote); + use_strict(); + statements(); + option.white = wmode; + if (next_token.id !== quote) { + stop('expected_a_b', next_token, quote, artifact()); + } + xmode = 'html'; + xquote = ''; + advance(quote); + tag = false; + } else if (attribute === 'style') { + xmode = 'scriptstring'; + advance('='); + quote = next_token.id; + if (quote !== '"' && quote !== '\'') { + stop('expected_a_b', next_token, '"', artifact()); + } + xmode = 'styleproperty'; + xquote = quote; + advance(quote); + substyle(); + xmode = 'html'; + xquote = ''; + advance(quote); + tag = false; + } else { + if (next_token.id === '=') { + advance('='); + tag = next_token.string; + if (!next_token.identifier && + next_token.id !== '"' && + next_token.id !== '\'' && + next_token.id !== '(string)' && + next_token.id !== '(string)' && + next_token.id !== '(color)') { + warn('expected_attribute_value_a', token, attribute); + } + advance(); + } else { + tag = true; + } + } + attributes[attribute] = tag; + do_attribute(attribute, tag); + } + do_tag(name, attributes); + if (!is_empty) { + stack.push(tag_name); + } + xmode = 'outer'; + advance('>'); + break; + case '') { + stop('expected_a_b', next_token, '>', artifact()); + } + xmode = 'outer'; + advance('>'); + break; + case '' || next_token.id === '(end)') { + break; + } + if (next_token.string.indexOf('--') >= 0) { + stop('unexpected_a', next_token, '--'); + } + if (next_token.string.indexOf('<') >= 0) { + stop('unexpected_a', next_token, '<'); + } + if (next_token.string.indexOf('>') >= 0) { + stop('unexpected_a', next_token, '>'); + } + } + xmode = 'outer'; + advance('>'); + break; + case '(end)': + return; + default: + if (next_token.id === '(end)') { + stop('missing_a', next_token, + ''); + } else { + advance(); + } + } + if (stack && stack.length === 0 && (option.adsafe || + !option.fragment || next_token.id === '(end)')) { + break; + } + } + if (next_token.id !== '(end)') { + stop('unexpected_a'); + } + } + + +// The actual JSLINT function itself. + + itself = function JSLint(the_source, the_option) { + + var i, predef, tree; + JSLINT.errors = []; + JSLINT.tree = ''; + begin = prev_token = token = next_token = + Object.create(syntax['(begin)']); + predefined = {}; + add_to_predefined(standard); + property = {}; + if (the_option) { + option = Object.create(the_option); + predef = option.predef; + if (predef) { + if (Array.isArray(predef)) { + for (i = 0; i < predef.length; i += 1) { + predefined[predef[i]] = true; + } + } else if (typeof predef === 'object') { + add_to_predefined(predef); + } + } + do_safe(); + } else { + option = {}; + } + option.indent = +option.indent || 4; + option.maxerr = +option.maxerr || 50; + adsafe_id = ''; + adsafe_may = adsafe_top = adsafe_went = false; + approved = {}; + if (option.approved) { + for (i = 0; i < option.approved.length; i += 1) { + approved[option.approved[i]] = option.approved[i]; + } + } else { + approved.test = 'test'; + } + tab = ''; + for (i = 0; i < option.indent; i += 1) { + tab += ' '; + } + global_scope = scope = {}; + global_funct = funct = { + '(scope)': scope, + '(breakage)': 0, + '(loopage)': 0 + }; + functions = [funct]; + + comments_off = false; + ids = {}; + in_block = false; + indent = null; + json_mode = false; + lookahead = []; + node_js = false; + prereg = true; + src = false; + stack = null; + strict_mode = false; + urls = []; + var_mode = null; + warnings = 0; + xmode = ''; + lex.init(the_source); + + assume(); + + try { + advance(); + if (next_token.id === '(number)') { + stop('unexpected_a'); + } else if (next_token.string.charAt(0) === '<') { + html(); + if (option.adsafe && !adsafe_went) { + warn('adsafe_go', this); + } + } else { + switch (next_token.id) { + case '{': + case '[': + json_mode = true; + json_value(); + break; + case '@': + case '*': + case '#': + case '.': + case ':': + xmode = 'style'; + advance(); + if (token.id !== '@' || !next_token.identifier || + next_token.string !== 'charset' || token.line !== 1 || + token.from !== 1) { + stop('css'); + } + advance(); + if (next_token.id !== '(string)' && + next_token.string !== 'UTF-8') { + stop('css'); + } + advance(); + semicolon(); + styles(); + break; + + default: + if (option.adsafe && option.fragment) { + stop('expected_a_b', + next_token, '
', artifact()); + } + +// If the first token is a semicolon, ignore it. This is sometimes used when +// files are intended to be appended to files that may be sloppy. A sloppy +// file may be depending on semicolon insertion on its last line. + + step_in(1); + if (next_token.id === ';' && !node_js) { + semicolon(); + } + adsafe_top = true; + tree = statements(); + begin.first = tree; + JSLINT.tree = begin; + // infer_types(tree); + if (option.adsafe && (tree.length !== 1 || + aint(tree[0], 'id', '(') || + aint(tree[0].first, 'id', '.') || + aint(tree[0].first.first, 'string', 'ADSAFE') || + aint(tree[0].first.second, 'string', 'lib') || + tree[0].second.length !== 2 || + tree[0].second[0].id !== '(string)' || + aint(tree[0].second[1], 'id', 'function'))) { + stop('adsafe_lib'); + } + if (tree.disrupt) { + warn('weird_program', prev_token); + } + } + } + indent = null; + advance('(end)'); + } catch (e) { + if (e) { // ~~ + JSLINT.errors.push({ + reason : e.message, + line : e.line || next_token.line, + character : e.character || next_token.from + }, null); + } + } + return JSLINT.errors.length === 0; + }; + + +// Data summary. + + itself.data = function () { + var data = {functions: []}, + function_data, + globals, + i, + j, + kind, + members = [], + name, + the_function, + undef = [], + unused = []; + if (itself.errors.length) { + data.errors = itself.errors; + } + + if (json_mode) { + data.json = true; + } + + if (urls.length > 0) { + data.urls = urls; + } + + globals = Object.keys(global_scope).filter(function (value) { + return value.charAt(0) !== '(' && typeof standard[value] !== 'boolean'; + }); + if (globals.length > 0) { + data.globals = globals; + } + + for (i = 1; i < functions.length; i += 1) { + the_function = functions[i]; + function_data = {}; + for (j = 0; j < functionicity.length; j += 1) { + function_data[functionicity[j]] = []; + } + for (name in the_function) { + if (Object.prototype.hasOwnProperty.call(the_function, name)) { + if (name.charAt(0) !== '(') { + kind = the_function[name]; + if (kind === 'unction' || kind === 'unparam') { + kind = 'unused'; + } + if (Array.isArray(function_data[kind])) { + function_data[kind].push(name); + if (kind === 'unused') { + unused.push({ + name: name, + line: the_function['(line)'], + 'function': the_function['(name)'] + }); + } else if (kind === 'undef') { + undef.push({ + name: name, + line: the_function['(line)'], + 'function': the_function['(name)'] + }); + } + } + } + } + } + for (j = 0; j < functionicity.length; j += 1) { + if (function_data[functionicity[j]].length === 0) { + delete function_data[functionicity[j]]; + } + } + function_data.name = the_function['(name)']; + function_data.params = the_function['(params)']; + function_data.line = the_function['(line)']; + data.functions.push(function_data); + } + + if (unused.length > 0) { + data.unused = unused; + } + if (undef.length > 0) { + data['undefined'] = undef; + } + + members = []; + for (name in property) { + if (typeof property[name] === 'number') { + data.member = property; + break; + } + } + + return data; + }; + + + itself.report = function (errors_only) { + var data = itself.data(), err, evidence, i, italics, j, key, keys, + length, mem = '', name, names, not_first, output = [], snippets, + the_function, warning; + + function detail(h, value) { + var comma_needed, singularity; + if (Array.isArray(value)) { + output.push('
' + h + ' '); + value.sort().forEach(function (item) { + if (item !== singularity) { + singularity = item; + output.push((comma_needed ? ', ' : '') + singularity); + comma_needed = true; + } + }); + output.push('
'); + } else if (value) { + output.push('
' + h + ' ' + value + '
'); + } + } + + if (data.errors || data.unused || data['undefined']) { + err = true; + output.push('
Error:'); + if (data.errors) { + for (i = 0; i < data.errors.length; i += 1) { + warning = data.errors[i]; + if (warning) { + evidence = warning.evidence || ''; + output.push('

Problem' + (isFinite(warning.line) + ? ' at line ' + String(warning.line) + + ' character ' + String(warning.character) + : '') + + ': ' + warning.reason.entityify() + + '

' + + (evidence && (evidence.length > 80 + ? evidence.slice(0, 77) + '...' + : evidence).entityify()) + '

'); + } + } + } + + if (data['undefined']) { + snippets = []; + for (i = 0; i < data['undefined'].length; i += 1) { + snippets[i] = '' + data['undefined'][i].name + ' ' + + String(data['undefined'][i].line) + ' ' + + data['undefined'][i]['function'] + ''; + } + output.push('

Undefined variable: ' + snippets.join(', ') + '

'); + } + if (data.unused) { + snippets = []; + for (i = 0; i < data.unused.length; i += 1) { + snippets[i] = '' + data.unused[i].name + ' ' + + String(data.unused[i].line) + ' ' + + data.unused[i]['function'] + ''; + } + output.push('

Unused variable: ' + snippets.join(', ') + '

'); + } + if (data.json) { + output.push('

JSON: bad.

'); + } + output.push('
'); + } + + if (!errors_only) { + + output.push('
'); + + if (data.urls) { + detail("URLs
", data.urls, '
'); + } + + if (xmode === 'style') { + output.push('

CSS.

'); + } else if (data.json && !err) { + output.push('

JSON: good.

'); + } else if (data.globals) { + output.push('
Global ' + + data.globals.sort().join(', ') + '
'); + } else { + output.push('
No new global variables introduced.
'); + } + + for (i = 0; i < data.functions.length; i += 1) { + the_function = data.functions[i]; + names = []; + if (the_function.params) { + for (j = 0; j < the_function.params.length; j += 1) { + names[j] = the_function.params[j].string; + } + } + output.push('
' + + String(the_function.line) + ' ' + + the_function.name.entityify() + + '(' + names.join(', ') + ')
'); + detail('Undefined', the_function['undefined']); + detail('Unused', the_function.unused); + detail('Closure', the_function.closure); + detail('Variable', the_function['var']); + detail('Exception', the_function.exception); + detail('Outer', the_function.outer); + detail('Global', the_function.global); + detail('Label', the_function.label); + } + + if (data.member) { + keys = Object.keys(data.member); + if (keys.length) { + keys = keys.sort(); + output.push('
/*properties
'); + mem = ' '; + italics = 0; + j = 0; + not_first = false; + for (i = 0; i < keys.length; i += 1) { + key = keys[i]; + if (data.member[key] > 0) { + if (not_first) { + mem += ', '; + } + name = ix.test(key) + ? key + : '\'' + key.entityify().replace(nx, sanitize) + '\''; + length += name.length + 2; + if (data.member[key] === 1) { + name = '' + name + ''; + italics += 1; + j = 1; + } + if (mem.length + name.length - (italics * 7) > 80) { + output.push(mem + '
'); + mem = ' '; + italics = j; + } + mem += name; + j = 0; + not_first = true; + } + } + output.push(mem + '
*/
'); + } + output.push('
'); + } + } + return output.join(''); + }; + itself.jslint = itself; + + itself.edition = '2012-02-23'; + + return itself; +}()); diff --git a/vim/ftplugin/javascript/jslint/runjslint.js b/vim/ftplugin/javascript/jslint/runjslint.js new file mode 100644 index 0000000..9d23cd1 --- /dev/null +++ b/vim/ftplugin/javascript/jslint/runjslint.js @@ -0,0 +1,103 @@ +/*jslint laxbreak: true */ + +var fs, vm, sandbox, jslintCore = 'jslint-core.js'; + +if (typeof require !== 'undefined') { + print = require('util').puts; + fs = require('fs'); + vm = require('vm'); + sandbox = {}; + res = vm.runInNewContext(fs.readFileSync(jslintCore), sandbox, jslintCore); + JSLINT = sandbox.JSLINT; +} else { + load('jslint-core.js'); +} + +// Import extra libraries if running in Rhino. +if (typeof importPackage != 'undefined') { + importPackage(java.io); + importPackage(java.lang); +} + +var readSTDIN = (function() { + // readSTDIN() definition for nodejs + if (typeof process != 'undefined' && process.openStdin) { + return function readSTDIN(callback) { + var stdin = process.openStdin() + , body = []; + + stdin.on('data', function(chunk) { + body.push(chunk); + }); + + stdin.on('end', function(chunk) { + callback(body.join('\n')); + }); + }; + + // readSTDIN() definition for Rhino + } else if (typeof BufferedReader != 'undefined') { + return function readSTDIN(callback) { + // setup the input buffer and output buffer + var stdin = new BufferedReader(new InputStreamReader(System['in'])), + lines = []; + + // read stdin buffer until EOF (or skip) + while (stdin.ready()){ + lines.push(stdin.readLine()); + } + + callback(lines.join('\n')); + }; + + // readSTDIN() definition for Spidermonkey + } else if (typeof readline != 'undefined') { + return function readSTDIN(callback) { + var line + , input = [] + , emptyCount = 0 + , i; + + line = readline(); + while (emptyCount < 25) { + input.push(line); + if (line) { + emptyCount = 0; + } else { + emptyCount += 1; + } + line = readline(); + } + + input.splice(-emptyCount); + callback(input.join('\n')); + }; + } +})(); + +readSTDIN(function(body) { + var ok = JSLINT(body) + , i + , error + , errorType + , nextError + , errorCount + , WARN = 'WARNING' + , ERROR = 'ERROR'; + + if (!ok) { + errorCount = JSLINT.errors.length; + for (i = 0; i < errorCount; i += 1) { + error = JSLINT.errors[i]; + errorType = WARN; + nextError = i < errorCount ? JSLINT.errors[i+1] : null; + if (error && error.reason && error.reason.match(/^Stopping/) === null) { + // If jslint stops next, this was an actual error + if (nextError && nextError.reason && nextError.reason.match(/^Stopping/) !== null) { + errorType = ERROR; + } + print([error.line, error.character, errorType, error.reason].join(":")); + } + } + } +}); diff --git a/vim/ftplugin/javascript/jslint/runjslint.wsf b/vim/ftplugin/javascript/jslint/runjslint.wsf new file mode 100644 index 0000000..d6c24bd --- /dev/null +++ b/vim/ftplugin/javascript/jslint/runjslint.wsf @@ -0,0 +1,48 @@ + + + + diff --git a/vim/plugin/LargeFile.vim b/vim/plugin/LargeFile.vim new file mode 100644 index 0000000..9f6551e --- /dev/null +++ b/vim/plugin/LargeFile.vim @@ -0,0 +1,80 @@ +" LargeFile: Sets up an autocmd to make editing large files work with celerity +" Author: Charles E. Campbell, Jr. +" Date: Sep 23, 2008 +" Version: 4 +" GetLatestVimScripts: 1506 1 :AutoInstall: LargeFile.vim + +" --------------------------------------------------------------------- +" Load Once: {{{1 +if exists("g:loaded_LargeFile") || &cp + finish +endif +let g:loaded_LargeFile = "v4" +let s:keepcpo = &cpo +set cpo&vim + +" --------------------------------------------------------------------- +" Commands: {{{1 +com! Unlarge call s:Unlarge() +com! -bang Large call s:LargeFile(0,expand("%")) + +" --------------------------------------------------------------------- +" Options: {{{1 +if !exists("g:LargeFile") + let g:LargeFile= 20 " in megabytes +endif + +" --------------------------------------------------------------------- +" LargeFile Autocmd: {{{1 +" for large files: turns undo, syntax highlighting, undo off etc +" (based on vimtip#611) +augroup LargeFile + au! + au BufReadPre * call LargeFile(0,expand("")) + au BufReadPost * + \ if &ch < 2 && (getfsize(expand("")) >= g:LargeFile*1024*1024 || getfsize(expand("")) == -2) + \| echomsg "***note*** handling a large file" + \| endif +augroup END + +" --------------------------------------------------------------------- +" s:LargeFile: {{{2 +fun! s:LargeFile(force,fname) +" call Dfunc("LargeFile(force=".a:force." fname<".a:fname.">)") + if a:force || getfsize(a:fname) >= g:LargeFile*1024*1024 || getfsize(a:fname) <= -2 + syn clear + let b:eikeep = &ei + let b:ulkeep = &ul + let b:bhkeep = &bh + let b:fdmkeep= &fdm + let b:swfkeep= &swf + set ei=FileType + setlocal noswf bh=unload fdm=manual ul=-1 + let fname=escape(substitute(a:fname,'\','/','g'),' ') + exe "au LargeFile BufEnter ".fname." set ul=-1" + exe "au LargeFile BufLeave ".fname." let &ul=".b:ulkeep."|set ei=".b:eikeep + exe "au LargeFile BufUnload ".fname." au! LargeFile * ". fname + echomsg "***note*** handling a large file" + endif +" call Dret("s:LargeFile") +endfun + +" --------------------------------------------------------------------- +" s:Unlarge: this function will undo what the LargeFile autocmd does {{{2 +fun! s:Unlarge() +" call Dfunc("s:Unlarge()") + if exists("b:eikeep") |let &ei = b:eikeep |endif + if exists("b:ulkeep") |let &ul = b:ulkeep |endif + if exists("b:bhkeep") |let &bh = b:bhkeep |endif + if exists("b:fdmkeep")|let &fdm = b:fdmkeep|endif + if exists("b:swfkeep")|let &swf = b:swfkeep|endif + syn on + doau FileType +" call Dret("s:Unlarge") +endfun + +" --------------------------------------------------------------------- +" Restore: {{{1 +let &cpo= s:keepcpo +unlet s:keepcpo +" vim: ts=4 fdm=marker diff --git a/vimrc b/vimrc index d88bac3..5ce3d57 100755 --- a/vimrc +++ b/vimrc @@ -80,6 +80,7 @@ set backspace=indent,eol,start " load the plugin and indent settings for the detected filetype filetype plugin indent on +filetype plugin on " Opens an edit command with the path of the currently edited file filled in " Normal mode: e diff --git a/zshrc b/zshrc index 85e83ef..696cce6 100644 --- a/zshrc +++ b/zshrc @@ -17,7 +17,7 @@ export ZSH_THEME="ben-prose" # DISABLE_LS_COLORS="true" # Uncomment following line if you want to disable autosetting terminal title. -# DISABLE_AUTO_TITLE="true" +DISABLE_AUTO_TITLE="true" # Uncomment following line if you want disable red dots displayed while waiting for completion # DISABLE_COMPLETION_WAITING_DOTS="true" @@ -56,10 +56,12 @@ alias rspec="rspec --color" #Screeninator and RVM scripts [[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm +bindkey -v + # # End of the custom things from my bash profile. # There's probably a more "zsh-ish" way of doing these, but I have no time. # # Customize to your needs... -export PATH=/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin +export PATH=/usr/local/share/npm/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin -- cgit From 5456416faf6cea4c7e3e77074a5cb24f55e007f8 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:39:29 -0600 Subject: Add gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e0bca4c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +vim/.backup -- cgit From c1ee7d654c235bf267e12c56060d6346bac84432 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:39:29 -0600 Subject: Add gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e0bca4c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +vim/.backup -- cgit From 5adc7ec862f0f1b16d8584267f8980e020fca590 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:40:48 -0600 Subject: Add DS_Store to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e0bca4c..5673cb2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +.DS_Store vim/.backup -- cgit From f3bb3a2de44624da5112beb0c26f3b5fb20b43eb Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:40:48 -0600 Subject: Add DS_Store to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e0bca4c..5673cb2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +.DS_Store vim/.backup -- cgit From d26e01d7260a8e7bd32ab75f755fa327e680f53e Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:41:44 -0600 Subject: Remove backup and DS_Store --- .DS_Store | Bin 6148 -> 0 bytes vim/.DS_Store | Bin 15364 -> 0 bytes vim/.backup/App-Movement-RCA-Spec.md.swp | Bin 16384 -> 0 bytes vim/.backup/Community.js.swp | Bin 16384 -> 0 bytes vim/.backup/Entries-CRUD-RCA-Spec.md.swp | Bin 24576 -> 0 bytes vim/.backup/EventTracker.js.swp | Bin 16384 -> 0 bytes vim/.backup/LargeFile.vim~ | 80 -------- vim/.backup/Rule.js.swp | Bin 16384 -> 0 bytes vim/.backup/Vimball.swo | Bin 12288 -> 0 bytes vim/.backup/Vimball.swp | Bin 12288 -> 0 bytes vim/.backup/[Rhenium]-Rhenium-Spec.md.swp | Bin 16384 -> 0 bytes vim/.backup/clean_db.rb.swp | Bin 12288 -> 0 bytes vim/.backup/layout.erb.swp | Bin 12288 -> 0 bytes vim/.backup/main.js.swp | Bin 16384 -> 0 bytes vim/.backup/page.rb.swp | Bin 16384 -> 0 bytes vim/.backup/player.lua.swp | Bin 16384 -> 0 bytes vim/.backup/schedule.rb.swp | Bin 12288 -> 0 bytes vim/.backup/server.js~ | 258 ------------------------- vim/.backup/server.jz~ | 260 -------------------------- vim/.backup/style_propagation.rb.swp | Bin 16384 -> 0 bytes vim/.backup/tidy_db.rb.swo | Bin 12288 -> 0 bytes vim/.backup/trashcan.js.swp | Bin 16384 -> 0 bytes vim/.backup/voice_feeder.rb.swp | Bin 16384 -> 0 bytes vim/.backup/widget.js.swn | Bin 16384 -> 0 bytes vim/.backup/widget.js.swo | Bin 16384 -> 0 bytes vim/.backup/widget.js.swp | Bin 24576 -> 0 bytes vim/.backup/you_tube.rb.swp | Bin 12288 -> 0 bytes vim/autoload/.DS_Store | Bin 12292 -> 0 bytes vim/autoload/Powerline/.DS_Store | Bin 6148 -> 0 bytes vim/autoload/Powerline/Colorschemes/.DS_Store | Bin 6148 -> 0 bytes vim/autoload/Powerline/Themes/.DS_Store | Bin 6148 -> 0 bytes vim/colors/.DS_Store | Bin 21508 -> 0 bytes vim/doc/.DS_Store | Bin 6148 -> 0 bytes vim/plugin/.DS_Store | Bin 6148 -> 0 bytes vim/ruby/.DS_Store | Bin 6148 -> 0 bytes 35 files changed, 598 deletions(-) delete mode 100644 .DS_Store delete mode 100644 vim/.DS_Store delete mode 100644 vim/.backup/App-Movement-RCA-Spec.md.swp delete mode 100644 vim/.backup/Community.js.swp delete mode 100644 vim/.backup/Entries-CRUD-RCA-Spec.md.swp delete mode 100644 vim/.backup/EventTracker.js.swp delete mode 100644 vim/.backup/LargeFile.vim~ delete mode 100644 vim/.backup/Rule.js.swp delete mode 100644 vim/.backup/Vimball.swo delete mode 100644 vim/.backup/Vimball.swp delete mode 100644 vim/.backup/[Rhenium]-Rhenium-Spec.md.swp delete mode 100644 vim/.backup/clean_db.rb.swp delete mode 100644 vim/.backup/layout.erb.swp delete mode 100644 vim/.backup/main.js.swp delete mode 100644 vim/.backup/page.rb.swp delete mode 100644 vim/.backup/player.lua.swp delete mode 100644 vim/.backup/schedule.rb.swp delete mode 100755 vim/.backup/server.js~ delete mode 100755 vim/.backup/server.jz~ delete mode 100644 vim/.backup/style_propagation.rb.swp delete mode 100644 vim/.backup/tidy_db.rb.swo delete mode 100644 vim/.backup/trashcan.js.swp delete mode 100644 vim/.backup/voice_feeder.rb.swp delete mode 100644 vim/.backup/widget.js.swn delete mode 100644 vim/.backup/widget.js.swo delete mode 100644 vim/.backup/widget.js.swp delete mode 100644 vim/.backup/you_tube.rb.swp delete mode 100644 vim/autoload/.DS_Store delete mode 100644 vim/autoload/Powerline/.DS_Store delete mode 100644 vim/autoload/Powerline/Colorschemes/.DS_Store delete mode 100644 vim/autoload/Powerline/Themes/.DS_Store delete mode 100644 vim/colors/.DS_Store delete mode 100644 vim/doc/.DS_Store delete mode 100644 vim/plugin/.DS_Store delete mode 100644 vim/ruby/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 1ad65a3..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/vim/.DS_Store b/vim/.DS_Store deleted file mode 100644 index 86412de..0000000 Binary files a/vim/.DS_Store and /dev/null differ diff --git a/vim/.backup/App-Movement-RCA-Spec.md.swp b/vim/.backup/App-Movement-RCA-Spec.md.swp deleted file mode 100644 index 230e570..0000000 Binary files a/vim/.backup/App-Movement-RCA-Spec.md.swp and /dev/null differ diff --git a/vim/.backup/Community.js.swp b/vim/.backup/Community.js.swp deleted file mode 100644 index 9d2431d..0000000 Binary files a/vim/.backup/Community.js.swp and /dev/null differ diff --git a/vim/.backup/Entries-CRUD-RCA-Spec.md.swp b/vim/.backup/Entries-CRUD-RCA-Spec.md.swp deleted file mode 100644 index d8cc0a3..0000000 Binary files a/vim/.backup/Entries-CRUD-RCA-Spec.md.swp and /dev/null differ diff --git a/vim/.backup/EventTracker.js.swp b/vim/.backup/EventTracker.js.swp deleted file mode 100644 index efd9596..0000000 Binary files a/vim/.backup/EventTracker.js.swp and /dev/null differ diff --git a/vim/.backup/LargeFile.vim~ b/vim/.backup/LargeFile.vim~ deleted file mode 100644 index 9f6551e..0000000 --- a/vim/.backup/LargeFile.vim~ +++ /dev/null @@ -1,80 +0,0 @@ -" LargeFile: Sets up an autocmd to make editing large files work with celerity -" Author: Charles E. Campbell, Jr. -" Date: Sep 23, 2008 -" Version: 4 -" GetLatestVimScripts: 1506 1 :AutoInstall: LargeFile.vim - -" --------------------------------------------------------------------- -" Load Once: {{{1 -if exists("g:loaded_LargeFile") || &cp - finish -endif -let g:loaded_LargeFile = "v4" -let s:keepcpo = &cpo -set cpo&vim - -" --------------------------------------------------------------------- -" Commands: {{{1 -com! Unlarge call s:Unlarge() -com! -bang Large call s:LargeFile(0,expand("%")) - -" --------------------------------------------------------------------- -" Options: {{{1 -if !exists("g:LargeFile") - let g:LargeFile= 20 " in megabytes -endif - -" --------------------------------------------------------------------- -" LargeFile Autocmd: {{{1 -" for large files: turns undo, syntax highlighting, undo off etc -" (based on vimtip#611) -augroup LargeFile - au! - au BufReadPre * call LargeFile(0,expand("")) - au BufReadPost * - \ if &ch < 2 && (getfsize(expand("")) >= g:LargeFile*1024*1024 || getfsize(expand("")) == -2) - \| echomsg "***note*** handling a large file" - \| endif -augroup END - -" --------------------------------------------------------------------- -" s:LargeFile: {{{2 -fun! s:LargeFile(force,fname) -" call Dfunc("LargeFile(force=".a:force." fname<".a:fname.">)") - if a:force || getfsize(a:fname) >= g:LargeFile*1024*1024 || getfsize(a:fname) <= -2 - syn clear - let b:eikeep = &ei - let b:ulkeep = &ul - let b:bhkeep = &bh - let b:fdmkeep= &fdm - let b:swfkeep= &swf - set ei=FileType - setlocal noswf bh=unload fdm=manual ul=-1 - let fname=escape(substitute(a:fname,'\','/','g'),' ') - exe "au LargeFile BufEnter ".fname." set ul=-1" - exe "au LargeFile BufLeave ".fname." let &ul=".b:ulkeep."|set ei=".b:eikeep - exe "au LargeFile BufUnload ".fname." au! LargeFile * ". fname - echomsg "***note*** handling a large file" - endif -" call Dret("s:LargeFile") -endfun - -" --------------------------------------------------------------------- -" s:Unlarge: this function will undo what the LargeFile autocmd does {{{2 -fun! s:Unlarge() -" call Dfunc("s:Unlarge()") - if exists("b:eikeep") |let &ei = b:eikeep |endif - if exists("b:ulkeep") |let &ul = b:ulkeep |endif - if exists("b:bhkeep") |let &bh = b:bhkeep |endif - if exists("b:fdmkeep")|let &fdm = b:fdmkeep|endif - if exists("b:swfkeep")|let &swf = b:swfkeep|endif - syn on - doau FileType -" call Dret("s:Unlarge") -endfun - -" --------------------------------------------------------------------- -" Restore: {{{1 -let &cpo= s:keepcpo -unlet s:keepcpo -" vim: ts=4 fdm=marker diff --git a/vim/.backup/Rule.js.swp b/vim/.backup/Rule.js.swp deleted file mode 100644 index 3d23813..0000000 Binary files a/vim/.backup/Rule.js.swp and /dev/null differ diff --git a/vim/.backup/Vimball.swo b/vim/.backup/Vimball.swo deleted file mode 100644 index 845507d..0000000 Binary files a/vim/.backup/Vimball.swo and /dev/null differ diff --git a/vim/.backup/Vimball.swp b/vim/.backup/Vimball.swp deleted file mode 100644 index 99764ea..0000000 Binary files a/vim/.backup/Vimball.swp and /dev/null differ diff --git a/vim/.backup/[Rhenium]-Rhenium-Spec.md.swp b/vim/.backup/[Rhenium]-Rhenium-Spec.md.swp deleted file mode 100644 index 990306d..0000000 Binary files a/vim/.backup/[Rhenium]-Rhenium-Spec.md.swp and /dev/null differ diff --git a/vim/.backup/clean_db.rb.swp b/vim/.backup/clean_db.rb.swp deleted file mode 100644 index 9d6f1c8..0000000 Binary files a/vim/.backup/clean_db.rb.swp and /dev/null differ diff --git a/vim/.backup/layout.erb.swp b/vim/.backup/layout.erb.swp deleted file mode 100644 index ba28785..0000000 Binary files a/vim/.backup/layout.erb.swp and /dev/null differ diff --git a/vim/.backup/main.js.swp b/vim/.backup/main.js.swp deleted file mode 100644 index d543eff..0000000 Binary files a/vim/.backup/main.js.swp and /dev/null differ diff --git a/vim/.backup/page.rb.swp b/vim/.backup/page.rb.swp deleted file mode 100644 index c016f4e..0000000 Binary files a/vim/.backup/page.rb.swp and /dev/null differ diff --git a/vim/.backup/player.lua.swp b/vim/.backup/player.lua.swp deleted file mode 100644 index a3a785a..0000000 Binary files a/vim/.backup/player.lua.swp and /dev/null differ diff --git a/vim/.backup/schedule.rb.swp b/vim/.backup/schedule.rb.swp deleted file mode 100644 index 44d1165..0000000 Binary files a/vim/.backup/schedule.rb.swp and /dev/null differ diff --git a/vim/.backup/server.js~ b/vim/.backup/server.js~ deleted file mode 100755 index dc39a5e..0000000 --- a/vim/.backup/server.js~ +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env node - -require('colors'); -var Ne = require('neon'); - -Nitrogen = { - Manifest : require('./lib/manifest.js'), - Server : {} -}; - -Ne.Class(Nitrogen.Server, 'Editor')({ - prototype : { - fs : require('fs'), - express : require('express'), - httpProxy : require('http-proxy'), - io : require('socket.io'), - http : require('http'), - app : null, - server : null, - socket : null, - port : 4000, - occipitalOptions : {}, - - init : function init(config) { - Object.keys(config).forEach(function (property) { - this[property] = config[property]; - }, this); - - console.log('Nitrogen Session Server starting '); - this.app = this.express(); - this.proxy = new this.httpProxy.RoutingProxy(); - this.server = this.http.createServer(this.app); - this.initRack(); - this.initDb(); - this.initRoutes(); - this.server.listen(this.port); - this.socket = this.io.listen(this.server); - this.initSyncEvents(); - console.log('Nitrogen Session Server listening on port ' + this.port); - }, - - initRack : function initRack() { - var nitrogen = this; - this.app.use(this.express.logger()); - this.app.use(this.express.compress()); - this.app.use(function (request, response, next) { - response.header("Access-Control-Allow-Origin", "*"); - response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); - response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); - if ('OPTIONS' == request.method) { - response.send(200); - } - else { - next(); - } - }); - // This has to be here in order for a proxied post to work. - // See https://github.com/nodejitsu/node-http-proxy/issues/180 - // for more information. - this.app.use(function (request, response, next) { - if (request.url.match(/\/attachments\/.*/) && request.method === "POST" ){ - var options = nitrogen.occipitalOptions; - nitrogen.proxy.proxyRequest( request, response, options ); - } else { - return next(); - } - }); - this.app.use(this.express.bodyParser()); - this.app.use('/', this.express.static('public')); - }, - - initDb : function initDb() { - var fileNames = this.fs.readdirSync(__dirname + '/../').filter(function(fn){ return fn.match(/.*\.json$/); }); - var i, filePath, collectionName; - data = Nitrogen.data = {}; - - for( i=0; i < fileNames.length; i+=1 ){ - filePath = __dirname + '/../' + fileNames[i]; - collectionName = fileNames[i].replace(/.json/, ''); - data[collectionName] = this.fs.readFileSync(filePath).toString().replace(/\n$/, "").split(/\n/).map(function(r){ - return JSON.parse(r); - }); - } - }, - - initRoutes : function initRoutes() { - var nitrogen = this, - path = require('path'); - - this.app.get('/', function (request, response) { - var file = path.resolve('./public/app.html'); - response.sendfile(file); - }); - - this.app.get('/api/all', function (req, res) { - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(data)); - }); - - this.app.get('/api/:model', function (req, res) { - var records = data[req.params.model] - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(records)); - }); - - this.app.get('/api/:model/:id', function (req, res){ - var model = req.params.model; - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - - if (record) { - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(record)); - } - else { - res.set('Content-Type', 'application/json'); - res.send(404, 'record not found'); - } - }); - - this.app.get('/api/:model/:id/delete', function (req, res){ - var model = req.params.model; - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - - data[model].splice(data[model].indexOf(record), 1); - - res.set('Content-Type', 'application/json'); - res.send('{}'); - }); - - this.app.post('/api/:model/create', function (req, res){ - var model = req.params.model; - var record = req.body; - record.id = util.generateUid(24); - - data[model].push(record); - - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(record)); - }); - - this.app.post('/api/:model/:id/update', function (req, res){ - var model = req.params.model; - - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - - var position = data[model].indexOf(record); - console.log(req); - data[model].splice(position, 1, req.body); - - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(record)); - }); - - this.app.get('/manifest_doc.js', function (req, res) { - res.set('Content-Type', 'application/json'); - - // Generate the package every time for development - Manifest.generatePackage(function () { - res.sendfile(path.resolve('./public/manifest_doc.js')); - }); - /* TODO: Uncomment when file detection is done - nitrogen.fs.exists('./public/manifest_doc.js', function (exists) { - if (exists) { - res.sendfile(path.resolve('./public/manifest_doc.js')); - } else { - // create package - Manifest.generatePackage(function () { - res.sendfile(path.resolve('./public/manifest_doc.js')); - }); - } - }); */ - }); - - this.app.get('/get_assets', function (req, res) { - res.set('Content-Type', 'text/plain'); - - // Generate the package everytime for development - Manifest.generatePackage(function () { - res.sendfile(path.resolve('../app_assets/package.dat')); - }); - /* TODO: Uncomment when file detection is ready - nitrogen.fs.exists('../app_assets/package.dat', function (exists) { - if (exists) { - res.sendfile(path.resolve('../app_assets/package.dat')); - } else { - // create package - Manifest.generatePackage(function () { - res.sendfile(path.resolve('../app_assets/package.dat')); - }); - } - }); */ - }); - - this.app.get('/attachments/*', function (req, res) { - var options = nitrogen.occipitalOptions; - - nitrogen.proxy.proxyRequest( req, res, options ); - }); - }, - - initSyncEvents : function () { - this.socket.sockets.on('connection', function (socket) { - socket.emit('connected', {message : "Connection established"}); - - socket.on('sync', function (sync_data) { - console.log(">> Incoming LSD DATA".blue); - - sync_data = JSON.parse(sync_data); - - // Let's handle each guy - switch(sync_data.action) { - case "create": - data["tasks"].push(sync_data.data); - break; - case "update": - var record = data["tasks"].filter(function (record) { - return record.id == sync_data.data.id; - })[0]; - var position = data["tasks"].indexOf(record); - data["tasks"].splice(position, 1, sync_data.data); - break; - case "remove": - var record = data["tasks"].filter(function (record) { - return record.id == sync_data.data.id; - })[0]; - var position = data["tasks"].indexOf(record); - data["tasks"].splice(position, 1); - break; - } - - socket.emit('sync_ok', {message : "Sync Received: OK"}); - }); - }); - - this.socket.sockets.on('disconnect', function (socket) { - socket.emit('disconnected', {message : "Connection lost"}); - }); - } - } -}); - -new Nitrogen.Server.Editor({ - port : process.argv[2] || 4000, - occipitalOptions : { - host : (process.argv[3]) ? process.argv[3].replace(/:.*/, '') : '127.0.0.1', - port : (process.argv[3]) ? process.argv[3].replace(/.*:/, '') : '3001' - } -}); - diff --git a/vim/.backup/server.jz~ b/vim/.backup/server.jz~ deleted file mode 100755 index 907e448..0000000 --- a/vim/.backup/server.jz~ +++ /dev/null @@ -1,260 +0,0 @@ -#!/usr/bin/env node - -require('colors'); -var Ne = require('neon'); - -Nitrogen = { - Manifest : require('./lib/manifest.js'), - Server : {} -}; - -Ne.Class(Nitrogen.Server, 'Editor')({ - prototype : { - fs : require('fs'), - express : require('express'), - httpProxy : require('http-proxy'), - io : require('socket.io'), - http : require('http'), - app : null, - server : null, - socket : null, - port : 4000, - occipitalOptions : {}, - - init : function init(config) { - Object.keys(config).forEach(function (property) { - this[property] = config[property]; - }, this); - - console.log('Nitrogen Session Server starting '); - this.app = this.express(); - this.proxy = new this.httpProxy.RoutingProxy(); - this.server = this.http.createServer(this.app); - this.initRack(); - this.initDb(); - this.initRoutes(); - this.server.listen(this.port); - this.socket = this.io.listen(this.server); - this.socket.set('transports', ['websocket']) - this.socket.disable('heartbeats'); - this.initSyncEvents(); - console.log('Nitrogen Session Server listening on port ' + this.port); - }, - - initRack : function initRack() { - var nitrogen = this; - this.app.use(this.express.logger()); - this.app.use(this.express.compress()); - this.app.use(function (request, response, next) { - response.header("Access-Control-Allow-Origin", "*"); - response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); - response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); - if ('OPTIONS' == request.method) { - response.send(200); - } - else { - next(); - } - }); - // This has to be here in order for a proxied post to work. - // See https://github.com/nodejitsu/node-http-proxy/issues/180 - // for more information. - this.app.use(function (request, response, next) { - if (request.url.match(/\/attachments\/.*/) && request.method === "POST" ){ - var options = nitrogen.occipitalOptions; - nitrogen.proxy.proxyRequest( request, response, options ); - } else { - return next(); - } - }); - this.app.use(this.express.bodyParser()); - this.app.use('/', this.express.static('public')); - }, - - initDb : function initDb() { - var fileNames = this.fs.readdirSync(__dirname + '/../').filter(function(fn){ return fn.match(/.*\.json$/); }); - var i, filePath, collectionName; - data = Nitrogen.data = {}; - - for( i=0; i < fileNames.length; i+=1 ){ - filePath = __dirname + '/../' + fileNames[i]; - collectionName = fileNames[i].replace(/.json/, ''); - data[collectionName] = this.fs.readFileSync(filePath).toString().replace(/\n$/, "").split(/\n/).map(function(r){ - return JSON.parse(r); - }); - } - }, - - initRoutes : function initRoutes() { - var nitrogen = this, - path = require('path'); - - this.app.get('/', function (request, response) { - var file = path.resolve('./public/app.html'); - response.sendfile(file); - }); - - this.app.get('/api/all', function (req, res) { - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(data)); - }); - - this.app.get('/api/:model', function (req, res) { - var records = data[req.params.model] - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(records)); - }); - - this.app.get('/api/:model/:id', function (req, res){ - var model = req.params.model; - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - - if (record) { - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(record)); - } - else { - res.set('Content-Type', 'application/json'); - res.send(404, 'record not found'); - } - }); - - this.app.get('/api/:model/:id/delete', function (req, res){ - var model = req.params.model; - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - - data[model].splice(data[model].indexOf(record), 1); - - res.set('Content-Type', 'application/json'); - res.send('{}'); - }); - - this.app.post('/api/:model/create', function (req, res){ - var model = req.params.model; - var record = req.body; - record.id = util.generateUid(24); - - data[model].push(record); - - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(record)); - }); - - this.app.post('/api/:model/:id/update', function (req, res){ - var model = req.params.model; - - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - - var position = data[model].indexOf(record); - console.log(req); - data[model].splice(position, 1, req.body); - - var record = data[model].filter(function (record) { - return record.id == req.params.id; - })[0]; - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(record)); - }); - - this.app.get('/manifest_doc.js', function (req, res) { - res.set('Content-Type', 'application/json'); - - // Generate the package every time for development - Manifest.generatePackage(function () { - res.sendfile(path.resolve('./public/manifest_doc.js')); - }); - /* TODO: Uncomment when file detection is done - nitrogen.fs.exists('./public/manifest_doc.js', function (exists) { - if (exists) { - res.sendfile(path.resolve('./public/manifest_doc.js')); - } else { - // create package - Manifest.generatePackage(function () { - res.sendfile(path.resolve('./public/manifest_doc.js')); - }); - } - }); */ - }); - - this.app.get('/get_assets', function (req, res) { - res.set('Content-Type', 'text/plain'); - - // Generate the package everytime for development - Manifest.generatePackage(function () { - res.sendfile(path.resolve('../app_assets/package.dat')); - }); - /* TODO: Uncomment when file detection is ready - nitrogen.fs.exists('../app_assets/package.dat', function (exists) { - if (exists) { - res.sendfile(path.resolve('../app_assets/package.dat')); - } else { - // create package - Manifest.generatePackage(function () { - res.sendfile(path.resolve('../app_assets/package.dat')); - }); - } - }); */ - }); - - this.app.get('/attachments/*', function (req, res) { - var options = nitrogen.occipitalOptions; - - nitrogen.proxy.proxyRequest( req, res, options ); - }); - }, - - initSyncEvents : function () { - this.socket.sockets.on('connection', function (socket) { - socket.emit('connected', {message : "Connection established"}); - - socket.on('sync', function (sync_data) { - console.log(">> Incoming LSD DATA".blue); - - sync_data = JSON.parse(sync_data); - - // Let's handle each guy - switch(sync_data.action) { - case "create": - data["tasks"].push(sync_data.data); - break; - case "update": - var record = data["tasks"].filter(function (record) { - return record.id == sync_data.data.id; - })[0]; - var position = data["tasks"].indexOf(record); - data["tasks"].splice(position, 1, sync_data.data); - break; - case "remove": - var record = data["tasks"].filter(function (record) { - return record.id == sync_data.data.id; - })[0]; - var position = data["tasks"].indexOf(record); - data["tasks"].splice(position, 1); - break; - } - - socket.emit('sync_ok', {message : "Sync Received: OK"}); - }); - }); - - this.socket.sockets.on('disconnect', function (socket) { - socket.emit('disconnected', {message : "Connection lost"}); - }); - } - } -}); - -new Nitrogen.Server.Editor({ - port : process.argv[2] || 4000, - occipitalOptions : { - host : (process.argv[3]) ? process.argv[3].replace(/:.*/, '') : '127.0.0.1', - port : (process.argv[3]) ? process.argv[3].replace(/.*:/, '') : '3001' - } -}); - diff --git a/vim/.backup/style_propagation.rb.swp b/vim/.backup/style_propagation.rb.swp deleted file mode 100644 index d94f28e..0000000 Binary files a/vim/.backup/style_propagation.rb.swp and /dev/null differ diff --git a/vim/.backup/tidy_db.rb.swo b/vim/.backup/tidy_db.rb.swo deleted file mode 100644 index f9f69fa..0000000 Binary files a/vim/.backup/tidy_db.rb.swo and /dev/null differ diff --git a/vim/.backup/trashcan.js.swp b/vim/.backup/trashcan.js.swp deleted file mode 100644 index e798ad2..0000000 Binary files a/vim/.backup/trashcan.js.swp and /dev/null differ diff --git a/vim/.backup/voice_feeder.rb.swp b/vim/.backup/voice_feeder.rb.swp deleted file mode 100644 index e3e557d..0000000 Binary files a/vim/.backup/voice_feeder.rb.swp and /dev/null differ diff --git a/vim/.backup/widget.js.swn b/vim/.backup/widget.js.swn deleted file mode 100644 index 14c88af..0000000 Binary files a/vim/.backup/widget.js.swn and /dev/null differ diff --git a/vim/.backup/widget.js.swo b/vim/.backup/widget.js.swo deleted file mode 100644 index c26c46e..0000000 Binary files a/vim/.backup/widget.js.swo and /dev/null differ diff --git a/vim/.backup/widget.js.swp b/vim/.backup/widget.js.swp deleted file mode 100644 index 21d79bc..0000000 Binary files a/vim/.backup/widget.js.swp and /dev/null differ diff --git a/vim/.backup/you_tube.rb.swp b/vim/.backup/you_tube.rb.swp deleted file mode 100644 index 88f58b0..0000000 Binary files a/vim/.backup/you_tube.rb.swp and /dev/null differ diff --git a/vim/autoload/.DS_Store b/vim/autoload/.DS_Store deleted file mode 100644 index 2827dba..0000000 Binary files a/vim/autoload/.DS_Store and /dev/null differ diff --git a/vim/autoload/Powerline/.DS_Store b/vim/autoload/Powerline/.DS_Store deleted file mode 100644 index 871e86f..0000000 Binary files a/vim/autoload/Powerline/.DS_Store and /dev/null differ diff --git a/vim/autoload/Powerline/Colorschemes/.DS_Store b/vim/autoload/Powerline/Colorschemes/.DS_Store deleted file mode 100644 index f68b536..0000000 Binary files a/vim/autoload/Powerline/Colorschemes/.DS_Store and /dev/null differ diff --git a/vim/autoload/Powerline/Themes/.DS_Store b/vim/autoload/Powerline/Themes/.DS_Store deleted file mode 100644 index 44586fd..0000000 Binary files a/vim/autoload/Powerline/Themes/.DS_Store and /dev/null differ diff --git a/vim/colors/.DS_Store b/vim/colors/.DS_Store deleted file mode 100644 index f9205e7..0000000 Binary files a/vim/colors/.DS_Store and /dev/null differ diff --git a/vim/doc/.DS_Store b/vim/doc/.DS_Store deleted file mode 100644 index 3da680a..0000000 Binary files a/vim/doc/.DS_Store and /dev/null differ diff --git a/vim/plugin/.DS_Store b/vim/plugin/.DS_Store deleted file mode 100644 index dd8c972..0000000 Binary files a/vim/plugin/.DS_Store and /dev/null differ diff --git a/vim/ruby/.DS_Store b/vim/ruby/.DS_Store deleted file mode 100644 index 5008ddf..0000000 Binary files a/vim/ruby/.DS_Store and /dev/null differ -- cgit From fbde376a40967a788e88bd7500503976c717421e Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 25 Mar 2013 16:41:44 -0600 Subject: Remove backup and DS_Store --- .DS_Store | Bin 6148 -> 0 bytes vim/.DS_Store | Bin 15364 -> 0 bytes vim/autoload/.DS_Store | Bin 12292 -> 0 bytes vim/autoload/Powerline/.DS_Store | Bin 6148 -> 0 bytes vim/autoload/Powerline/Colorschemes/.DS_Store | Bin 6148 -> 0 bytes vim/autoload/Powerline/Themes/.DS_Store | Bin 6148 -> 0 bytes vim/colors/.DS_Store | Bin 21508 -> 0 bytes vim/doc/.DS_Store | Bin 6148 -> 0 bytes vim/plugin/.DS_Store | Bin 6148 -> 0 bytes vim/ruby/.DS_Store | Bin 6148 -> 0 bytes 10 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store delete mode 100644 vim/.DS_Store delete mode 100644 vim/autoload/.DS_Store delete mode 100644 vim/autoload/Powerline/.DS_Store delete mode 100644 vim/autoload/Powerline/Colorschemes/.DS_Store delete mode 100644 vim/autoload/Powerline/Themes/.DS_Store delete mode 100644 vim/colors/.DS_Store delete mode 100644 vim/doc/.DS_Store delete mode 100644 vim/plugin/.DS_Store delete mode 100644 vim/ruby/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 1ad65a3..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/vim/.DS_Store b/vim/.DS_Store deleted file mode 100644 index 86412de..0000000 Binary files a/vim/.DS_Store and /dev/null differ diff --git a/vim/autoload/.DS_Store b/vim/autoload/.DS_Store deleted file mode 100644 index 2827dba..0000000 Binary files a/vim/autoload/.DS_Store and /dev/null differ diff --git a/vim/autoload/Powerline/.DS_Store b/vim/autoload/Powerline/.DS_Store deleted file mode 100644 index 871e86f..0000000 Binary files a/vim/autoload/Powerline/.DS_Store and /dev/null differ diff --git a/vim/autoload/Powerline/Colorschemes/.DS_Store b/vim/autoload/Powerline/Colorschemes/.DS_Store deleted file mode 100644 index f68b536..0000000 Binary files a/vim/autoload/Powerline/Colorschemes/.DS_Store and /dev/null differ diff --git a/vim/autoload/Powerline/Themes/.DS_Store b/vim/autoload/Powerline/Themes/.DS_Store deleted file mode 100644 index 44586fd..0000000 Binary files a/vim/autoload/Powerline/Themes/.DS_Store and /dev/null differ diff --git a/vim/colors/.DS_Store b/vim/colors/.DS_Store deleted file mode 100644 index f9205e7..0000000 Binary files a/vim/colors/.DS_Store and /dev/null differ diff --git a/vim/doc/.DS_Store b/vim/doc/.DS_Store deleted file mode 100644 index 3da680a..0000000 Binary files a/vim/doc/.DS_Store and /dev/null differ diff --git a/vim/plugin/.DS_Store b/vim/plugin/.DS_Store deleted file mode 100644 index dd8c972..0000000 Binary files a/vim/plugin/.DS_Store and /dev/null differ diff --git a/vim/ruby/.DS_Store b/vim/ruby/.DS_Store deleted file mode 100644 index 5008ddf..0000000 Binary files a/vim/ruby/.DS_Store and /dev/null differ -- cgit From 6c396295dcca469828e84ce3ff450f207a12736d Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Tue, 26 Mar 2013 15:53:30 -0600 Subject: Adds some plugins --- zshrc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zshrc b/zshrc index 696cce6..a18d284 100644 --- a/zshrc +++ b/zshrc @@ -24,7 +24,7 @@ DISABLE_AUTO_TITLE="true" # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Example format: plugins=(rails git textmate ruby lighthouse) -plugins=(git brew bundler cap gem osx rails3 rvm dircycle) +plugins=(git brew bundler cap gem osx rails3 rvm dircycle command-coloring npm) source $ZSH/oh-my-zsh.sh @@ -57,6 +57,7 @@ alias rspec="rspec --color" [[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm bindkey -v +bindkey '^R' history-incremental-pattern-search-backward # # End of the custom things from my bash profile. -- cgit From 162b65d8624bac4e04a3ac6ccd46ce7e8975fb81 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Thu, 28 Mar 2013 14:53:32 -0600 Subject: Local vim/zsh changes --- vimrc | 3 +++ zshrc | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/vimrc b/vimrc index d88bac3..8b575bc 100755 --- a/vimrc +++ b/vimrc @@ -160,3 +160,6 @@ set foldlevel=1 " powerline stuff let g:Powerline_symbols = 'fancy' + +" node cleaning +let g:ctrlp_custom_ignore = 'node_modules\|DS_Store\|git' diff --git a/zshrc b/zshrc index b818570..b649043 100644 --- a/zshrc +++ b/zshrc @@ -63,4 +63,4 @@ alias rspec="rspec --color" # # Customize to your needs... -export PATH=/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin +export PATH=/usr/local/share/npm/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin -- cgit From eb45b5761906bdf075e182fff6effdca0d30c134 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 8 Apr 2013 17:20:29 -0500 Subject: Fix broken path, also, add ctags yo. --- vim/.backup/.htaccess.swp | Bin 12288 -> 0 bytes vimrc | 5 +++++ zshrc | 1 - 3 files changed, 5 insertions(+), 1 deletion(-) delete mode 100644 vim/.backup/.htaccess.swp diff --git a/vim/.backup/.htaccess.swp b/vim/.backup/.htaccess.swp deleted file mode 100644 index 5c0572a..0000000 Binary files a/vim/.backup/.htaccess.swp and /dev/null differ diff --git a/vimrc b/vimrc index 5ce3d57..9ac964a 100755 --- a/vimrc +++ b/vimrc @@ -146,6 +146,7 @@ endif " Mapping for TagBar nmap :TagbarToggle +let g:tagbar_ctags_bin="/usr/local/bin/ctags" " Color Column set colorcolumn=81 @@ -161,3 +162,7 @@ set foldlevel=1 " powerline stuff let g:Powerline_symbols = 'fancy' + +" Fix CtrlP root folder and add some ignores +let g:ctrlp_working_path_mode = 0 +let g:ctrlp_custom_ignore = '\v[\/](\.(git|hg|svn)|node_modules)$' diff --git a/zshrc b/zshrc index a18d284..f1f9e6a 100644 --- a/zshrc +++ b/zshrc @@ -65,4 +65,3 @@ bindkey '^R' history-incremental-pattern-search-backward # # Customize to your needs... -export PATH=/usr/local/share/npm/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/benbeltran/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/benbeltran/.rvm/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin -- cgit From 75a6977d066445f43fdb0ed35b7ab8398fdc917d Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Tue, 16 Apr 2013 01:22:46 -0500 Subject: Use the newer powerline. --- ben-prose.zsh-theme | 10 +- config/mc/ini | 141 +++++++++ config/mc/panels.ini | 1 + config/powerline/colors.json | 98 +++++++ config/powerline/colorschemes/ipython/default.json | 8 + config/powerline/colorschemes/shell/default.json | 17 ++ config/powerline/colorschemes/shell/solarized.json | 17 ++ config/powerline/colorschemes/tmux/default.json | 24 ++ config/powerline/colorschemes/vim/default.json | 94 ++++++ config/powerline/colorschemes/vim/solarized.json | 91 ++++++ config/powerline/colorschemes/wm/default.json | 25 ++ config/powerline/config.json | 48 +++ config/powerline/themes/ipython/in.json | 26 ++ config/powerline/themes/ipython/in2.json | 13 + config/powerline/themes/ipython/out.json | 25 ++ config/powerline/themes/ipython/rewrite.json | 23 ++ config/powerline/themes/shell/default.json | 45 +++ .../powerline/themes/shell/default_leftonly.json | 43 +++ config/powerline/themes/tmux/default.json | 64 ++++ config/powerline/themes/vim/cmdwin.json | 18 ++ config/powerline/themes/vim/default.json | 108 +++++++ config/powerline/themes/vim/help.json | 36 +++ config/powerline/themes/vim/quickfix.json | 37 +++ config/powerline/themes/wm/default.json | 31 ++ tmux-powerline | 1 - tmux.conf | 13 +- vim/.netrwhist | 3 +- vim/autoload/Powerline/Colorschemes/default.vim | 161 ----------- vim/autoload/Powerline/Functions.vim | 90 ------ vim/autoload/Powerline/Functions/cfi.vim | 3 - vim/autoload/Powerline/Functions/ft_man.vim | 12 - vim/autoload/Powerline/Functions/fugitive.vim | 7 - vim/autoload/Powerline/Functions/syntastic.vim | 16 - vim/autoload/Powerline/Matches.vim | 13 - vim/autoload/Powerline/Segments.vim | 28 -- vim/autoload/Powerline/Segments/cfi.vim | 5 - vim/autoload/Powerline/Segments/ctrlp.vim | 10 - vim/autoload/Powerline/Segments/ft_man.vim | 3 - vim/autoload/Powerline/Segments/fugitive.vim | 5 - vim/autoload/Powerline/Segments/rvm.vim | 5 - vim/autoload/Powerline/Segments/syntastic.vim | 5 - vim/autoload/Powerline/Segments/virtualenv.vim | 5 - vim/autoload/Powerline/Themes/default.vim | 114 -------- vim/doc/Powerline.txt | 322 --------------------- vim/plugin/Powerline.vim | 56 ---- vimrc | 2 +- 46 files changed, 1038 insertions(+), 884 deletions(-) create mode 100644 config/mc/ini create mode 100644 config/mc/panels.ini create mode 100644 config/powerline/colors.json create mode 100644 config/powerline/colorschemes/ipython/default.json create mode 100644 config/powerline/colorschemes/shell/default.json create mode 100644 config/powerline/colorschemes/shell/solarized.json create mode 100644 config/powerline/colorschemes/tmux/default.json create mode 100644 config/powerline/colorschemes/vim/default.json create mode 100644 config/powerline/colorschemes/vim/solarized.json create mode 100644 config/powerline/colorschemes/wm/default.json create mode 100644 config/powerline/config.json create mode 100644 config/powerline/themes/ipython/in.json create mode 100644 config/powerline/themes/ipython/in2.json create mode 100644 config/powerline/themes/ipython/out.json create mode 100644 config/powerline/themes/ipython/rewrite.json create mode 100644 config/powerline/themes/shell/default.json create mode 100644 config/powerline/themes/shell/default_leftonly.json create mode 100644 config/powerline/themes/tmux/default.json create mode 100644 config/powerline/themes/vim/cmdwin.json create mode 100644 config/powerline/themes/vim/default.json create mode 100644 config/powerline/themes/vim/help.json create mode 100644 config/powerline/themes/vim/quickfix.json create mode 100644 config/powerline/themes/wm/default.json delete mode 160000 tmux-powerline delete mode 100644 vim/autoload/Powerline/Colorschemes/default.vim delete mode 100644 vim/autoload/Powerline/Functions.vim delete mode 100644 vim/autoload/Powerline/Functions/cfi.vim delete mode 100644 vim/autoload/Powerline/Functions/ft_man.vim delete mode 100644 vim/autoload/Powerline/Functions/fugitive.vim delete mode 100644 vim/autoload/Powerline/Functions/syntastic.vim delete mode 100644 vim/autoload/Powerline/Matches.vim delete mode 100644 vim/autoload/Powerline/Segments.vim delete mode 100644 vim/autoload/Powerline/Segments/cfi.vim delete mode 100644 vim/autoload/Powerline/Segments/ctrlp.vim delete mode 100644 vim/autoload/Powerline/Segments/ft_man.vim delete mode 100644 vim/autoload/Powerline/Segments/fugitive.vim delete mode 100644 vim/autoload/Powerline/Segments/rvm.vim delete mode 100644 vim/autoload/Powerline/Segments/syntastic.vim delete mode 100644 vim/autoload/Powerline/Segments/virtualenv.vim delete mode 100644 vim/autoload/Powerline/Themes/default.vim delete mode 100644 vim/doc/Powerline.txt delete mode 100644 vim/plugin/Powerline.vim diff --git a/ben-prose.zsh-theme b/ben-prose.zsh-theme index 3573c24..dc21546 100644 --- a/ben-prose.zsh-theme +++ b/ben-prose.zsh-theme @@ -6,14 +6,6 @@ function rvm_info { echo '('`rvm-prompt`') ' } -function hg_prompt_info { - $OH_MY_ZSH_HG prompt --angle-brackets "\ -< on %{$fg[magenta]%}%{$reset_color%}>\ -< at %{$fg[yellow]%}%{$reset_color%}>\ -%{$fg[green]%}%{$reset_color%}< -patches: >" 2>/dev/null -} - function box_name { [ -f ~/.box-name ] && cat ~/.box-name || hostname -s } @@ -28,7 +20,7 @@ zle -N zle-line-init zle -N zle-keymap-select PROMPT=' -%{$fg[red]%}%n%{$reset_color%} at %{$fg[yellow]%}$(box_name)%{$reset_color%} in %{$fg_bold[green]%}${PWD/#$HOME/~}%{$reset_color%}$(hg_prompt_info)$(git_prompt_info) %{$fg[black]%}$(rvm_info)%{$reset_color%} +%{$fg[red]%}%n%{$reset_color%} at %{$fg[yellow]%}$(box_name)%{$reset_color%} in %{$fg_bold[green]%}${PWD/#$HOME/~}%{$reset_color%}$(git_prompt_info) %{$fg[black]%}$(rvm_info)%{$reset_color%} %(?,,%{${fg_bold[white]}%}[%?]%{$reset_color%} )$ ' ZSH_THEME_GIT_PROMPT_PREFIX=" on %{$fg[blue]%}" diff --git a/config/mc/ini b/config/mc/ini new file mode 100644 index 0000000..ce20bb3 --- /dev/null +++ b/config/mc/ini @@ -0,0 +1,141 @@ + +[Midnight-Commander] +verbose=1 +pause_after_run=1 +shell_patterns=1 +auto_save_setup=1 +auto_menu=0 +use_internal_view=1 +use_internal_edit=1 +clear_before_exec=1 +confirm_delete=1 +confirm_overwrite=1 +confirm_execute=0 +confirm_history_cleanup=1 +confirm_exit=1 +confirm_directory_hotlist_delete=1 +safe_delete=0 +mouse_repeat_rate=100 +double_click_speed=250 +use_8th_bit_as_meta=0 +confirm_view_dir=0 +mouse_move_pages_viewer=1 +mouse_close_dialog=0 +fast_refresh=0 +drop_menus=0 +wrap_mode=1 +old_esc_mode=0 +old_esc_mode_timeout=1000000 +cd_symlinks=1 +show_all_if_ambiguous=0 +max_dirt_limit=10 +use_file_to_guess_type=1 +alternate_plus_minus=0 +only_leading_plus_minus=1 +show_output_starts_shell=0 +xtree_mode=0 +num_history_items_recorded=60 +file_op_compute_totals=1 +classic_progressbar=1 +vfs_timeout=60 +ftpfs_directory_timeout=900 +use_netrc=1 +ftpfs_retry_seconds=30 +ftpfs_always_use_proxy=0 +ftpfs_use_passive_connections=1 +ftpfs_use_passive_connections_over_proxy=0 +ftpfs_use_unix_list_options=1 +ftpfs_first_cd_then_ls=1 +fish_directory_timeout=900 +editor_tab_spacing=8 +editor_word_wrap_line_length=72 +editor_fill_tabs_with_spaces=0 +editor_return_does_auto_indent=1 +editor_backspace_through_tabs=0 +editor_fake_half_tabs=1 +editor_option_save_mode=0 +editor_option_save_position=1 +editor_option_auto_para_formatting=0 +editor_option_typewriter_wrap=0 +editor_edit_confirm_save=1 +editor_syntax_highlighting=1 +editor_persistent_selections=1 +editor_cursor_beyond_eol=0 +editor_visible_tabs=1 +editor_visible_spaces=1 +editor_line_state=0 +editor_simple_statusbar=0 +editor_check_new_line=0 +editor_show_right_margin=0 +editor_group_undo=0 +nice_rotating_dash=1 +mcview_remember_file_position=0 +auto_fill_mkdir_name=1 +copymove_persistent_attr=1 +select_flags=6 +editor_backup_extension=~ +mcview_eof= +ignore_ftp_chattr_errors=true +keymap=mc.keymap +skin=default + +preallocate_space=0 + + + +[Layout] +message_visible=1 +keybar_visible=1 +xterm_title=1 +output_lines=0 +command_prompt=1 +menubar_visible=1 +free_space=1 + +horizontal_split=0 +vertical_equal=1 +left_panel_size=72 +horizontal_equal=1 +top_panel_size=67 + + + +[Misc] +timeformat_recent=%b %e %H:%M +timeformat_old=%b %e %Y +ftp_proxy_host=gate +ftpfs_password=anonymous@ +display_codepage=UTF-8 +source_codepage=Other_8_bit +autodetect_codeset= +clipboard_store= +clipboard_paste= + +[Colors] +base_color= +screen-256color= +color_terminals= + +[Panels] +show_mini_info=true +kilobyte_si=false +mix_all_files=false +show_backups=true +show_dot_files=true +fast_reload=false +fast_reload_msg_shown=false +mark_moves_down=true +reverse_files_only=true +auto_save_setup_panels=false +navigate_with_arrows=false +panel_scroll_pages=true +mouse_move_pages=true +filetype_mode=true +permission_mode=false +torben_fj_mode=false +quick_search_mode=2 + +[Panelize] +Find *.orig after patching=find . -name \\*.orig -print +Find SUID and SGID programs=find . \\( \\( -perm -04000 -a -perm +011 \\) -o \\( -perm -02000 -a -perm +01 \\) \\) -print +Find rejects after patching=find . -name \\*.rej -print diff --git a/config/mc/panels.ini b/config/mc/panels.ini new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/config/mc/panels.ini @@ -0,0 +1 @@ + diff --git a/config/powerline/colors.json b/config/powerline/colors.json new file mode 100644 index 0000000..3bbb90f --- /dev/null +++ b/config/powerline/colors.json @@ -0,0 +1,98 @@ +{ + "colors": { + "black": 16, + "white": 231, + + "darkestgreen": 22, + "darkgreen": 28, + "mediumgreen": 70, + "brightgreen": 148, + + "darkestcyan": 23, + "darkcyan": 74, + "mediumcyan": 117, + "brightcyan": 159, + + "darkestblue": 24, + "darkblue": 31, + + "darkestred": 52, + "darkred": 88, + "mediumred": 124, + "brightred": 160, + "brightestred": 196, + + "darkestpurple": 55, + "mediumpurple": 98, + "brightpurple": 189, + + "darkorange": 94, + "mediumorange": 166, + "brightorange": 208, + "brightestorange": 214, + + "brightyellow": 220, + + "gray0": 233, + "gray1": 235, + "gray2": 236, + "gray3": 239, + "gray4": 240, + "gray5": 241, + "gray6": 244, + "gray7": 245, + "gray8": 247, + "gray9": 250, + "gray10": 252, + + "gray61": [14, "93a1a1"], + "gray13": [8, "002b36"], + + "royalblue5": [0, "073642"], + "darkgreencopper": [10, "586e75"], + "lightskyblue4": [11, "657b83"], + "azure4": [12, "839496"], + "lightyellow": [7, "eee8d5"], + "oldlace": [15, "fdf6e3"], + + "green": [2, "719e07"], + "cyan": [6, "2aa198"], + "blue": [4, "268bd2"], + "red": [1, "dc322f"], + "magenta": [5, "d33682"], + "violet": [13, "6c71c4"], + "orange": [9, "cb4b16"], + "yellow": [3, "b58900"], + + "lightyellowgreen": 106, + "gold3": 178, + "orangered": 202, + + "steelblue": 67, + "darkorange3": 166, + "skyblue1": 117, + "khaki1": 228 + }, + "gradients": { + "green_yellow_red": [ + [190, 184, 178, 172, 166, 160], + ["8ae71c", "8ce71c", "8fe71c", "92e71c", "95e71d", "98e71d", "9ae71d", "9de71d", "a0e71e", "a3e71e", "a6e71e", "a8e71e", "abe71f", "aee71f", "b1e71f", "b4e71f", "b6e720", "b9e720", "bce720", "bfe720", "c2e821", "c3e721", "c5e621", "c7e521", "c9e522", "cbe422", "cde322", "cfe222", "d1e223", "d3e123", "d5e023", "d7df23", "d9df24", "dbde24", "dddd24", "dfdc24", "e1dc25", "e3db25", "e5da25", "e7d925", "e9d926", "e9d626", "e9d426", "e9d126", "e9cf27", "e9cc27", "e9ca27", "e9c727", "e9c528", "e9c228", "e9c028", "e9bd28", "e9bb29", "e9b829", "e9b629", "e9b329", "e9b12a", "e9ae2a", "e9ac2a", "e9a92a", "eaa72b", "eaa42b", "eaa22b", "ea9f2b", "ea9d2c", "ea9b2c", "ea982c", "ea962c", "ea942d", "ea912d", "ea8f2d", "ea8d2d", "ea8a2e", "ea882e", "ea862e", "ea832e", "ea812f", "ea7f2f", "ea7c2f", "ea7a2f", "eb7830", "eb7530", "eb7330", "eb7130", "eb6f31", "eb6c31", "eb6a31", "eb6831", "eb6632", "eb6332", "eb6132", "eb5f32", "eb5d33", "eb5a33", "eb5833", "eb5633", "eb5434", "eb5134", "eb4f34", "eb4d34", "ec4b35"] + ], + "green_yellow_orange_red": [ + [2, 3, 9, 1], + ["719e07", "739d06", "759c06", "779c06", "799b06", "7b9a05", "7d9a05", "7f9905", "819805", "839805", "859704", "879704", "899604", "8b9504", "8d9504", "8f9403", "919303", "949303", "969203", "989102", "9a9102", "9c9002", "9e9002", "a08f02", "a28e01", "a48e01", "a68d01", "a88c01", "aa8c01", "ac8b00", "ae8a00", "b08a00", "b28900", "b58900", "b58700", "b68501", "b78302", "b78102", "b87f03", "b97d04", "b97b04", "ba7905", "bb7806", "bb7606", "bc7407", "bd7208", "bd7008", "be6e09", "bf6c0a", "bf6a0a", "c0690b", "c1670c", "c1650c", "c2630d", "c3610e", "c35f0e", "c45d0f", "c55b10", "c55a10", "c65811", "c75612", "c75412", "c85213", "c95014", "c94e14", "ca4c15", "cb4b16", "cb4a16", "cc4917", "cc4818", "cd4719", "cd4719", "ce461a", "ce451b", "cf441c", "cf441c", "d0431d", "d0421e", "d1411f", "d1411f", "d24020", "d23f21", "d33e22", "d33e22", "d43d23", "d43c24", "d53b25", "d53b25", "d63a26", "d63927", "d73828", "d73828", "d83729", "d8362a", "d9352b", "d9352b", "da342c", "da332d", "db322e", "dc322f"] + ], + "yellow_red": [ + [220, 178, 172, 166, 160], + ["ffd700", "fdd500", "fbd300", "fad200", "f8d000", "f7cf00", "f5cd00", "f3cb00", "f2ca00", "f0c800", "efc700", "edc500", "ebc300", "eac200", "e8c000", "e7bf00", "e5bd00", "e3bb00", "e2ba00", "e0b800", "dfb700", "ddb500", "dbb300", "dab200", "d8b000", "d7af00", "d7ad00", "d7ab00", "d7aa00", "d7a800", "d7a700", "d7a500", "d7a300", "d7a200", "d7a000", "d79f00", "d79d00", "d79b00", "d79a00", "d79800", "d79700", "d79500", "d79300", "d79200", "d79000", "d78f00", "d78d00", "d78b00", "d78a00", "d78800", "d78700", "d78500", "d78300", "d78200", "d78000", "d77f00", "d77d00", "d77b00", "d77a00", "d77800", "d77700", "d77500", "d77300", "d77200", "d77000", "d76f00", "d76d00", "d76b00", "d76a00", "d76800", "d76700", "d76500", "d76300", "d76200", "d76000", "d75f00", "d75b00", "d75700", "d75300", "d74f00", "d74c00", "d74800", "d74400", "d74000", "d73c00", "d73900", "d73500", "d73100", "d72d00", "d72900", "d72600", "d72200", "d71e00", "d71a00", "d71600", "d71300", "d70f00", "d70b00", "d70700"] + ], + "yellow_orange_red": [ + [3, 9, 1], + ["b58900", "b58700", "b58600", "b68501", "b68401", "b78202", "b78102", "b88003", "b87f03", "b87d03", "b97c04", "b97b04", "ba7a05", "ba7805", "bb7706", "bb7606", "bc7507", "bc7307", "bc7207", "bd7108", "bd7008", "be6e09", "be6d09", "bf6c0a", "bf6b0a", "c06a0b", "c0680b", "c0670b", "c1660c", "c1650c", "c2630d", "c2620d", "c3610e", "c3600e", "c35e0e", "c45d0f", "c45c0f", "c55b10", "c55910", "c65811", "c65711", "c75612", "c75412", "c75312", "c85213", "c85113", "c94f14", "c94e14", "ca4d15", "ca4c15", "cb4b16", "cb4a16", "cb4a17", "cc4917", "cc4918", "cc4818", "cd4819", "cd4719", "cd471a", "ce461a", "ce461b", "ce451b", "cf451c", "cf441c", "cf441d", "d0431d", "d0431e", "d0421e", "d1421f", "d1411f", "d14120", "d24020", "d24021", "d23f21", "d33f22", "d33e22", "d33e23", "d43d23", "d43d24", "d43c24", "d53c25", "d53b25", "d53b26", "d63a26", "d63a27", "d63927", "d73928", "d73828", "d73829", "d83729", "d8372a", "d8362a", "d9362b", "d9352b", "d9352c", "da342c", "da342d", "da332d", "db332e"] + ], + "blue_red": [ + [39, 74, 68, 67, 103, 97, 96, 132, 131, 167, 203, 197], + ["19b4fe", "1bb2fc", "1db1fa", "1faff8", "22aef6", "24adf4", "26abf2", "29aaf0", "2ba9ee", "2da7ec", "30a6ea", "32a5e8", "34a3e6", "36a2e4", "39a0e2", "3b9fe1", "3d9edf", "409cdd", "429bdb", "449ad9", "4798d7", "4997d5", "4b96d3", "4d94d1", "5093cf", "5292cd", "5490cb", "578fc9", "598dc7", "5b8cc6", "5e8bc4", "6089c2", "6288c0", "6487be", "6785bc", "6984ba", "6b83b8", "6e81b6", "7080b4", "727eb2", "757db0", "777cae", "797aac", "7b79ab", "7e78a9", "8076a7", "8275a5", "8574a3", "8772a1", "89719f", "8c709d", "8e6e9b", "906d99", "926b97", "956a95", "976993", "996791", "9c668f", "9e658e", "a0638c", "a3628a", "a56188", "a75f86", "a95e84", "ac5c82", "ae5b80", "b05a7e", "b3587c", "b5577a", "b75678", "ba5476", "bc5374", "be5273", "c05071", "c34f6f", "c54e6d", "c74c6b", "ca4b69", "cc4967", "ce4865", "d14763", "d34561", "d5445f", "d7435d", "da415b", "dc4059", "de3f58", "e13d56", "e33c54", "e53a52", "e83950", "ea384e", "ec364c", "ee354a", "f13448", "f33246", "f53144", "f83042", "fa2e40"] + ] + } +} diff --git a/config/powerline/colorschemes/ipython/default.json b/config/powerline/colorschemes/ipython/default.json new file mode 100644 index 0000000..d787591 --- /dev/null +++ b/config/powerline/colorschemes/ipython/default.json @@ -0,0 +1,8 @@ +{ + "name": "Default color scheme for IPython prompt", + "groups": { + "virtualenv": { "fg": "white", "bg": "darkcyan" }, + "prompt": { "fg": "gray9", "bg": "gray4" }, + "prompt_count": { "fg": "white", "bg": "gray4" } + } +} diff --git a/config/powerline/colorschemes/shell/default.json b/config/powerline/colorschemes/shell/default.json new file mode 100644 index 0000000..639c1f9 --- /dev/null +++ b/config/powerline/colorschemes/shell/default.json @@ -0,0 +1,17 @@ +{ + "name": "Default color scheme for shell prompts", + "groups": { + "user": { "fg": "white", "bg": "darkblue", "attr": ["bold"] }, + "superuser": { "fg": "white", "bg": "brightred", "attr": ["bold"] }, + "virtualenv": { "fg": "white", "bg": "darkcyan" }, + "branch": { "fg": "gray9", "bg": "gray2" }, + "branch_dirty": { "fg": "brightyellow", "bg": "gray2" }, + "branch_clean": { "fg": "gray9", "bg": "gray2" }, + "cwd": { "fg": "gray9", "bg": "gray4" }, + "cwd:current_folder": { "fg": "gray10", "bg": "gray4", "attr": ["bold"] }, + "cwd:divider": { "fg": "gray7", "bg": "gray4" }, + "hostname": { "fg": "brightyellow", "bg": "mediumorange" }, + "exit_fail": { "fg": "white", "bg": "darkestred" }, + "exit_success": { "fg": "white", "bg": "darkestgreen" } + } +} diff --git a/config/powerline/colorschemes/shell/solarized.json b/config/powerline/colorschemes/shell/solarized.json new file mode 100644 index 0000000..5bf8672 --- /dev/null +++ b/config/powerline/colorschemes/shell/solarized.json @@ -0,0 +1,17 @@ +{ + "name": "Solarized Dark", + "groups": { + "user": { "fg": "oldlace", "bg": "blue", "attr": ["bold"] }, + "superuser": { "fg": "oldlace", "bg": "red", "attr": ["bold"] }, + "virtualenv": { "fg": "oldlace", "bg": "green" }, + "branch": { "fg": "gray61", "bg": "royalblue5" }, + "branch_dirty": { "fg": "yellow", "bg": "royalblue5" }, + "branch_clean": { "fg": "gray61", "bg": "royalblue5" }, + "cwd": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "cwd:current_folder": { "fg": "oldlace", "bg": "darkgreencopper", "attr": ["bold"] }, + "cwd:divider": { "fg": "gray61", "bg": "darkgreencopper" }, + "hostname": { "fg": "oldlace", "bg": "darkgreencopper" }, + "exit_fail": { "fg": "oldlace", "bg": "red" }, + "exit_success": { "fg": "oldlace", "bg": "green" } + } +} diff --git a/config/powerline/colorschemes/tmux/default.json b/config/powerline/colorschemes/tmux/default.json new file mode 100644 index 0000000..35686d3 --- /dev/null +++ b/config/powerline/colorschemes/tmux/default.json @@ -0,0 +1,24 @@ +{ + "name": "Default color scheme for terminal prompts", + "groups": { + "background:divider": { "fg": "gray5", "bg": "gray0" }, + "session": { "fg": "black", "bg": "gray10", "attr": ["bold"] }, + "date": { "fg": "gray8", "bg": "gray2" }, + "time": { "fg": "gray10", "bg": "gray2", "attr": ["bold"] }, + "time:divider": { "fg": "gray5", "bg": "gray2" }, + "email_alert": { "fg": "white", "bg": "brightred", "attr": ["bold"] }, + "email_alert_gradient": { "fg": "white", "bg": "yellow_orange_red", "attr": ["bold"] }, + "hostname": { "fg": "black", "bg": "gray10", "attr": ["bold"] }, + "weather": { "fg": "gray8", "bg": "gray0" }, + "weather_temp_gradient": { "fg": "blue_red", "bg": "gray0" }, + "weather_condition_hot": { "fg": "khaki1", "bg": "gray0" }, + "weather_condition_snowy": { "fg": "skyblue1", "bg": "gray0" }, + "weather_condition_rainy": { "fg": "skyblue1", "bg": "gray0" }, + "uptime": { "fg": "gray8", "bg": "gray0" }, + "external_ip": { "fg": "gray8", "bg": "gray0" }, + "network_load": { "fg": "gray8", "bg": "gray0" }, + "network_load_gradient": { "fg": "green_yellow_orange_red", "bg": "gray0" }, + "system_load": { "fg": "gray8", "bg": "gray0" }, + "system_load_gradient": { "fg": "green_yellow_orange_red", "bg": "gray0" } + } +} diff --git a/config/powerline/colorschemes/vim/default.json b/config/powerline/colorschemes/vim/default.json new file mode 100644 index 0000000..ec15879 --- /dev/null +++ b/config/powerline/colorschemes/vim/default.json @@ -0,0 +1,94 @@ +{ + "name": "Default color scheme", + "groups": { + "background": { "fg": "white", "bg": "gray2" }, + "background:divider": { "fg": "gray6", "bg": "gray2" }, + "mode": { "fg": "darkestgreen", "bg": "brightgreen", "attr": ["bold"] }, + "modified_indicator": { "fg": "brightyellow", "bg": "gray4", "attr": ["bold"] }, + "paste_indicator": { "fg": "white", "bg": "mediumorange", "attr": ["bold"] }, + "readonly_indicator": { "fg": "brightestred", "bg": "gray4" }, + "branch": { "fg": "gray9", "bg": "gray4" }, + "branch_dirty": { "fg": "brightyellow", "bg": "gray4" }, + "branch_clean": { "fg": "gray9", "bg": "gray4" }, + "branch:divider": { "fg": "gray7", "bg": "gray4" }, + "file_directory": { "fg": "gray9", "bg": "gray4" }, + "file_name": { "fg": "white", "bg": "gray4", "attr": ["bold"] }, + "file_size": { "fg": "gray8", "bg": "gray2" }, + "file_name_no_file": { "fg": "gray9", "bg": "gray4", "attr": ["bold"] }, + "file_name_empty": { "fg": "gray9", "bg": "gray4" }, + "file_format": { "fg": "gray8", "bg": "gray2" }, + "file_encoding": { "fg": "gray8", "bg": "gray2" }, + "file_type": { "fg": "gray8", "bg": "gray2" }, + "file_vcs_status": { "fg": "brightestred", "bg": "gray4" }, + "file_vcs_status_M": { "fg": "brightyellow", "bg": "gray4" }, + "file_vcs_status_A": { "fg": "brightgreen", "bg": "gray4" }, + "line_percent": { "fg": "gray9", "bg": "gray4" }, + "line_percent_gradient": { "fg": "green_yellow_red", "bg": "gray4" }, + "line_current": { "fg": "gray1", "bg": "gray10", "attr": ["bold"] }, + "line_current_symbol": { "fg": "gray1", "bg": "gray10" }, + "col_current": { "fg": "gray6", "bg": "gray10" }, + "modified_buffers": { "fg": "brightyellow", "bg": "gray2" } + }, + "mode_translations": { + "nc": { + "colors": { + "brightyellow": "darkorange", + "brightestred": "darkred", + "gray0": "gray0", + "gray1": "gray0", + "gray2": "gray0", + "gray3": "gray1", + "gray4": "gray1", + "gray5": "gray1", + "gray6": "gray1", + "gray7": "gray4", + "gray8": "gray4", + "gray9": "gray4", + "gray10": "gray5", + "white": "gray6", + "green_yellow_red": "gray5" + } + }, + "i": { + "colors": { + "gray0": "darkestblue", + "gray1": "darkestblue", + "gray2": "darkestblue", + "gray3": "darkblue", + "gray4": "darkblue", + "gray5": "darkestcyan", + "gray6": "darkestcyan", + "gray7": "darkestcyan", + "gray8": "mediumcyan", + "gray9": "mediumcyan", + "gray10": "mediumcyan", + "green_yellow_red": "gray5" + }, + "groups": { + "mode": { "fg": "darkestcyan", "bg": "white", "attr": ["bold"] }, + "background:divider": { "fg": "darkcyan", "bg": "darkestblue" }, + "branch:divider": { "fg": "darkcyan", "bg": "darkblue" } + } + }, + "v": { + "groups": { + "mode": { "fg": "darkorange", "bg": "brightestorange", "attr": ["bold"] } + } + }, + "V": { + "groups": { + "mode": { "fg": "darkorange", "bg": "brightestorange", "attr": ["bold"] } + } + }, + "^V": { + "groups": { + "mode": { "fg": "darkorange", "bg": "brightestorange", "attr": ["bold"] } + } + }, + "R": { + "groups": { + "mode": { "fg": "white", "bg": "brightred", "attr": ["bold"] } + } + } + } +} diff --git a/config/powerline/colorschemes/vim/solarized.json b/config/powerline/colorschemes/vim/solarized.json new file mode 100644 index 0000000..2eb4c36 --- /dev/null +++ b/config/powerline/colorschemes/vim/solarized.json @@ -0,0 +1,91 @@ +{ + "name": "Solarized Dark", + "groups": { + "background": { "fg": "oldlace", "bg": "royalblue5" }, + "background:divider": { "fg": "lightskyblue4", "bg": "royalblue5" }, + "mode": { "fg": "oldlace", "bg": "green", "attr": ["bold"] }, + "modified_indicator": { "fg": "yellow", "bg": "darkgreencopper", "attr": ["bold"] }, + "paste_indicator": { "fg": "oldlace", "bg": "orange", "attr": ["bold"] }, + "readonly_indicator": { "fg": "red", "bg": "darkgreencopper" }, + "branch": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "branch_dirty": { "fg": "yellow", "bg": "darkgreencopper" }, + "branch_clean": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "branch:divider": { "fg": "gray61", "bg": "darkgreencopper" }, + "file_directory": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "file_name": { "fg": "oldlace", "bg": "darkgreencopper", "attr": ["bold"] }, + "file_size": { "fg": "oldlace", "bg": "darkgreencopper" }, + "file_name_no_file": { "fg": "oldlace", "bg": "darkgreencopper", "attr": ["bold"] }, + "file_name_empty": { "fg": "oldlace", "bg": "darkgreencopper" }, + "file_format": { "fg": "gray61", "bg": "royalblue5" }, + "file_encoding": { "fg": "gray61", "bg": "royalblue5" }, + "file_type": { "fg": "gray61", "bg": "royalblue5" }, + "file_vcs_status": { "fg": "red", "bg": "darkgreencopper" }, + "file_vcs_status_M": { "fg": "yellow", "bg": "darkgreencopper" }, + "file_vcs_status_A": { "fg": "green", "bg": "darkgreencopper" }, + "line_percent": { "fg": "oldlace", "bg": "lightskyblue4" }, + "line_percent_gradient": { "fg": "green_yellow_orange_red", "bg": "lightskyblue4" }, + "line_current": { "fg": "gray13", "bg": "lightyellow", "attr": ["bold"] }, + "line_current_symbol": { "fg": "gray13", "bg": "lightyellow" }, + "col_current": { "fg": "azure4", "bg": "lightyellow" } + }, + "mode_translations": { + "nc": { + "colors": { + "darkgreencopper": "royalblue5", + "lightskyblue4": "royalblue5", + "azure4": "darkgreencopper", + "gray61": "lightskyblue4", + "lightyellow": "azure4", + "oldlace": "gray61" + } + }, + "i": { + "groups": { + "background": { "fg": "oldlace", "bg": "darkgreencopper" }, + "background:divider": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "mode": { "fg": "oldlace", "bg": "blue", "attr": ["bold"] }, + "modified_indicator": { "fg": "yellow", "bg": "lightyellow", "attr": ["bold"] }, + "paste_indicator": { "fg": "oldlace", "bg": "orange", "attr": ["bold"] }, + "readonly_indicator": { "fg": "red", "bg": "lightyellow" }, + "branch": { "fg": "darkgreencopper", "bg": "lightyellow" }, + "branch:divider": { "fg": "lightskyblue4", "bg": "lightyellow" }, + "file_directory": { "fg": "darkgreencopper", "bg": "lightyellow" }, + "file_name": { "fg": "royalblue5", "bg": "lightyellow", "attr": ["bold"] }, + "file_size": { "fg": "royalblue5", "bg": "lightyellow" }, + "file_name_no_file": { "fg": "royalblue5", "bg": "lightyellow", "attr": ["bold"] }, + "file_name_empty": { "fg": "royalblue5", "bg": "lightyellow" }, + "file_format": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "file_encoding": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "file_type": { "fg": "lightyellow", "bg": "darkgreencopper" }, + "file_vcs_status": { "fg": "red", "bg": "lightyellow" }, + "file_vcs_status_M": { "fg": "yellow", "bg": "lightyellow" }, + "file_vcs_status_A": { "fg": "green", "bg": "lightyellow" }, + "line_percent": { "fg": "oldlace", "bg": "gray61" }, + "line_percent_gradient": { "fg": "oldlace", "bg": "gray61" }, + "line_current": { "fg": "gray13", "bg": "oldlace", "attr": ["bold"] }, + "line_current_symbol": { "fg": "gray13", "bg": "oldlace" }, + "col_current": { "fg": "azure4", "bg": "oldlace" } + } + }, + "v": { + "groups": { + "mode": { "fg": "oldlace", "bg": "orange", "attr": ["bold"] } + } + }, + "V": { + "groups": { + "mode": { "fg": "oldlace", "bg": "orange", "attr": ["bold"] } + } + }, + "^V": { + "groups": { + "mode": { "fg": "oldlace", "bg": "orange", "attr": ["bold"] } + } + }, + "R": { + "groups": { + "mode": { "fg": "oldlace", "bg": "red", "attr": ["bold"] } + } + } + } +} diff --git a/config/powerline/colorschemes/wm/default.json b/config/powerline/colorschemes/wm/default.json new file mode 100644 index 0000000..d71d4e3 --- /dev/null +++ b/config/powerline/colorschemes/wm/default.json @@ -0,0 +1,25 @@ +{ + "name": "Default color scheme for window managers", + "groups": { + "background:divider": { "fg": "gray5", "bg": "gray0" }, + "session": { "fg": "black", "bg": "gray10", "attr": ["bold"] }, + "date": { "fg": "gray8", "bg": "gray2" }, + "time": { "fg": "gray10", "bg": "gray2", "attr": ["bold"] }, + "time:divider": { "fg": "gray5", "bg": "gray2" }, + "email_alert": { "fg": "white", "bg": "brightred", "attr": ["bold"] }, + "email_alert_gradient": { "fg": "white", "bg": "yellow_orange_red", "attr": ["bold"] }, + "hostname": { "fg": "black", "bg": "gray10", "attr": ["bold"] }, + "weather": { "fg": "gray8", "bg": "gray0" }, + "weather_temp_gradient": { "fg": "blue_red", "bg": "gray0" }, + "weather_condition_hot": { "fg": "khaki1", "bg": "gray0" }, + "weather_condition_snowy": { "fg": "skyblue1", "bg": "gray0" }, + "weather_condition_rainy": { "fg": "skyblue1", "bg": "gray0" }, + "uptime": { "fg": "gray8", "bg": "gray0" }, + "external_ip": { "fg": "gray8", "bg": "gray0" }, + "network_load": { "fg": "gray8", "bg": "gray0" }, + "system_load": { "fg": "gray8", "bg": "gray0" }, + "system_load_good": { "fg": "lightyellowgreen", "bg": "gray0" }, + "system_load_bad": { "fg": "gold3", "bg": "gray0" }, + "system_load_ugly": { "fg": "orangered", "bg": "gray0" } + } +} diff --git a/config/powerline/config.json b/config/powerline/config.json new file mode 100644 index 0000000..a70922f --- /dev/null +++ b/config/powerline/config.json @@ -0,0 +1,48 @@ +{ + "common": { + "term_truecolor": false, + "dividers": { + "left": { + "hard": " ", + "soft": " " + }, + "right": { + "hard": " ", + "soft": " " + } + }, + "spaces": 1 + }, + "ext": { + "ipython": { + "colorscheme": "default", + "theme": "in", + "local_themes": { + "rewrite": "rewrite", + "out": "out", + "in2": "in2" + } + }, + "shell": { + "colorscheme": "default", + "theme": "default" + }, + "tmux": { + "colorscheme": "default", + "theme": "default" + }, + "vim": { + "colorscheme": "default", + "theme": "default", + "local_themes": { + "cmdwin": "cmdwin", + "help": "help", + "quickfix": "quickfix" + } + }, + "wm": { + "colorscheme": "default", + "theme": "default" + } + } +} diff --git a/config/powerline/themes/ipython/in.json b/config/powerline/themes/ipython/in.json new file mode 100644 index 0000000..ac979c5 --- /dev/null +++ b/config/powerline/themes/ipython/in.json @@ -0,0 +1,26 @@ +{ + "default_module": "powerline.segments.common", + "segments": { + "left": [ + { + "name": "virtualenv" + }, + { + "type": "string", + "contents": "In[", + "draw_soft_divider": false, + "highlight_group": ["prompt"] + }, + { + "name": "prompt_count", + "module": "powerline.segments.ipython", + "draw_soft_divider": false + }, + { + "type": "string", + "contents": "]", + "highlight_group": ["prompt"] + } + ] + } +} diff --git a/config/powerline/themes/ipython/in2.json b/config/powerline/themes/ipython/in2.json new file mode 100644 index 0000000..601fc9e --- /dev/null +++ b/config/powerline/themes/ipython/in2.json @@ -0,0 +1,13 @@ +{ + "default_module": "powerline.segments.common", + "segments": { + "left": [ + { + "type": "string", + "contents": "", + "width": "auto", + "highlight_group": ["prompt"] + } + ] + } +} diff --git a/config/powerline/themes/ipython/out.json b/config/powerline/themes/ipython/out.json new file mode 100644 index 0000000..11a6323 --- /dev/null +++ b/config/powerline/themes/ipython/out.json @@ -0,0 +1,25 @@ +{ + "default_module": "powerline.segments.common", + "segments": { + "left": [ + { + "type": "string", + "contents": "Out[", + "draw_soft_divider": false, + "width": "auto", + "align": "r", + "highlight_group": ["prompt"] + }, + { + "name": "prompt_count", + "module": "powerline.segments.ipython", + "draw_soft_divider": false + }, + { + "type": "string", + "contents": "]", + "highlight_group": ["prompt"] + } + ] + } +} diff --git a/config/powerline/themes/ipython/rewrite.json b/config/powerline/themes/ipython/rewrite.json new file mode 100644 index 0000000..47d8de0 --- /dev/null +++ b/config/powerline/themes/ipython/rewrite.json @@ -0,0 +1,23 @@ +{ + "segments": { + "left": [ + { + "type": "string", + "contents": "", + "draw_soft_divider": false, + "width": "auto", + "highlight_group": ["prompt"] + }, + { + "name": "prompt_count", + "module": "powerline.segments.ipython", + "draw_soft_divider": false + }, + { + "type": "string", + "contents": ">", + "highlight_group": ["prompt"] + } + ] + } +} diff --git a/config/powerline/themes/shell/default.json b/config/powerline/themes/shell/default.json new file mode 100644 index 0000000..6246a96 --- /dev/null +++ b/config/powerline/themes/shell/default.json @@ -0,0 +1,45 @@ +{ + "default_module": "powerline.segments.common", + "segment_data": { + "hostname": { + "before": " ", + "args": { + "only_if_ssh": true + } + }, + "virtualenv": { + "before": "ⓔ " + }, + "branch": { + "before": " " + } + }, + "segments": { + "left": [ + { + "name": "hostname" + }, + { + "name": "user" + }, + { + "name": "virtualenv" + }, + { + "name": "cwd", + "args": { + "dir_limit_depth": 3 + } + } + ], + "right": [ + { + "module": "powerline.segments.shell", + "name": "last_pipe_status" + }, + { + "name": "branch" + } + ] + } +} diff --git a/config/powerline/themes/shell/default_leftonly.json b/config/powerline/themes/shell/default_leftonly.json new file mode 100644 index 0000000..16af975 --- /dev/null +++ b/config/powerline/themes/shell/default_leftonly.json @@ -0,0 +1,43 @@ +{ + "default_module": "powerline.segments.common", + "segment_data": { + "hostname": { + "before": " ", + "args": { + "only_if_ssh": true + } + }, + "virtualenv": { + "before": "ⓔ " + }, + "branch": { + "before": " " + } + }, + "segments": { + "left": [ + { + "name": "hostname" + }, + { + "name": "user" + }, + { + "name": "virtualenv" + }, + { + "name": "branch" + }, + { + "name": "cwd", + "args": { + "dir_limit_depth": 3 + } + }, + { + "name": "last_status", + "module": "powerline.segments.shell" + } + ] + } +} diff --git a/config/powerline/themes/tmux/default.json b/config/powerline/themes/tmux/default.json new file mode 100644 index 0000000..2367821 --- /dev/null +++ b/config/powerline/themes/tmux/default.json @@ -0,0 +1,64 @@ +{ + "default_module": "powerline.segments.common", + "segment_data": { + "uptime": { + "before": "⇑ " + }, + "external_ip": { + "before": "ⓦ " + }, + "date": { + "before": "⌚ " + }, + "email_imap_alert": { + "before": "✉ ", + "args": { + "username": "", + "password": "" + } + } + }, + "segments": { + "right": [ + { + "name": "uptime", + "priority": 50 + }, + { + "name": "external_ip", + "priority": 50 + }, + { + "name": "network_load", + "priority": 50 + }, + { + "name": "system_load", + "priority": 50 + }, + { + "name": "weather", + "priority": 50 + }, + { + "name": "date" + }, + { + "name": "date", + "args": { + "format": "%H:%M", + "istime": true + } + }, + { + "name": "email_imap_alert", + "priority": 10 + }, + ], + "left" : [ + { + "name": "hostname" + } + ] + } +} diff --git a/config/powerline/themes/vim/cmdwin.json b/config/powerline/themes/vim/cmdwin.json new file mode 100644 index 0000000..c300d94 --- /dev/null +++ b/config/powerline/themes/vim/cmdwin.json @@ -0,0 +1,18 @@ +{ + "segments": { + "left": [ + { + "type": "string", + "contents": "Command Line", + "highlight_group": ["file_name"] + }, + { + "type": "string", + "highlight_group": ["background"], + "draw_soft_divider": false, + "draw_hard_divider": false, + "width": "auto" + } + ] + } +} diff --git a/config/powerline/themes/vim/default.json b/config/powerline/themes/vim/default.json new file mode 100644 index 0000000..29d6a2a --- /dev/null +++ b/config/powerline/themes/vim/default.json @@ -0,0 +1,108 @@ +{ + "segment_data": { + "branch": { + "before": " " + }, + "modified_indicator": { + "args": { "text": "+" } + }, + "line_percent": { + "args": { "gradient": true }, + "after": "%" + }, + "line_current_symbol": { + "contents": " " + } + }, + "segments": { + "left": [ + { + "name": "mode", + "exclude_modes": ["nc"] + }, + { + "name": "paste_indicator", + "exclude_modes": ["nc"], + "priority": 10 + }, + { + "name": "branch", + "exclude_modes": ["nc"], + "priority": 30 + }, + { + "name": "readonly_indicator", + "draw_soft_divider": false, + "after": " " + }, + { + "name": "file_directory", + "priority": 40, + "draw_soft_divider": false + }, + { + "name": "file_name", + "draw_soft_divider": false + }, + { + "name": "file_vcs_status", + "before": " ", + "draw_soft_divider": false + }, + { + "name": "modified_indicator", + "before": " " + }, + { + "type": "string", + "highlight_group": ["background"], + "draw_soft_divider": false, + "draw_hard_divider": false, + "width": "auto" + } + ], + "right": [ + { + "name": "file_format", + "draw_soft_divider": false, + "exclude_modes": ["nc"], + "priority": 60 + }, + { + "name": "file_encoding", + "exclude_modes": ["nc"], + "priority": 60 + }, + { + "name": "file_type", + "exclude_modes": ["nc"], + "priority": 60 + }, + { + "name": "line_percent", + "priority": 50, + "width": 4, + "align": "r" + }, + { + "type": "string", + "name": "line_current_symbol", + "highlight_group": ["line_current_symbol", "line_current"] + }, + { + "name": "line_current", + "draw_soft_divider": false, + "width": 3, + "align": "r" + }, + { + "name": "virtcol_current", + "draw_soft_divider": false, + "priority": 20, + "before": ":", + "width": 3, + "align": "l" + } + ] + } +} diff --git a/config/powerline/themes/vim/help.json b/config/powerline/themes/vim/help.json new file mode 100644 index 0000000..7407105 --- /dev/null +++ b/config/powerline/themes/vim/help.json @@ -0,0 +1,36 @@ +{ + "segments": { + "left": [ + { + "name": "file_name", + "draw_soft_divider": false + }, + { + "type": "string", + "highlight_group": ["background"], + "draw_soft_divider": false, + "draw_hard_divider": false, + "width": "auto" + } + ], + "right": [ + { + "name": "line_percent", + "priority": 30, + "width": 4, + "align": "r" + }, + { + "type": "string", + "name": "line_current_symbol", + "highlight_group": ["line_current_symbol", "line_current"] + }, + { + "name": "line_current", + "draw_soft_divider": false, + "width": 3, + "align": "r" + } + ] + } +} diff --git a/config/powerline/themes/vim/quickfix.json b/config/powerline/themes/vim/quickfix.json new file mode 100644 index 0000000..da77d63 --- /dev/null +++ b/config/powerline/themes/vim/quickfix.json @@ -0,0 +1,37 @@ +{ + "segment_data": { + "buffer_name": { + "contents": "Location List" + } + }, + "segments": { + "left": [ + { + "type": "string", + "name": "buffer_name", + "highlight_group": ["file_name"], + "draw_soft_divider": false + }, + { + "type": "string", + "highlight_group": ["background"], + "draw_soft_divider": false, + "draw_hard_divider": false, + "width": "auto" + } + ], + "right": [ + { + "type": "string", + "name": "line_current_symbol", + "highlight_group": ["line_current_symbol", "line_current"] + }, + { + "name": "line_current", + "draw_soft_divider": false, + "width": 3, + "align": "r" + } + ] + } +} diff --git a/config/powerline/themes/wm/default.json b/config/powerline/themes/wm/default.json new file mode 100644 index 0000000..c1cee4b --- /dev/null +++ b/config/powerline/themes/wm/default.json @@ -0,0 +1,31 @@ +{ + "default_module": "powerline.segments.common", + "segments": { + "right": [ + { + "name": "weather", + "priority": 50 + }, + { + "name": "date" + }, + { + "name": "date", + "args": { + "format": "%H:%M", + "istime": true + }, + "before": "⌚ " + }, + { + "name": "email_imap_alert", + "before": "✉ ", + "priority": 10, + "args": { + "username": "", + "password": "" + } + } + ] + } +} diff --git a/tmux-powerline b/tmux-powerline deleted file mode 160000 index 9a1c6b1..0000000 --- a/tmux-powerline +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9a1c6b12748fa807fbbe0c032e57fe85712a6d47 diff --git a/tmux.conf b/tmux.conf index 02772c0..cd64511 100644 --- a/tmux.conf +++ b/tmux.conf @@ -23,18 +23,7 @@ bind - split-window -v # set -g status-right '#[fg=black]#[bg=white]#(uptime)' # set -g status-right-length 70 -# powerline tmux -set-option -g status on -set-option -g status-bg colour12 -set-option -g status-fg colour7 -set-window-option -g window-status-current-bg colour9 -set-option -g status-interval 2 -set-option -g status-utf8 on -set-option -g status-justify "centre" -set-option -g status-left-length 60 -set-option -g status-right-length 90 -set-option -g status-left "#(~/.dotfiles/tmux-powerline/status-left.sh)" -set-option -g status-right "#(~/.dotfiles/tmux-powerline/status-right.sh)" +source /Users/benbeltran/Library/Python/2.7/lib/python/site-packages/powerline/bindings/tmux/powerline.conf #Set Activity monitoring. setw -g monitor-activity on diff --git a/vim/.netrwhist b/vim/.netrwhist index 6e853d2..03884d9 100644 --- a/vim/.netrwhist +++ b/vim/.netrwhist @@ -1,5 +1,6 @@ let g:netrw_dirhistmax =10 -let g:netrw_dirhist_cnt =3 +let g:netrw_dirhist_cnt =4 let g:netrw_dirhist_1='/Users/benbeltran/.newsbeuter' let g:netrw_dirhist_2='/Users/benbeltran/.vim' let g:netrw_dirhist_3='/Users/benbeltran/.dotfiles/tmux-powerline' +let g:netrw_dirhist_4='/Users/benbeltran/.config' diff --git a/vim/autoload/Powerline/Colorschemes/default.vim b/vim/autoload/Powerline/Colorschemes/default.vim deleted file mode 100644 index 1452cf4..0000000 --- a/vim/autoload/Powerline/Colorschemes/default.vim +++ /dev/null @@ -1,161 +0,0 @@ -call Pl#Hi#Allocate({ - \ 'black' : 16, - \ 'white' : 231, - \ - \ 'darkestgreen' : 22, - \ 'darkgreen' : 28, - \ 'mediumgreen' : 70, - \ 'brightgreen' : 148, - \ - \ 'darkestcyan' : 23, - \ 'mediumcyan' : 117, - \ - \ 'darkestblue' : 24, - \ 'darkblue' : 31, - \ - \ 'darkestred' : 52, - \ 'darkred' : 88, - \ 'mediumred' : 124, - \ 'brightred' : 160, - \ 'brightestred' : 196, - \ - \ 'darkestpurple' : 55, - \ 'mediumpurple' : 98, - \ 'brightpurple' : 189, - \ - \ 'brightorange' : 208, - \ 'brightestorange': 214, - \ - \ 'gray0' : 233, - \ 'gray1' : 235, - \ 'gray2' : 236, - \ 'gray3' : 239, - \ 'gray4' : 240, - \ 'gray5' : 241, - \ 'gray6' : 244, - \ 'gray7' : 245, - \ 'gray8' : 247, - \ 'gray9' : 250, - \ 'gray10' : 252, - \ }) - -let g:Powerline#Colorschemes#default#colorscheme = Pl#Colorscheme#Init([ - \ Pl#Hi#Segments(['SPLIT'], { - \ 'n': ['white', 'gray2'], - \ 'N': ['white', 'gray0'], - \ 'i': ['white', 'darkestblue'], - \ }), - \ - \ Pl#Hi#Segments(['mode_indicator'], { - \ 'n': ['darkestgreen', 'brightgreen', ['bold']], - \ 'i': ['darkestcyan', 'white', ['bold']], - \ 'v': ['darkred', 'brightorange', ['bold']], - \ 'r': ['white', 'brightred', ['bold']], - \ 's': ['white', 'gray5', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['branch', 'scrollpercent', 'raw', 'filesize'], { - \ 'n': ['gray9', 'gray4'], - \ 'N': ['gray3', 'gray1'], - \ 'i': ['mediumcyan', 'darkblue'], - \ }), - \ - \ Pl#Hi#Segments(['fileinfo', 'filename'], { - \ 'n': ['white', 'gray4', ['bold']], - \ 'N': ['gray7', 'gray1', ['bold']], - \ 'i': ['white', 'darkblue', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['static_str'], { - \ 'n': ['white', 'gray4'], - \ 'N': ['gray7', 'gray1'], - \ 'i': ['white', 'darkblue'], - \ }), - \ - \ Pl#Hi#Segments(['fileinfo.flags'], { - \ 'n': ['brightestred', ['bold']], - \ 'N': ['darkred'], - \ 'i': ['brightestred', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['current_function', 'fileformat', 'fileencoding', 'pwd', 'filetype', 'rvm:string', 'rvm:statusline', 'virtualenv:statusline', 'charcode', 'currhigroup'], { - \ 'n': ['gray8', 'gray2'], - \ 'i': ['mediumcyan', 'darkestblue'], - \ }), - \ - \ Pl#Hi#Segments(['lineinfo'], { - \ 'n': ['gray2', 'gray10', ['bold']], - \ 'N': ['gray7', 'gray1', ['bold']], - \ 'i': ['darkestcyan', 'mediumcyan', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['errors'], { - \ 'n': ['brightestorange', 'gray2', ['bold']], - \ 'i': ['brightestorange', 'darkestblue', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['lineinfo.line.tot'], { - \ 'n': ['gray6'], - \ 'N': ['gray5'], - \ 'i': ['darkestcyan'], - \ }), - \ - \ Pl#Hi#Segments(['ws_marker'], { - \ 'n': ['white', 'brightestred'], - \ 'i': ['darkestcyan', 'white'], - \ }), - \ - \ Pl#Hi#Segments(['gundo:static_str.name', 'command_t:static_str.name'], { - \ 'n': ['white', 'mediumred', ['bold']], - \ 'N': ['brightred', 'darkestred', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['gundo:static_str.buffer', 'command_t:raw.line'], { - \ 'n': ['white', 'darkred'], - \ 'N': ['brightred', 'darkestred'], - \ }), - \ - \ Pl#Hi#Segments(['gundo:SPLIT', 'command_t:SPLIT'], { - \ 'n': ['white', 'darkred'], - \ 'N': ['white', 'darkestred'], - \ }), - \ - \ Pl#Hi#Segments(['lustyexplorer:static_str.name', 'minibufexplorer.static_str.name', 'nerdtree:raw.name', 'tagbar:static_str.name'], { - \ 'n': ['white', 'mediumgreen', ['bold']], - \ 'N': ['mediumgreen', 'darkestgreen', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['lustyexplorer:static_str.buffer', 'tagbar:static_str.buffer'], { - \ 'n': ['brightgreen', 'darkgreen'], - \ 'N': ['mediumgreen', 'darkestgreen'], - \ }), - \ - \ Pl#Hi#Segments(['lustyexplorer:SPLIT', 'minibufexplorer:SPLIT', 'nerdtree:SPLIT', 'tagbar:SPLIT'], { - \ 'n': ['white', 'darkgreen'], - \ 'N': ['white', 'darkestgreen'], - \ }), - \ - \ Pl#Hi#Segments(['ctrlp:focus', 'ctrlp:byfname'], { - \ 'n': ['brightpurple', 'darkestpurple'], - \ }), - \ - \ Pl#Hi#Segments(['ctrlp:prev', 'ctrlp:next', 'ctrlp:pwd'], { - \ 'n': ['white', 'mediumpurple'], - \ }), - \ - \ Pl#Hi#Segments(['ctrlp:item'], { - \ 'n': ['darkestpurple', 'white', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['ctrlp:marked'], { - \ 'n': ['brightestred', 'darkestpurple', ['bold']], - \ }), - \ - \ Pl#Hi#Segments(['ctrlp:count'], { - \ 'n': ['darkestpurple', 'white'], - \ }), - \ - \ Pl#Hi#Segments(['ctrlp:SPLIT'], { - \ 'n': ['white', 'darkestpurple'], - \ }), - \ ]) diff --git a/vim/autoload/Powerline/Functions.vim b/vim/autoload/Powerline/Functions.vim deleted file mode 100644 index b170ca8..0000000 --- a/vim/autoload/Powerline/Functions.vim +++ /dev/null @@ -1,90 +0,0 @@ -" Recalculate the trailing whitespace warning when idle, and after saving -autocmd CursorHold,BufWritePost,InsertLeave * unlet! b:statusline_trailing_space_warning - -function! Powerline#Functions#GetMode() " {{{ - let mode = mode() - - if mode =~# '\v(v|V|)' - " Visual mode - if mode ==# 'v' - let mode = 'VISUAL' - elseif mode ==# 'V' - let mode = 'V·LINE' - elseif mode ==# '' - let mode = 'V·BLOCK' - endif - elseif mode =~# '\v(s|S|)' - " Select mode - if mode ==# 's' - let mode = 'SELECT' - elseif mode ==# 'S' - let mode = 'S·LINE' - elseif mode ==# '' - let mode = 'S·BLOCK' - endif - elseif mode =~# '\vi' - let mode = 'INSERT' " Insert mode - elseif mode =~# '\v(R|Rv)' - let mode = 'REPLACE' " Replace mode - else - " Fallback to normal mode - let mode = ' N ' " Normal (current) - endif - - return mode -endfunction " }}} -function! Powerline#Functions#GetFilesize() " {{{ - let bytes = getfsize(expand("%:p")) - - if bytes <= 0 - return '' - endif - - if bytes < 1024 - return bytes . 'B' - else - return (bytes / 1024) . 'kB' - endif -endfunction "}}} -function! Powerline#Functions#GetCharCode() " {{{ - " Get the output of :ascii - redir => ascii - silent! ascii - redir END - - if match(ascii, 'NUL') != -1 - return 'NUL' - endif - - " Zero pad hex values - let nrformat = '0x%02x' - - let encoding = (&fenc == '' ? &enc : &fenc) - - if encoding == 'utf-8' - " Zero pad with 4 zeroes in unicode files - let nrformat = '0x%04x' - endif - - " Get the character and the numeric value from the return value of :ascii - " This matches the two first pieces of the return value, e.g. - " " 70" => char: 'F', nr: '70' - let [str, char, nr; rest] = matchlist(ascii, '\v\<(.{-1,})\>\s*([0-9]+)') - - " Format the numeric value - let nr = printf(nrformat, nr) - - return "'". char ."' ". nr -endfunction "}}} -function! Powerline#Functions#GetWSMarker() " {{{ - " Return '...' if trailing white space is detected - " Return '' otherwise - if ! exists("b:statusline_trailing_space_warning") - if search('\s$', 'nw') != 0 - let b:statusline_trailing_space_warning = ' … ' - else - let b:statusline_trailing_space_warning = '' - endif - endif - return b:statusline_trailing_space_warning -endfunction " }}} diff --git a/vim/autoload/Powerline/Functions/cfi.vim b/vim/autoload/Powerline/Functions/cfi.vim deleted file mode 100644 index a7b472c..0000000 --- a/vim/autoload/Powerline/Functions/cfi.vim +++ /dev/null @@ -1,3 +0,0 @@ -function! Powerline#Functions#cfi#GetCurrentFunction() " {{{ - return cfi#format('%s', '') -endfunction " }}} diff --git a/vim/autoload/Powerline/Functions/ft_man.vim b/vim/autoload/Powerline/Functions/ft_man.vim deleted file mode 100644 index 29135e4..0000000 --- a/vim/autoload/Powerline/Functions/ft_man.vim +++ /dev/null @@ -1,12 +0,0 @@ -function! Powerline#Functions#ft_man#GetName() " {{{ - let matches = matchlist(getline(1), '\v^([a-zA-Z_\.\-]+)\((\d+)\)') - - if ! len(matches) - return 'n/a' - endif - - let file = tolower(matches[1]) - let num = matches[2] - - return file -endfunction " }}} diff --git a/vim/autoload/Powerline/Functions/fugitive.vim b/vim/autoload/Powerline/Functions/fugitive.vim deleted file mode 100644 index bb00131..0000000 --- a/vim/autoload/Powerline/Functions/fugitive.vim +++ /dev/null @@ -1,7 +0,0 @@ -function! Powerline#Functions#fugitive#GetBranch(symbol) " {{{ - let ret = fugitive#statusline() - - let ret = substitute(ret, '\c\v\[?GIT\(([a-z0-9\-_\./:]+)\)\]?', a:symbol .' \1', 'g') - - return ret -endfunction " }}} diff --git a/vim/autoload/Powerline/Functions/syntastic.vim b/vim/autoload/Powerline/Functions/syntastic.vim deleted file mode 100644 index e2c04fa..0000000 --- a/vim/autoload/Powerline/Functions/syntastic.vim +++ /dev/null @@ -1,16 +0,0 @@ -function! Powerline#Functions#syntastic#GetErrors(line_symbol) " {{{ - if ! exists('g:syntastic_stl_format') - " Syntastic hasn't been loaded yet - return '' - endif - - " Temporarily change syntastic output format - let old_stl_format = g:syntastic_stl_format - let g:syntastic_stl_format = '╱╱╱%E{ ERRORS (%e) '. a:line_symbol .' %fe }%W{ WARNINGS (%w) '. a:line_symbol .' %fw }╱╱╱' - - let ret = SyntasticStatuslineFlag() - - let g:syntastic_stl_format = old_stl_format - - return ret -endfunction " }}} diff --git a/vim/autoload/Powerline/Matches.vim b/vim/autoload/Powerline/Matches.vim deleted file mode 100644 index a71f734..0000000 --- a/vim/autoload/Powerline/Matches.vim +++ /dev/null @@ -1,13 +0,0 @@ -let g:Powerline#Matches#matches = { - \ 'command_t' : Pl#Match#Add('bufname("%")', 'GoToFile'), - \ 'ft_help' : Pl#Match#Add('&ft' , 'help'), - \ 'ft_man' : Pl#Match#Add('&ft' , 'man'), - \ 'ft_qf' : Pl#Match#Add('&ft' , 'qf'), - \ 'ft_vimpager' : Pl#Match#Add('&ft' , 'vimpager'), - \ 'gundo_preview' : Pl#Match#Add('bufname("%")', '__Gundo_Preview__'), - \ 'gundo_tree' : Pl#Match#Add('bufname("%")', '__Gundo__'), - \ 'lustyexplorer' : Pl#Match#Add('bufname("%")', '\[LustyExplorer-Buffers\]'), - \ 'minibufexplorer' : Pl#Match#Add('bufname("%")', '\-MiniBufExplorer\-'), - \ 'tagbar' : Pl#Match#Add('&ft' , 'tagbar'), - \ 'nerdtree' : Pl#Match#Add('&ft' , 'nerdtree'), -\ } diff --git a/vim/autoload/Powerline/Segments.vim b/vim/autoload/Powerline/Segments.vim deleted file mode 100644 index 837ec5f..0000000 --- a/vim/autoload/Powerline/Segments.vim +++ /dev/null @@ -1,28 +0,0 @@ -let g:Powerline#Segments#segments = Pl#Segment#Init( - \ Pl#Segment#Create('SPLIT' , '__split__'), - \ Pl#Segment#Create('TRUNCATE', '__truncate__'), - \ - \ Pl#Segment#Create('mode_indicator' , '%{Powerline#Functions#GetMode()}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('fileinfo', - \ Pl#Segment#Create('flags.ro' , '%{&readonly ? "$RO" : ""}'), - \ Pl#Segment#Create('name' , '%t'), - \ Pl#Segment#Create('flags.mod' , '%M'), - \ Pl#Segment#Create('flags.type' , '%H%W'), - \ ), - \ Pl#Segment#Create('filename' , '%t'), - \ Pl#Segment#Create('filesize' , '%{Powerline#Functions#GetFilesize()}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('pwd' , '%{substitute(getcwd(), expand("$HOME"), "~", "g")}'), - \ Pl#Segment#Create('static_str' , '%%{"%s"}'), - \ Pl#Segment#Create('raw' , '%s'), - \ Pl#Segment#Create('fileformat' , '%{&fileformat}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('fileencoding' , '%{(&fenc == "" ? &enc : &fenc)}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('filetype' , '%{strlen(&ft) ? &ft : "no ft"}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('scrollpercent' , '%3p%%'), - \ Pl#Segment#Create('lineinfo', - \ Pl#Segment#Create('line.cur' , '$LINE %3l'), - \ Pl#Segment#Create('line.tot' , '$COL %-2c'), - \ ), - \ Pl#Segment#Create('charcode' , '%{Powerline#Functions#GetCharCode()}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('currhigroup' , '%{synIDattr(synID(line("."), col("."), 1), "name")}', Pl#Segment#Modes('!N')), - \ Pl#Segment#Create('ws_marker' , '%{Powerline#Functions#GetWSMarker()}', Pl#Segment#Modes('!N')), -\ ) diff --git a/vim/autoload/Powerline/Segments/cfi.vim b/vim/autoload/Powerline/Segments/cfi.vim deleted file mode 100644 index bde558b..0000000 --- a/vim/autoload/Powerline/Segments/cfi.vim +++ /dev/null @@ -1,5 +0,0 @@ -let g:Powerline#Segments#cfi#segments = Pl#Segment#Init('cfi', - \ (exists('g:cfi_disable') && g:cfi_disable == 0), - \ - \ Pl#Segment#Create('current_function', '%{Powerline#Functions#cfi#GetCurrentFunction()}', Pl#Segment#Modes('!N')) -\ ) diff --git a/vim/autoload/Powerline/Segments/ctrlp.vim b/vim/autoload/Powerline/Segments/ctrlp.vim deleted file mode 100644 index bab5193..0000000 --- a/vim/autoload/Powerline/Segments/ctrlp.vim +++ /dev/null @@ -1,10 +0,0 @@ -let g:Powerline#Segments#ctrlp#segments = Pl#Segment#Init('ctrlp' - \ , Pl#Segment#Create('focus', '%{"%0"}') - \ , Pl#Segment#Create('byfname', '%{"%1"}') - \ , Pl#Segment#Create('prev', '%-3{"%3"}') - \ , Pl#Segment#Create('item', '%-9{"%4"}') - \ , Pl#Segment#Create('next', '%-3{"%5"}') - \ , Pl#Segment#Create('marked', '%{"%6" == " <+>" ? "" : strpart("%6", 2, len("%6") - 3)}') - \ - \ , Pl#Segment#Create('count', '%-6{"%0"}') -\ ) diff --git a/vim/autoload/Powerline/Segments/ft_man.vim b/vim/autoload/Powerline/Segments/ft_man.vim deleted file mode 100644 index ee11849..0000000 --- a/vim/autoload/Powerline/Segments/ft_man.vim +++ /dev/null @@ -1,3 +0,0 @@ -let g:Powerline#Segments#ft_man#segments = Pl#Segment#Init('ft_man', - \ Pl#Segment#Create('filename', '%{Powerline#Functions#ft_man#GetName()}') -\ ) diff --git a/vim/autoload/Powerline/Segments/fugitive.vim b/vim/autoload/Powerline/Segments/fugitive.vim deleted file mode 100644 index 297556b..0000000 --- a/vim/autoload/Powerline/Segments/fugitive.vim +++ /dev/null @@ -1,5 +0,0 @@ -let g:Powerline#Segments#fugitive#segments = Pl#Segment#Init('fugitive', - \ (exists('g:loaded_fugitive') && g:loaded_fugitive == 1), - \ - \ Pl#Segment#Create('branch', '%{Powerline#Functions#fugitive#GetBranch("$BRANCH")}') -\ ) diff --git a/vim/autoload/Powerline/Segments/rvm.vim b/vim/autoload/Powerline/Segments/rvm.vim deleted file mode 100644 index 7e34245..0000000 --- a/vim/autoload/Powerline/Segments/rvm.vim +++ /dev/null @@ -1,5 +0,0 @@ -let g:Powerline#Segments#rvm#segments = Pl#Segment#Init('rvm', - \ (exists('g:loaded_rvm') && g:loaded_rvm == 1), - \ Pl#Segment#Create('string', '%{rvm#string()}'), - \ Pl#Segment#Create('statusline', '%{rvm#statusline()}') -\ ) diff --git a/vim/autoload/Powerline/Segments/syntastic.vim b/vim/autoload/Powerline/Segments/syntastic.vim deleted file mode 100644 index 2f0caa9..0000000 --- a/vim/autoload/Powerline/Segments/syntastic.vim +++ /dev/null @@ -1,5 +0,0 @@ -let g:Powerline#Segments#syntastic#segments = Pl#Segment#Init('syntastic', - \ (exists('g:loaded_syntastic_plugin') && g:loaded_syntastic_plugin == 1), - \ - \ Pl#Segment#Create('errors', '%{Powerline#Functions#syntastic#GetErrors("$LINE")}', Pl#Segment#Modes('!N')) -\ ) diff --git a/vim/autoload/Powerline/Segments/virtualenv.vim b/vim/autoload/Powerline/Segments/virtualenv.vim deleted file mode 100644 index 90661f1..0000000 --- a/vim/autoload/Powerline/Segments/virtualenv.vim +++ /dev/null @@ -1,5 +0,0 @@ -let g:Powerline#Segments#virtualenv#segments = Pl#Segment#Init('virtualenv', - \ has('python') && (exists('g:virtualenv_loaded') && g:virtualenv_loaded == 1), - \ - \ Pl#Segment#Create('statusline', '%{VirtualEnvStatusline()}') -\ ) diff --git a/vim/autoload/Powerline/Themes/default.vim b/vim/autoload/Powerline/Themes/default.vim deleted file mode 100644 index 75106eb..0000000 --- a/vim/autoload/Powerline/Themes/default.vim +++ /dev/null @@ -1,114 +0,0 @@ -let g:Powerline#Themes#default#theme = Pl#Theme#Create( - \ Pl#Theme#Buffer('' - \ , 'mode_indicator' - \ , 'fugitive:branch' - \ , 'fileinfo' - \ , 'syntastic:errors' - \ , Pl#Segment#Truncate() - \ , 'cfi:current_function' - \ , Pl#Segment#Split() - \ , 'rvm:string' - \ , 'virtualenv:statusline' - \ , 'fileformat' - \ , 'fileencoding' - \ , 'filetype' - \ , 'scrollpercent' - \ , 'lineinfo' - \ ), - \ - \ Pl#Theme#Buffer('command_t' - \ , ['static_str.name', 'Command-T'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ , ['raw.line', '%10(Match #%l%)'] - \ ), - \ - \ Pl#Theme#Buffer('gundo', Pl#Match#Any('gundo_tree') - \ , ['static_str.name', 'Gundo'] - \ , ['static_str.buffer', 'Undo tree'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ), - \ - \ Pl#Theme#Buffer('gundo', Pl#Match#Any('gundo_preview') - \ , ['static_str.name', 'Gundo'] - \ , ['static_str.buffer', 'Diff preview'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ), - \ - \ Pl#Theme#Buffer('ft_help' - \ , ['static_str.name', 'Help'] - \ , 'filename' - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ , 'scrollpercent' - \ ), - \ - \ Pl#Theme#Buffer('ft_vimpager' - \ , ['static_str.name', 'Pager'] - \ , 'filename' - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ , 'scrollpercent' - \ ), - \ - \ Pl#Theme#Buffer('lustyexplorer' - \ , ['static_str.name', 'LustyExplorer'] - \ , ['static_str.buffer', 'Buffer list'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ), - \ - \ Pl#Theme#Buffer('ft_man' - \ , ['static_str.name', 'Man page'] - \ , 'filename' - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ , 'scrollpercent' - \ ), - \ - \ Pl#Theme#Buffer('minibufexplorer' - \ , ['static_str.name', 'MiniBufExplorer'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ), - \ - \ Pl#Theme#Buffer('ft_qf' - \ , ['static_str.name', 'Quickfix'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ), - \ - \ Pl#Theme#Buffer('tagbar' - \ , ['static_str.name', 'Tagbar'] - \ , ['static_str.buffer', 'Tree'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ), - \ - \ Pl#Theme#Buffer('ctrlp', Pl#Theme#Callback('ctrlp_main', 'if ! exists("g:ctrlp_status_func") | let g:ctrlp_status_func = {} | endif | let g:ctrlp_status_func.main = "%s"') - \ , 'ctrlp:prev' - \ , 'ctrlp:item' - \ , 'ctrlp:next' - \ , 'ctrlp:marked' - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ , 'ctrlp:focus' - \ , 'ctrlp:byfname' - \ , 'pwd' - \ ), - \ - \ Pl#Theme#Buffer('ctrlp', Pl#Theme#Callback('ctrlp_prog', 'if ! exists("g:ctrlp_status_func") | let g:ctrlp_status_func = {} | endif | let g:ctrlp_status_func.prog = "%s"') - \ , 'ctrlp:count' - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ , 'pwd' - \ ), - \ - \ Pl#Theme#Buffer('nerdtree' - \ , ['raw.name', '%{expand("%:p:h")}'] - \ , Pl#Segment#Truncate() - \ , Pl#Segment#Split() - \ ) -\ ) diff --git a/vim/doc/Powerline.txt b/vim/doc/Powerline.txt deleted file mode 100644 index 7ec7a50..0000000 --- a/vim/doc/Powerline.txt +++ /dev/null @@ -1,322 +0,0 @@ -*Powerline.txt* For Vim version 7.3. Last change: 2011 Nov 23 - - ______ - _________ \ /__ - \_____ \______ _ _____________ / /'__' ___ ____ - | ___/ _ \ \/ \/ / __ \_ ___\ / | |/ \_/ __ \ - | | | (_) \ _ / ___/| | / /__| | | \ ___/ - '___' \____/ \/ \/ \___ |__' /___ /'__'__| /\___ \ - \/ / / \/ \/ - | / - |/ - ' - -============================================================================== -CONTENTS *Powerline-contents* - - 1. Introduction ....................... |Powerline-introduction| - 2. Usage .............................. |Powerline-usage| - 3. Requirements ....................... |Powerline-requirements| - 3.1 Recommended settings ........... |Powerline-recommended-settings| - 4. Configuration ...................... |Powerline-configuration| - 4.1 Powerline_cache_file ........... |Powerline_cache_file| - 4.1.1 Clearing the cache ....... |:PowerlineClearCache| - 4.2 Powerline_cache_enabled ........ |Powerline_cache_enabled| - 4.3 Powerline_symbols .............. |Powerline_symbols| - 4.3.1 Compatible symbols ....... |Powerline-symbols-compatible| - 4.3.2 Fancy symbols ............ |Powerline-symbols-fancy| - 4.4 Powerline_theme ................ |Powerline_theme| - 4.5 Powerline_colorscheme .......... |Powerline_colorscheme| - 5. Fonts .............................. |Powerline-fonts| - 6. Customization ...................... |Powerline-customization| - 6.1 Basic customization ............ |Powerline-basic-customization| - 6.2 Advanced customization ......... |Powerline-advanced-customization| - 6.2.1 Colorschemes ............. |Powerline-cust-colorschemes| - 6.2.2 Functions ................ |Powerline-cust-functions| - 6.2.3 Segments ................. |Powerline-cust-segments| - 6.2.4 Themes ................... |Powerline-cust-themes| - 7. License ............................ |Powerline-license| - 8. Known issues ....................... |Powerline-known-issues| - 9. Contributing ....................... |Powerline-contributing| - -============================================================================== -1. Introduction *Powerline* *Powerline-introduction* - -Powerline is a utility plugin which allows you to create better-looking, more -functional vim statuslines. - -============================================================================== -2. Usage *Powerline-usage* - -Powerline is automatically enabled when it's installed, either by unzipping -the provided archive or by adding it as a Pathogen/Vundle bundle. - -============================================================================== -3. Requirements *Powerline-requirements* - -Powerline has been developed and tested in vim 7.3, but it should run without -any problems in vim 7.2. The default configuration requires a Unix-like system -to work properly. - -The plugin only works with vim running in an 88/256-color terminal or gvim. - -Vi-compatible mode must be disabled. - ------------------------------------------------------------------------------- -3.1 Recommended settings *Powerline-recommended-settings* - -The following configuration options should be set in your |vimrc|: > - - set nocompatible " Disable vi-compatibility - set laststatus=2 " Always show the statusline - set encoding=utf-8 " Necessary to show unicode glyphs - -Note: If you're using an 88/256-color terminal but still don't see the colored -statusline, you may have to set the following option as well: > - - set t_Co=256 " Explicitly tell vim that the terminal supports 256 colors - -============================================================================== -4. Configuration *Powerline-configuration* - -Powerline will work fine without any user configuration, but default behavior -can be overridden by setting configuration variables globally in your |vimrc| -file. - ------------------------------------------------------------------------------- -4.1 Powerline_cache_file *Powerline_cache_file* - -By default Powerline caches all the statuslines and colors in a cache file in -the plugin's directory (or the vim directory, depending on the installation -method used). - -It's recommended that you enable the cache, as this dramatically improves vim -startup time after the cache file has been generated (the plugin usually loads -within ~100ms without the cache and ~1ms with the cache). - -Note: The default cache filename includes the current theme, colorscheme and -symbol settings in order to tie the cache file your current configuration, so -the cache file will be regenerated when you change any settings. This may -leave several old cache files in your vim folder, and these may safely be -deleted. - -Defaults: "/Powerline___.cache" - ------------------------------------------------------------------------------- -4.1.1 Clearing the cache *:PowerlineClearCache* - -Powerline provides a command to easily clear the cache after changing your -settings or updating your theme. Simply run the following command to clear -your cache, and restart vim afterwards: > - - :PowerlineClearCache -< ------------------------------------------------------------------------------- -4.2 Powerline_cache_enabled *Powerline_cache_enabled* - -It's possible to disable statusline caching by setting this option to 0. This -is mostly useful when developing statuslines. - -Default: 1 - ------------------------------------------------------------------------------- -4.3 Powerline_symbols *Powerline_symbols* - -This option defines which set of symbols and dividers you want to use. There -are currently three available options: "compatible", "unicode" and "fancy". - - TYPE DESCRIPTION ~ - compatible Doesn't use any special characters. - unicode Simulates icons and arrows using similar unicode glyphs. - fancy Custom icons and arrows. Requires a patched font. - -Symbols can be inserted into statuslines by using the following variables -(just insert the variables as text in your segments): - - VARIABLE DESCRIPTION ~ - $BRANCH Inserts a branch symbol - $RO Inserts a read-only symbol - $FT Inserts a filetype symbol - $LINE Inserts a line number symbol - -Default: "compatible" - ------------------------------------------------------------------------------- -4.3.1 Compatible symbols *Powerline-symbols-compatible* - -These symbols will work in any configuration, and do not require a special -font to work. This option will replace the fancy icons with plain text, and -the pointy dividers with straight lines. - ------------------------------------------------------------------------------- -4.3.2 Fancy symbols *Powerline-symbols-fancy* - -These symbols require a custom font to work. A font patcher is provided for -adding the required symbols to any outline font and some bitmap fonts, see -|Powerline-fonts| and the provided README file for usage details. - ------------------------------------------------------------------------------- -4.4 Powerline_theme *Powerline_theme* - -This option defines the theme Powerline uses. The available themes are located -in autoload/Powerline/Themes/. - -Default: "default" - ------------------------------------------------------------------------------- -4.5 Powerline_colorscheme *Powerline_colorscheme* - -This option defines the colorscheme Powerline uses. The available colorschemes -are located in autoload/Powerline/Colorschemes/. - -Default: "default" - -============================================================================== -5. Fonts *Powerline-fonts* - -TODO - -============================================================================== -6. Customization *Powerline-customization* - -There are currently two ways of customizing Powerline: Basic customization -using a couple of functions to insert and remove existing segments from the -statusline, and advanced customization using your own autoload files. The -customization features of Powerline allow you to create your own statuslines -without ever touching the original source code. - ------------------------------------------------------------------------------- -6.1 Basic customization *Powerline-basic-customization* - -Powerline provides the following functions to alter the default statusline -look. These functions should be called from your |vimrc| file or another file -which is sourced at vim startup. - -Note: These functions are currently applied to all statuslines, so if you -insert a segment after a segment which is present in many statuslines (e.g. -the "filename" segment), all the statuslines will have the inserted segment. -This behavior may be changed in a future version of Powerline. - -Note: Remember to clear your cache with |:PowerlineClearCache| after changing -your statusline! - -Example: > - - " Insert the charcode segment after the filetype segment - call Pl#Theme#InsertSegment('charcode', 'after', 'filetype') - - " Replace the scrollpercent segment with the charcode segment - call Pl#Theme#ReplaceSegment('scrollpercent', 'fileinfo') -< - *Pl#Theme#InsertSegment* -Pl#Theme#InsertSegment({newsegment}, {location}, {targetsegment}) - -This function inserts {newsegment} before or after {targetsegment}. The -{location} parameter specifies the location of the new segment, valid values -are "before" and "after". You can see all the available segments in -autoload/Powerline/Segments.vim and the files specified in -|Powerline-cust-segments|. - -Pl#Theme#RemoveSegment({targetsegment}) *Pl#Theme#RemoveSegment* - -This function removes the {targetsegment} segment entirely. - -Pl#Theme#ReplaceSegment({oldsegment}, {newsegment}) *Pl#Theme#ReplaceSegment* - -This function replaces {oldsegment} with {newsegment}. - ------------------------------------------------------------------------------- -6.2 Advanced customization *Powerline-advanced-customization* - -Because Powerline utilizes vim's autoload functionality, you can easily create -your own segments, themes, functions and colorschemes without touching the -original source code. This is a bit more complex than using the utility -functions, but it allows you to do a lot more with your statusline. - -Your custom autoload files should be stored in your |runtimepath| (usually in -"~/.vim/autoload/Powerline/*"). - -Note: Remember to clear your cache with |:PowerlineClearCache| after changing -your statusline! - -6.2.1 Colorschemes *Powerline-cust-colorschemes* ------------------------------------------------------------------------------- - -Colorschemes should be stored as separate files in -{runtimepath}/autoload/Powerline/Colorschemes/. - -SYNTAX ~ - -TODO - -EXAMPLE ~ - -TODO - -6.2.2 Functions *Powerline-cust-functions* ------------------------------------------------------------------------------- - -Functions should be stored as separate files in -{runtimepath}/autoload/Powerline/Functions/. - -SYNTAX ~ - -TODO - -EXAMPLE ~ - -TODO - -6.2.3 Segments *Powerline-cust-segments* ------------------------------------------------------------------------------- - -Segments should be stored as separate files in -{runtimepath}/autoload/Powerline/Segments/. - -SYNTAX ~ - -TODO - -EXAMPLE ~ - -TODO - -6.2.4 Themes *Powerline-cust-themes* ------------------------------------------------------------------------------- - -Themes should be stored as separate files in -{runtimepath}/autoload/Powerline/Themes/. - -SYNTAX ~ - -TODO - -EXAMPLE ~ - -TODO - -============================================================================== -7. License *Powerline-license* - -Creative Commons Attribution-ShareAlike 3.0 Unported - -http://creativecommons.org/licenses/by-sa/3.0/ - -============================================================================== -8. Known issues *Powerline-known-issues* - -See the issue tracker at -https://github.com/Lokaltog/vim-powerline/issues - -============================================================================== -9. Contributing *Powerline-contributing* - -If you experience any bugs or have feature requests, please open an issue on -GitHub. Fork the source repository on GitHub and send a pull request if you -have any code improvements. - -Author: Kim Silkebækken -Source repository: https://github.com/Lokaltog/vim-powerline - -============================================================================== -vim:tw=78:sw=4:ts=8:ft=help:norl: diff --git a/vim/plugin/Powerline.vim b/vim/plugin/Powerline.vim deleted file mode 100644 index 12b4204..0000000 --- a/vim/plugin/Powerline.vim +++ /dev/null @@ -1,56 +0,0 @@ -" Powerline - The ultimate statusline utility -" -" Author: Kim Silkebækken -" Source repository: https://github.com/Lokaltog/vim-powerline - -" Script initialization {{{ - if exists('g:Powerline_loaded') || &compatible || version < 702 - finish - endif - - let g:Powerline_loaded = 1 -" }}} -" Commands {{{ - command! PowerlineClearCache call Pl#ClearCache() - command! PowerlineReloadColorscheme call Pl#ReloadColorscheme() -" }}} -" Set default options {{{ - for [s:key, s:value] in items({ - \ 'theme' : 'default' - \ , 'colorscheme' : 'default' - \ , 'symbols' : 'compatible' - \ , 'cache_enabled': 1 - \ }) - - if ! exists('g:Powerline_' . s:key) - exec printf('let g:Powerline_%s = %s', s:key, string(s:value)) - endif - endfor - - if ! exists('g:Powerline_cache_file') - exec 'let g:Powerline_cache_file = '. string(printf('%s/Powerline_%s_%s_%s.cache' - \ , simplify(expand(':p:h') .'/..') - \ , g:Powerline_theme - \ , g:Powerline_colorscheme - \ , g:Powerline_symbols - \ )) - endif -" }}} -" Autocommands {{{ - augroup Powerline - autocmd! - - " Reload statuslines when changing color scheme - au ColorScheme * - \ call Pl#Load() - - au BufEnter,WinEnter,FileType,BufUnload * - \ call Pl#UpdateStatusline(1) - - au BufLeave,WinLeave * - \ call Pl#UpdateStatusline(0) - - au BufWritePost */autoload/Powerline/Colorschemes/*.vim - \ :PowerlineReloadColorscheme - augroup END -" }}} diff --git a/vimrc b/vimrc index eea2e28..bf76925 100755 --- a/vimrc +++ b/vimrc @@ -161,7 +161,7 @@ set nofoldenable set foldlevel=1 " powerline stuff -let g:Powerline_symbols = 'fancy' +set rtp+=/Users/benbeltran/Library/Python/2.7/lib/python/site-packages/powerline/bindings/vim " Fix CtrlP root folder and add some ignores let g:ctrlp_working_path_mode = 0 -- cgit From 6c451d345b0d55c24e6d368597d22f9165fa3c95 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Tue, 16 Apr 2013 08:33:35 -0500 Subject: Add vim-json bundle --- vim/bundle/vim-json | 1 + 1 file changed, 1 insertion(+) create mode 160000 vim/bundle/vim-json diff --git a/vim/bundle/vim-json b/vim/bundle/vim-json new file mode 160000 index 0000000..4a0bb3e --- /dev/null +++ b/vim/bundle/vim-json @@ -0,0 +1 @@ +Subproject commit 4a0bb3e186ec8938131f2c9debc85097e86a2b63 -- cgit From e66374a548b5827600f90f85403fcffd98f9995b Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Tue, 23 Apr 2013 08:47:31 -0500 Subject: Consolidate configurations --- tmux.conf | 3 ++- vim/bundle/ctrlp.vim | 2 +- vimrc | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tmux.conf b/tmux.conf index cd64511..ad09b55 100644 --- a/tmux.conf +++ b/tmux.conf @@ -23,7 +23,8 @@ bind - split-window -v # set -g status-right '#[fg=black]#[bg=white]#(uptime)' # set -g status-right-length 70 -source /Users/benbeltran/Library/Python/2.7/lib/python/site-packages/powerline/bindings/tmux/powerline.conf +# Powerline +source ~/Library/Python/2.7/lib/python/site-packages/powerline/bindings/tmux/powerline.conf #Set Activity monitoring. setw -g monitor-activity on diff --git a/vim/bundle/ctrlp.vim b/vim/bundle/ctrlp.vim index be5842a..6ddbfe2 160000 --- a/vim/bundle/ctrlp.vim +++ b/vim/bundle/ctrlp.vim @@ -1 +1 @@ -Subproject commit be5842a376f16c16c5dc4cc1879d7168a074f7de +Subproject commit 6ddbfe2cc00a7eeb2a4450552b78276488a2e2c9 diff --git a/vimrc b/vimrc index bf76925..1f5dea3 100755 --- a/vimrc +++ b/vimrc @@ -161,7 +161,7 @@ set nofoldenable set foldlevel=1 " powerline stuff -set rtp+=/Users/benbeltran/Library/Python/2.7/lib/python/site-packages/powerline/bindings/vim +set rtp+=~/Library/Python/2.7/lib/python/site-packages/powerline/bindings/vim " Fix CtrlP root folder and add some ignores let g:ctrlp_working_path_mode = 0 -- cgit From 24873310b30e1bd2ef7087a559a667532009b4c1 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Tue, 23 Apr 2013 08:52:28 -0500 Subject: Better tmux powerline activity highlight --- tmux.conf | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tmux.conf b/tmux.conf index ad09b55..33db53a 100644 --- a/tmux.conf +++ b/tmux.conf @@ -26,6 +26,9 @@ bind - split-window -v # Powerline source ~/Library/Python/2.7/lib/python/site-packages/powerline/bindings/tmux/powerline.conf +# Better powerline highlighting. +set-window-option -g window-status-activity-attr bold,blink,underscore + #Set Activity monitoring. setw -g monitor-activity on set -g visual-activity on -- cgit From 1eb2f805df7e1af7600565d77a88b2a7ea99ceae Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 3 Jun 2013 07:24:52 -0500 Subject: Update stuffs --- vim/.netrwhist | 4 ++- vim/colors/molokai.vim | 88 ++++++++++++++++++++++++++++++++++++++++---------- vimrc | 3 +- zshrc | 3 +- 4 files changed, 78 insertions(+), 20 deletions(-) diff --git a/vim/.netrwhist b/vim/.netrwhist index 03884d9..115134c 100644 --- a/vim/.netrwhist +++ b/vim/.netrwhist @@ -1,6 +1,8 @@ let g:netrw_dirhistmax =10 -let g:netrw_dirhist_cnt =4 +let g:netrw_dirhist_cnt =6 let g:netrw_dirhist_1='/Users/benbeltran/.newsbeuter' let g:netrw_dirhist_2='/Users/benbeltran/.vim' let g:netrw_dirhist_3='/Users/benbeltran/.dotfiles/tmux-powerline' let g:netrw_dirhist_4='/Users/benbeltran/.config' +let g:netrw_dirhist_5='/Users/benbeltran/Projects/nitrogen/GantNitrogenIntegrationDependencies.oplx' +let g:netrw_dirhist_6='/private/etc/postfix' diff --git a/vim/colors/molokai.vim b/vim/colors/molokai.vim index aae9420..d809d1b 100644 --- a/vim/colors/molokai.vim +++ b/vim/colors/molokai.vim @@ -1,3 +1,4 @@ + " Vim color file " " Author: Tomas Restrepo @@ -75,12 +76,11 @@ hi PreProc guifg=#A6E22E hi Question guifg=#66D9EF hi Repeat guifg=#F92672 gui=bold hi Search guifg=#FFFFFF guibg=#455354 -" marks column +" marks hi SignColumn guifg=#A6E22E guibg=#232526 hi SpecialChar guifg=#F92672 gui=bold -hi SpecialComment guifg=#465457 gui=bold +hi SpecialComment guifg=#7E8E91 gui=bold hi Special guifg=#66D9EF guibg=bg gui=italic -hi SpecialKey guifg=#888A85 gui=italic if has("spell") hi SpellBad guisp=#FF0000 gui=undercurl hi SpellCap guisp=#7070F0 gui=undercurl @@ -111,21 +111,32 @@ if s:molokai_original == 1 hi Comment guifg=#75715E hi CursorLine guibg=#3E3D32 hi CursorColumn guibg=#3E3D32 + hi ColorColumn guibg=#3B3A32 hi LineNr guifg=#BCBCBC guibg=#3B3A32 - hi NonText guifg=#BCBCBC guibg=#3B3A32 + hi NonText guifg=#75715E + hi SpecialKey guifg=#75715E else hi Normal guifg=#F8F8F2 guibg=#1B1D1E - hi Comment guifg=#465457 + hi Comment guifg=#7E8E91 hi CursorLine guibg=#293739 hi CursorColumn guibg=#293739 - hi LineNr guifg=#BCBCBC guibg=#232526 - hi NonText guifg=#BCBCBC guibg=#232526 + hi ColorColumn guibg=#232526 + hi LineNr guifg=#465457 guibg=#232526 + hi NonText guifg=#465457 + hi SpecialKey guifg=#465457 end " " Support for 256-color terminal " if &t_Co > 255 + if s:molokai_original == 1 + hi Normal ctermbg=234 + hi CursorLine ctermbg=235 cterm=none + else + hi Normal ctermfg=252 + hi CursorLine ctermbg=234 cterm=none + endif hi Boolean ctermfg=135 hi Character ctermfg=144 hi Number ctermfg=135 @@ -150,11 +161,11 @@ if &t_Co > 255 hi FoldColumn ctermfg=67 ctermbg=16 hi Folded ctermfg=67 ctermbg=16 hi Function ctermfg=118 - hi Identifier ctermfg=208 + hi Identifier ctermfg=208 cterm=none hi Ignore ctermfg=244 ctermbg=232 hi IncSearch ctermfg=193 ctermbg=16 - hi Keyword ctermfg=161 cterm=bold + hi keyword ctermfg=161 cterm=bold hi Label ctermfg=229 cterm=none hi Macro ctermfg=193 hi SpecialKey ctermfg=81 @@ -180,9 +191,13 @@ if &t_Co > 255 hi SignColumn ctermfg=118 ctermbg=235 hi SpecialChar ctermfg=161 cterm=bold hi SpecialComment ctermfg=245 cterm=bold - hi Special ctermfg=81 ctermbg=232 - hi SpecialKey ctermfg=245 - + hi Special ctermfg=81 + if has("spell") + hi SpellBad ctermbg=52 + hi SpellCap ctermbg=17 + hi SpellLocal ctermbg=17 + hi SpellRare ctermfg=none ctermbg=none cterm=reverse + endif hi Statement ctermfg=161 cterm=bold hi StatusLine ctermfg=238 ctermbg=253 hi StatusLineNC ctermfg=244 ctermbg=232 @@ -197,15 +212,54 @@ if &t_Co > 255 hi Underlined ctermfg=244 cterm=underline hi VertSplit ctermfg=244 ctermbg=232 cterm=bold - hi VisualNOS ctermbg=238 - hi Visual ctermbg=235 + hi VisualNOS ctermbg=240 + hi Visual ctermbg=238 hi WarningMsg ctermfg=231 ctermbg=238 cterm=bold hi WildMenu ctermfg=81 ctermbg=16 - hi Normal ctermfg=252 ctermbg=233 hi Comment ctermfg=59 - hi CursorLine ctermbg=234 cterm=none hi CursorColumn ctermbg=234 + hi ColorColumn ctermbg=234 hi LineNr ctermfg=250 ctermbg=234 - hi NonText ctermfg=250 ctermbg=234 + hi NonText ctermfg=59 + + hi SpecialKey ctermfg=59 + + if exists("g:rehash256") && g:rehash256 == 1 + hi Normal ctermfg=252 ctermbg=234 + hi CursorLine ctermbg=236 cterm=none + hi CursorLineNr ctermfg=226 + + hi Boolean ctermfg=141 + hi Character ctermfg=222 + hi Number ctermfg=141 + hi String ctermfg=222 + hi Conditional ctermfg=197 cterm=bold + hi Constant ctermfg=141 cterm=bold + + hi DiffDelete ctermfg=125 ctermbg=233 + + hi Directory ctermfg=154 cterm=bold + hi Error ctermfg=125 ctermbg=233 + hi Exception ctermfg=154 cterm=bold + hi Float ctermfg=141 + hi Function ctermfg=154 + hi Identifier ctermfg=208 + + hi Keyword ctermfg=197 cterm=bold + hi Operator ctermfg=197 + hi PreCondit ctermfg=154 cterm=bold + hi PreProc ctermfg=154 + hi Repeat ctermfg=197 cterm=bold + + hi Statement ctermfg=197 cterm=bold + hi Tag ctermfg=197 + hi Title ctermfg=203 + hi Visual ctermbg=238 + + hi Comment ctermfg=244 + hi LineNr ctermfg=239 ctermbg=235 + hi NonText ctermfg=239 + hi SpecialKey ctermfg=239 + endif end diff --git a/vimrc b/vimrc index 1f5dea3..e564874 100755 --- a/vimrc +++ b/vimrc @@ -121,7 +121,7 @@ set modelines=10 " Default color scheme set t_Co=256 -color railscasts +color molokai " Directories for swp files set backupdir=~/.vim/.backup @@ -166,3 +166,4 @@ set rtp+=~/Library/Python/2.7/lib/python/site-packages/powerline/bindings/vim " Fix CtrlP root folder and add some ignores let g:ctrlp_working_path_mode = 0 let g:ctrlp_custom_ignore = '\v[\/](\.(git|hg|svn)|node_modules|DS_Store)$' +let g:ctrlp_user_command = ['.git', 'cd %s && git ls-files'] diff --git a/zshrc b/zshrc index 59f79a1..d68d3dc 100644 --- a/zshrc +++ b/zshrc @@ -34,7 +34,7 @@ source $ZSH/oh-my-zsh.sh export TERM=screen-256color export JAVA_HOME=$(/usr/libexec/java_home) -export PATH=/usr/local/bin:/usr/local/sbin:$PATH +export PATH=/Users/benbeltran/Projects/nitrogen/bin:/usr/local/bin:/usr/local/sbin:$PATH export NODE_PATH=/usr/local/lib/node_modules:$NODE_PATH export PYTONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH export PS1="$PS1"'$([ -n "$TMUX" ] && tmux setenv TMUXPWD_$(tmux display -p "#I_#P") "$PWD")' @@ -52,6 +52,7 @@ echo -e "\033[m" alias dwarffortress="/Applications/Dwarf\ Fortress/df" alias ls="ls -FG" alias rspec="rspec --color" +alias nitro="server.js" #Screeninator and RVM scripts [[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm -- cgit From e54416f3b727a89ea3bf1a28507d58681ba89c64 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Mon, 3 Jun 2013 08:34:53 -0500 Subject: Relative line numbers for vim --- vimrc | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/vimrc b/vimrc index e564874..a9c30a0 100755 --- a/vimrc +++ b/vimrc @@ -167,3 +167,19 @@ set rtp+=~/Library/Python/2.7/lib/python/site-packages/powerline/bindings/vim let g:ctrlp_working_path_mode = 0 let g:ctrlp_custom_ignore = '\v[\/](\.(git|hg|svn)|node_modules|DS_Store)$' let g:ctrlp_user_command = ['.git', 'cd %s && git ls-files'] + +" Relative numbers +autocmd FocusLost * :set number +autocmd InsertEnter * :set number +autocmd InsertLeave * :set relativenumber +autocmd CursorMoved * :set relativenumber + +function! NumberToggle() + if(&relativenumber == 1) + set number + else + set relativenumber + endif +endfunction + +nnoremap :call NumberToggle() -- cgit From 7c14046e4995141df534fc0ac0f2cf2b36d807ac Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Wed, 5 Jun 2013 08:57:32 -0500 Subject: Delete a bunch of stuff, better arrange submodules --- .gitmodules | 8 + vim/tmp/ack.vim | 1 - vim/tmp/align | 1 - vim/tmp/arduino | 1 - vim/tmp/color-sampler | 1 - vim/tmp/command-t-1.2.1.vba | 3054 -------------------- vim/tmp/command_t/doc/command-t.txt | 786 ----- vim/tmp/command_t/plugin/command-t.vim | 164 -- vim/tmp/command_t/ruby/command-t/controller.rb | 317 -- vim/tmp/command_t/ruby/command-t/depend | 24 - vim/tmp/command_t/ruby/command-t/ext.c | 65 - vim/tmp/command_t/ruby/command-t/ext.h | 36 - vim/tmp/command_t/ruby/command-t/extconf.rb | 32 - vim/tmp/command_t/ruby/command-t/finder.rb | 52 - .../ruby/command-t/finder/buffer_finder.rb | 35 - .../command_t/ruby/command-t/finder/file_finder.rb | 35 - vim/tmp/command_t/ruby/command-t/match.c | 189 -- vim/tmp/command_t/ruby/command-t/match.h | 29 - vim/tmp/command_t/ruby/command-t/match_window.rb | 387 --- vim/tmp/command_t/ruby/command-t/matcher.c | 164 -- vim/tmp/command_t/ruby/command-t/matcher.h | 30 - vim/tmp/command_t/ruby/command-t/prompt.rb | 165 -- vim/tmp/command_t/ruby/command-t/ruby_compat.h | 49 - vim/tmp/command_t/ruby/command-t/scanner.rb | 28 - .../ruby/command-t/scanner/buffer_scanner.rb | 42 - .../ruby/command-t/scanner/file_scanner.rb | 94 - vim/tmp/command_t/ruby/command-t/settings.rb | 77 - vim/tmp/command_t/ruby/command-t/stub.rb | 46 - vim/tmp/command_t/ruby/command-t/vim.rb | 43 - .../command_t/ruby/command-t/vim/path_utilities.rb | 40 - vim/tmp/command_t/ruby/command-t/vim/screen.rb | 32 - vim/tmp/command_t/ruby/command-t/vim/window.rb | 38 - vim/tmp/conque/autoload/conque_term.vim | 1590 ---------- vim/tmp/conque/doc/conque_term.txt | 156 - vim/tmp/conque/plugin/conque_term.vim | 93 - vim/tmp/conque/syntax/conque_term.vim | 75 - vim/tmp/conque_1.1.tar.gz | Bin 16907 -> 0 bytes vim/tmp/cucumber | 1 - vim/tmp/endwise | 1 - vim/tmp/fugitive | 1 - vim/tmp/gist-vim | 1 - vim/tmp/git | 1 - vim/tmp/haml | 1 - vim/tmp/indent_object | 1 - vim/tmp/irblack | 1 - vim/tmp/javascript | 1 - vim/tmp/markdown | 1 - vim/tmp/nerdcommenter | 1 - vim/tmp/nerdtree | 1 - vim/tmp/puppet | 1 - vim/tmp/rails | 1 - vim/tmp/rspec | 1 - vim/tmp/scala | 1 - vim/tmp/searchfold | 1 - vim/tmp/snipmate | 1 - vim/tmp/solarized | 1 - vim/tmp/supertab | 1 - vim/tmp/surround | 1 - vim/tmp/syntastic | 1 - vim/tmp/taglist | 1 - vim/tmp/textile | 1 - vim/tmp/unimpaired | 1 - vim/tmp/vim-coffee-script | 1 - vim/tmp/vividchalk | 1 - vim/tmp/zoomwin | 1 - 65 files changed, 8 insertions(+), 7999 deletions(-) delete mode 160000 vim/tmp/ack.vim delete mode 160000 vim/tmp/align delete mode 160000 vim/tmp/arduino delete mode 160000 vim/tmp/color-sampler delete mode 100644 vim/tmp/command-t-1.2.1.vba delete mode 100644 vim/tmp/command_t/doc/command-t.txt delete mode 100644 vim/tmp/command_t/plugin/command-t.vim delete mode 100644 vim/tmp/command_t/ruby/command-t/controller.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/depend delete mode 100644 vim/tmp/command_t/ruby/command-t/ext.c delete mode 100644 vim/tmp/command_t/ruby/command-t/ext.h delete mode 100644 vim/tmp/command_t/ruby/command-t/extconf.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/finder.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/finder/buffer_finder.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/finder/file_finder.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/match.c delete mode 100644 vim/tmp/command_t/ruby/command-t/match.h delete mode 100644 vim/tmp/command_t/ruby/command-t/match_window.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/matcher.c delete mode 100644 vim/tmp/command_t/ruby/command-t/matcher.h delete mode 100644 vim/tmp/command_t/ruby/command-t/prompt.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/ruby_compat.h delete mode 100644 vim/tmp/command_t/ruby/command-t/scanner.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/scanner/buffer_scanner.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/scanner/file_scanner.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/settings.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/stub.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/vim.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/vim/path_utilities.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/vim/screen.rb delete mode 100644 vim/tmp/command_t/ruby/command-t/vim/window.rb delete mode 100644 vim/tmp/conque/autoload/conque_term.vim delete mode 100644 vim/tmp/conque/doc/conque_term.txt delete mode 100644 vim/tmp/conque/plugin/conque_term.vim delete mode 100644 vim/tmp/conque/syntax/conque_term.vim delete mode 100644 vim/tmp/conque_1.1.tar.gz delete mode 160000 vim/tmp/cucumber delete mode 160000 vim/tmp/endwise delete mode 160000 vim/tmp/fugitive delete mode 160000 vim/tmp/gist-vim delete mode 160000 vim/tmp/git delete mode 160000 vim/tmp/haml delete mode 160000 vim/tmp/indent_object delete mode 160000 vim/tmp/irblack delete mode 160000 vim/tmp/javascript delete mode 160000 vim/tmp/markdown delete mode 160000 vim/tmp/nerdcommenter delete mode 160000 vim/tmp/nerdtree delete mode 160000 vim/tmp/puppet delete mode 160000 vim/tmp/rails delete mode 160000 vim/tmp/rspec delete mode 160000 vim/tmp/scala delete mode 160000 vim/tmp/searchfold delete mode 160000 vim/tmp/snipmate delete mode 160000 vim/tmp/solarized delete mode 160000 vim/tmp/supertab delete mode 160000 vim/tmp/surround delete mode 160000 vim/tmp/syntastic delete mode 160000 vim/tmp/taglist delete mode 160000 vim/tmp/textile delete mode 160000 vim/tmp/unimpaired delete mode 160000 vim/tmp/vim-coffee-script delete mode 160000 vim/tmp/vividchalk delete mode 160000 vim/tmp/zoomwin diff --git a/.gitmodules b/.gitmodules index ab5fb65..ab37167 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,11 @@ [submodule "tmux-powerline"] path = tmux-powerline url = git://github.com/erikw/tmux-powerline.git + +[submodule "ctrlp"] + path = vim/bundle/ctrlp.vim + url = https://github.com/kien/ctrlp.vim.git + +[submodule "vim-json"] + path = vim/bundle/vim-json + url = https://github.com/elzr/vim-json.git diff --git a/vim/tmp/ack.vim b/vim/tmp/ack.vim deleted file mode 160000 index a41d5d5..0000000 --- a/vim/tmp/ack.vim +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a41d5d52c39a31128e969e69acf800b198cb07f9 diff --git a/vim/tmp/align b/vim/tmp/align deleted file mode 160000 index fa5fdee..0000000 --- a/vim/tmp/align +++ /dev/null @@ -1 +0,0 @@ -Subproject commit fa5fdeeea25269c3e83262c03dfa1ccd27dbd3c9 diff --git a/vim/tmp/arduino b/vim/tmp/arduino deleted file mode 160000 index c97f8ca..0000000 --- a/vim/tmp/arduino +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c97f8ca8941e63c446ecc87eca089b293c7ac01a diff --git a/vim/tmp/color-sampler b/vim/tmp/color-sampler deleted file mode 160000 index 681ed9e..0000000 --- a/vim/tmp/color-sampler +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 681ed9e94b7d498810be7a3ac0f048bcca8fd46d diff --git a/vim/tmp/command-t-1.2.1.vba b/vim/tmp/command-t-1.2.1.vba deleted file mode 100644 index 015f593..0000000 --- a/vim/tmp/command-t-1.2.1.vba +++ /dev/null @@ -1,3054 +0,0 @@ -" Vimball Archiver by Charles E. Campbell, Jr., Ph.D. -UseVimball -finish -ruby/command-t/controller.rb [[[1 -317 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/finder/buffer_finder' -require 'command-t/finder/file_finder' -require 'command-t/match_window' -require 'command-t/prompt' -require 'command-t/vim/path_utilities' - -module CommandT - class Controller - include VIM::PathUtilities - - def initialize - @prompt = Prompt.new - @buffer_finder = CommandT::BufferFinder.new - set_up_file_finder - set_up_max_height - end - - def show_buffer_finder - @path = VIM::pwd - @active_finder = @buffer_finder - show - end - - def show_file_finder - # optional parameter will be desired starting directory, or "" - @path = File.expand_path(::VIM::evaluate('a:arg'), VIM::pwd) - @file_finder.path = @path - @active_finder = @file_finder - show - rescue Errno::ENOENT - # probably a problem with the optional parameter - @match_window.print_no_such_file_or_directory - end - - def hide - @match_window.close - if VIM::Window.select @initial_window - if @initial_buffer.number == 0 - # upstream bug: buffer number misreported as 0 - # see: https://wincent.com/issues/1617 - ::VIM::command "silent b #{@initial_buffer.name}" - else - ::VIM::command "silent b #{@initial_buffer.number}" - end - end - end - - def flush - set_up_max_height - set_up_file_finder - end - - def handle_key - key = ::VIM::evaluate('a:arg').to_i.chr - if @focus == @prompt - @prompt.add! key - list_matches - else - @match_window.find key - end - end - - def backspace - if @focus == @prompt - @prompt.backspace! - list_matches - end - end - - def delete - if @focus == @prompt - @prompt.delete! - list_matches - end - end - - def accept_selection options = {} - selection = @match_window.selection - hide - open_selection(selection, options) unless selection.nil? - end - - def toggle_focus - @focus.unfocus # old focus - @focus = @focus == @prompt ? @match_window : @prompt - @focus.focus # new focus - end - - def cancel - hide - end - - def select_next - @match_window.select_next - end - - def select_prev - @match_window.select_prev - end - - def clear - @prompt.clear! - list_matches - end - - def cursor_left - @prompt.cursor_left if @focus == @prompt - end - - def cursor_right - @prompt.cursor_right if @focus == @prompt - end - - def cursor_end - @prompt.cursor_end if @focus == @prompt - end - - def cursor_start - @prompt.cursor_start if @focus == @prompt - end - - def leave - @match_window.leave - end - - def unload - @match_window.unload - end - - private - - def show - @initial_window = $curwin - @initial_buffer = $curbuf - @match_window = MatchWindow.new \ - :prompt => @prompt, - :match_window_at_top => get_bool('g:CommandTMatchWindowAtTop'), - :match_window_reverse => get_bool('g:CommandTMatchWindowReverse') - @focus = @prompt - @prompt.focus - register_for_key_presses - clear # clears prompt and lists matches - end - - def set_up_max_height - @max_height = get_number('g:CommandTMaxHeight') || 0 - end - - def set_up_file_finder - @file_finder = CommandT::FileFinder.new nil, - :max_files => get_number('g:CommandTMaxFiles'), - :max_depth => get_number('g:CommandTMaxDepth'), - :always_show_dot_files => get_bool('g:CommandTAlwaysShowDotFiles'), - :never_show_dot_files => get_bool('g:CommandTNeverShowDotFiles'), - :scan_dot_directories => get_bool('g:CommandTScanDotDirectories') - end - - def exists? name - ::VIM::evaluate("exists(\"#{name}\")").to_i != 0 - end - - def get_number name - exists?(name) ? ::VIM::evaluate("#{name}").to_i : nil - end - - def get_bool name - exists?(name) ? ::VIM::evaluate("#{name}").to_i != 0 : nil - end - - def get_string name - exists?(name) ? ::VIM::evaluate("#{name}").to_s : nil - end - - # expect a string or a list of strings - def get_list_or_string name - return nil unless exists?(name) - list_or_string = ::VIM::evaluate("#{name}") - if list_or_string.kind_of?(Array) - list_or_string.map { |item| item.to_s } - else - list_or_string.to_s - end - end - - # Backslash-escape space, \, |, %, #, " - def sanitize_path_string str - # for details on escaping command-line mode arguments see: :h : - # (that is, help on ":") in the Vim documentation. - str.gsub(/[ \\|%#"]/, '\\\\\0') - end - - def default_open_command - if !get_bool('&hidden') && get_bool('&modified') - 'sp' - else - 'e' - end - end - - def ensure_appropriate_window_selection - # normally we try to open the selection in the current window, but there - # is one exception: - # - # - we don't touch any "unlisted" buffer with buftype "nofile" (such as - # NERDTree or MiniBufExplorer); this is to avoid things like the "Not - # enough room" error which occurs when trying to open in a split in a - # shallow (potentially 1-line) buffer like MiniBufExplorer is current - # - # Other "unlisted" buffers, such as those with buftype "help" are treated - # normally. - initial = $curwin - while true do - break unless ::VIM::evaluate('&buflisted').to_i == 0 && - ::VIM::evaluate('&buftype').to_s == 'nofile' - ::VIM::command 'wincmd w' # try next window - break if $curwin == initial # have already tried all - end - end - - def open_selection selection, options = {} - command = options[:command] || default_open_command - selection = File.expand_path selection, @path - selection = relative_path_under_working_directory selection - selection = sanitize_path_string selection - ensure_appropriate_window_selection - ::VIM::command "silent #{command} #{selection}" - end - - def map key, function, param = nil - ::VIM::command "noremap #{key} " \ - ":call CommandT#{function}(#{param})" - end - - def xterm? - !!(::VIM::evaluate('&term') =~ /\Axterm/) - end - - def vt100? - !!(::VIM::evaluate('&term') =~ /\Avt100/) - end - - def register_for_key_presses - # "normal" keys (interpreted literally) - numbers = ('0'..'9').to_a.join - lowercase = ('a'..'z').to_a.join - uppercase = lowercase.upcase - punctuation = '<>`@#~!"$%&/()=+*-_.,;:?\\\'{}[] ' # and space - (numbers + lowercase + uppercase + punctuation).each_byte do |b| - map "", 'HandleKey', b - end - - # "special" keys (overridable by settings) - { 'Backspace' => '', - 'Delete' => '', - 'AcceptSelection' => '', - 'AcceptSelectionSplit' => ['', ''], - 'AcceptSelectionTab' => '', - 'AcceptSelectionVSplit' => '', - 'ToggleFocus' => '', - 'Cancel' => ['', ''], - 'SelectNext' => ['', '', ''], - 'SelectPrev' => ['', '', ''], - 'Clear' => '', - 'CursorLeft' => ['', ''], - 'CursorRight' => ['', ''], - 'CursorEnd' => '', - 'CursorStart' => '' }.each do |key, value| - if override = get_list_or_string("g:CommandT#{key}Map") - [override].flatten.each do |mapping| - map mapping, key - end - else - [value].flatten.each do |mapping| - map mapping, key unless mapping == '' && (xterm? || vt100?) - end - end - end - end - - # Returns the desired maximum number of matches, based on available - # vertical space and the g:CommandTMaxHeight option. - def match_limit - limit = VIM::Screen.lines - 5 - limit = 1 if limit < 0 - limit = [limit, @max_height].min if @max_height > 0 - limit - end - - def list_matches - matches = @active_finder.sorted_matches_for @prompt.abbrev, :limit => match_limit - @match_window.matches = matches - end - end # class Controller -end # module commandT -ruby/command-t/extconf.rb [[[1 -32 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'mkmf' - -def missing item - puts "couldn't find #{item} (required)" - exit 1 -end - -have_header('ruby.h') or missing('ruby.h') -create_makefile('ext') -ruby/command-t/finder/buffer_finder.rb [[[1 -35 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/ext' # CommandT::Matcher -require 'command-t/scanner/buffer_scanner' -require 'command-t/finder' - -module CommandT - class BufferFinder < Finder - def initialize - @scanner = BufferScanner.new - @matcher = Matcher.new @scanner, :always_show_dot_files => true - end - end # class BufferFinder -end # CommandT -ruby/command-t/finder/file_finder.rb [[[1 -35 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/ext' # CommandT::Matcher -require 'command-t/finder' -require 'command-t/scanner/file_scanner' - -module CommandT - class FileFinder < Finder - def initialize path = Dir.pwd, options = {} - @scanner = FileScanner.new path, options - @matcher = Matcher.new @scanner, options - end - end # class FileFinder -end # CommandT -ruby/command-t/finder.rb [[[1 -52 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/ext' # CommandT::Matcher - -module CommandT - # Encapsulates a Scanner instance (which builds up a list of available files - # in a directory) and a Matcher instance (which selects from that list based - # on a search string). - # - # Specialized subclasses use different kinds of scanners adapted for - # different kinds of search (files, buffers). - class Finder - def initialize path = Dir.pwd, options = {} - raise RuntimeError, 'Subclass responsibility' - end - - # Options: - # :limit (integer): limit the number of returned matches - def sorted_matches_for str, options = {} - @matcher.sorted_matches_for str, options - end - - def flush - @scanner.flush - end - - def path= path - @scanner.path = path - end - end # class Finder -end # CommandT -ruby/command-t/match_window.rb [[[1 -387 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'ostruct' -require 'command-t/settings' - -module CommandT - class MatchWindow - @@selection_marker = '> ' - @@marker_length = @@selection_marker.length - @@unselected_marker = ' ' * @@marker_length - @@buffer = nil - - def initialize options = {} - @prompt = options[:prompt] - @reverse_list = options[:match_window_reverse] - - # save existing window dimensions so we can restore them later - @windows = [] - (0..(::VIM::Window.count - 1)).each do |i| - window = OpenStruct.new :index => i, :height => ::VIM::Window[i].height - @windows << window - end - - # global settings (must manually save and restore) - @settings = Settings.new - ::VIM::set_option 'timeout' # ensure mappings timeout - ::VIM::set_option 'timeoutlen=0' # respond immediately to mappings - ::VIM::set_option 'nohlsearch' # don't highlight search strings - ::VIM::set_option 'noinsertmode' # don't make Insert mode the default - ::VIM::set_option 'noshowcmd' # don't show command info on last line - ::VIM::set_option 'report=9999' # don't show "X lines changed" reports - ::VIM::set_option 'sidescroll=0' # don't sidescroll in jumps - ::VIM::set_option 'sidescrolloff=0' # don't sidescroll automatically - ::VIM::set_option 'noequalalways' # don't auto-balance window sizes - - # show match window - split_location = options[:match_window_at_top] ? 'topleft' : 'botright' - if @@buffer # still have buffer from last time - ::VIM::command "silent! #{split_location} #{@@buffer.number}sbuffer" - raise "Can't re-open GoToFile buffer" unless $curbuf.number == @@buffer.number - $curwin.height = 1 - else # creating match window for first time and set it up - split_command = "silent! #{split_location} 1split GoToFile" - [ - split_command, - 'setlocal bufhidden=unload', # unload buf when no longer displayed - 'setlocal buftype=nofile', # buffer is not related to any file - 'setlocal nomodifiable', # prevent manual edits - 'setlocal noswapfile', # don't create a swapfile - 'setlocal nowrap', # don't soft-wrap - 'setlocal nonumber', # don't show line numbers - 'setlocal nolist', # don't use List mode (visible tabs etc) - 'setlocal foldcolumn=0', # don't show a fold column at side - 'setlocal foldlevel=99', # don't fold anything - 'setlocal nocursorline', # don't highlight line cursor is on - 'setlocal nospell', # spell-checking off - 'setlocal nobuflisted', # don't show up in the buffer list - 'setlocal textwidth=0' # don't hard-wrap (break long lines) - ].each { |command| ::VIM::command command } - - # sanity check: make sure the buffer really was created - raise "Can't find GoToFile buffer" unless $curbuf.name.match /GoToFile\z/ - @@buffer = $curbuf - end - - # syntax coloring - if VIM::has_syntax? - ::VIM::command "syntax match CommandTSelection \"^#{@@selection_marker}.\\+$\"" - ::VIM::command 'syntax match CommandTNoEntries "^-- NO MATCHES --$"' - ::VIM::command 'syntax match CommandTNoEntries "^-- NO SUCH FILE OR DIRECTORY --$"' - ::VIM::command 'highlight link CommandTSelection Visual' - ::VIM::command 'highlight link CommandTNoEntries Error' - ::VIM::evaluate 'clearmatches()' - - # hide cursor - @cursor_highlight = get_cursor_highlight - hide_cursor - end - - # perform cleanup using an autocmd to ensure we don't get caught out - # by some unexpected means of dismissing or leaving the Command-T window - # (eg. , etc) - ::VIM::command 'autocmd! * ' - ::VIM::command 'autocmd BufLeave ruby $command_t.leave' - ::VIM::command 'autocmd BufUnload ruby $command_t.unload' - - @has_focus = false - @selection = nil - @abbrev = '' - @window = $curwin - end - - def close - # Workaround for upstream bug in Vim 7.3 on some platforms - # - # On some platforms, $curbuf.number always returns 0. One workaround is - # to build Vim with --disable-largefile, but as this is producing lots of - # support requests, implement the following fallback to the buffer name - # instead, at least until upstream gets fixed. - # - # For more details, see: https://wincent.com/issues/1617 - if $curbuf.number == 0 - # use bwipeout as bunload fails if passed the name of a hidden buffer - ::VIM::command 'bwipeout! GoToFile' - @@buffer = nil - else - ::VIM::command "bunload! #{@@buffer.number}" - end - end - - def leave - close - unload - end - - def unload - restore_window_dimensions - @settings.restore - @prompt.dispose - show_cursor - end - - def add! char - @abbrev += char - end - - def backspace! - @abbrev.chop! - end - - def select_next - if @selection < @matches.length - 1 - @selection += 1 - print_match(@selection - 1) # redraw old selection (removes marker) - print_match(@selection) # redraw new selection (adds marker) - move_cursor_to_selected_line - else - # (possibly) loop or scroll - end - end - - def select_prev - if @selection > 0 - @selection -= 1 - print_match(@selection + 1) # redraw old selection (removes marker) - print_match(@selection) # redraw new selection (adds marker) - move_cursor_to_selected_line - else - # (possibly) loop or scroll - end - end - - def matches= matches - matches = matches.reverse if @reverse_list - if matches != @matches - @matches = matches - @selection = @reverse_list ? @matches.length - 1 : 0 - print_matches - move_cursor_to_selected_line - end - end - - def focus - unless @has_focus - @has_focus = true - if VIM::has_syntax? - ::VIM::command 'highlight link CommandTSelection Search' - end - end - end - - def unfocus - if @has_focus - @has_focus = false - if VIM::has_syntax? - ::VIM::command 'highlight link CommandTSelection Visual' - end - end - end - - def find char - # is this a new search or the continuation of a previous one? - now = Time.now - if @last_key_time.nil? or @last_key_time < (now - 0.5) - @find_string = char - else - @find_string += char - end - @last_key_time = now - - # see if there's anything up ahead that matches - @matches.each_with_index do |match, idx| - if match[0, @find_string.length].casecmp(@find_string) == 0 - old_selection = @selection - @selection = idx - print_match(old_selection) # redraw old selection (removes marker) - print_match(@selection) # redraw new selection (adds marker) - break - end - end - end - - # Returns the currently selected item as a String. - def selection - @matches[@selection] - end - - def print_no_such_file_or_directory - print_error 'NO SUCH FILE OR DIRECTORY' - end - - private - - def move_cursor_to_selected_line - # on some non-GUI terminals, the cursor doesn't hide properly - # so we move the cursor to prevent it from blinking away in the - # upper-left corner in a distracting fashion - @window.cursor = [@selection + 1, 0] - end - - def print_error msg - return unless VIM::Window.select(@window) - unlock - clear - @window.height = 1 - @@buffer[1] = "-- #{msg} --" - lock - end - - def restore_window_dimensions - # sort from tallest to shortest - @windows.sort! { |a, b| b.height <=> a.height } - - # starting with the tallest ensures that there are no constraints - # preventing windows on the side of vertical splits from regaining - # their original full size - @windows.each do |w| - # beware: window may be nil - window = ::VIM::Window[w.index] - window.height = w.height if window - end - end - - def match_text_for_idx idx - match = truncated_match @matches[idx] - if idx == @selection - prefix = @@selection_marker - suffix = padding_for_selected_match match - else - prefix = @@unselected_marker - suffix = '' - end - prefix + match + suffix - end - - # Print just the specified match. - def print_match idx - return unless VIM::Window.select(@window) - unlock - @@buffer[idx + 1] = match_text_for_idx idx - lock - end - - # Print all matches. - def print_matches - match_count = @matches.length - if match_count == 0 - print_error 'NO MATCHES' - else - return unless VIM::Window.select(@window) - unlock - clear - actual_lines = 1 - @window_width = @window.width # update cached value - max_lines = VIM::Screen.lines - 5 - max_lines = 1 if max_lines < 0 - actual_lines = match_count > max_lines ? max_lines : match_count - @window.height = actual_lines - (1..actual_lines).each do |line| - idx = line - 1 - if @@buffer.count >= line - @@buffer[line] = match_text_for_idx idx - else - @@buffer.append line - 1, match_text_for_idx(idx) - end - end - lock - end - end - - # Prepare padding for match text (trailing spaces) so that selection - # highlighting extends all the way to the right edge of the window. - def padding_for_selected_match str - len = str.length - if len >= @window_width - @@marker_length - '' - else - ' ' * (@window_width - @@marker_length - len) - end - end - - # Convert "really/long/path" into "really...path" based on available - # window width. - def truncated_match str - len = str.length - available_width = @window_width - @@marker_length - return str if len <= available_width - left = (available_width / 2) - 1 - right = (available_width / 2) - 2 + (available_width % 2) - str[0, left] + '...' + str[-right, right] - end - - def clear - # range = % (whole buffer) - # action = d (delete) - # register = _ (black hole register, don't record deleted text) - ::VIM::command 'silent %d _' - end - - def get_cursor_highlight - # as :highlight returns nothing and only prints, - # must redirect its output to a variable - ::VIM::command 'silent redir => g:command_t_cursor_highlight' - - # force 0 verbosity to ensure origin information isn't printed as well - ::VIM::command 'silent! 0verbose highlight Cursor' - ::VIM::command 'silent redir END' - - # there are 3 possible formats to check for, each needing to be - # transformed in a certain way in order to reapply the highlight: - # Cursor xxx guifg=bg guibg=fg -> :hi! Cursor guifg=bg guibg=fg - # Cursor xxx links to SomethingElse -> :hi! link Cursor SomethingElse - # Cursor xxx cleared -> :hi! clear Cursor - highlight = ::VIM::evaluate 'g:command_t_cursor_highlight' - if highlight =~ /^Cursor\s+xxx\s+links to (\w+)/ - "link Cursor #{$~[1]}" - elsif highlight =~ /^Cursor\s+xxx\s+cleared/ - 'clear Cursor' - elsif highlight =~ /Cursor\s+xxx\s+(.+)/ - "Cursor #{$~[1]}" - else # likely cause E411 Cursor highlight group not found - nil - end - end - - def hide_cursor - if @cursor_highlight - ::VIM::command 'highlight Cursor NONE' - end - end - - def show_cursor - if @cursor_highlight - ::VIM::command "highlight #{@cursor_highlight}" - end - end - - def lock - ::VIM::command 'setlocal nomodifiable' - end - - def unlock - ::VIM::command 'setlocal modifiable' - end - end -end -ruby/command-t/prompt.rb [[[1 -165 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - # Abuse the status line as a prompt. - class Prompt - attr_accessor :abbrev - - def initialize - @abbrev = '' # abbreviation entered so far - @col = 0 # cursor position - @has_focus = false - end - - # Erase whatever is displayed in the prompt line, - # effectively disposing of the prompt - def dispose - ::VIM::command 'echo' - ::VIM::command 'redraw' - end - - # Clear any entered text. - def clear! - @abbrev = '' - @col = 0 - redraw - end - - # Insert a character at (before) the current cursor position. - def add! char - left, cursor, right = abbrev_segments - @abbrev = left + char + cursor + right - @col += 1 - redraw - end - - # Delete a character to the left of the current cursor position. - def backspace! - if @col > 0 - left, cursor, right = abbrev_segments - @abbrev = left.chop! + cursor + right - @col -= 1 - redraw - end - end - - # Delete a character at the current cursor position. - def delete! - if @col < @abbrev.length - left, cursor, right = abbrev_segments - @abbrev = left + right - redraw - end - end - - def cursor_left - if @col > 0 - @col -= 1 - redraw - end - end - - def cursor_right - if @col < @abbrev.length - @col += 1 - redraw - end - end - - def cursor_end - if @col < @abbrev.length - @col = @abbrev.length - redraw - end - end - - def cursor_start - if @col != 0 - @col = 0 - redraw - end - end - - def redraw - if @has_focus - prompt_highlight = 'Comment' - normal_highlight = 'None' - cursor_highlight = 'Underlined' - else - prompt_highlight = 'NonText' - normal_highlight = 'NonText' - cursor_highlight = 'NonText' - end - left, cursor, right = abbrev_segments - components = [prompt_highlight, '>>', 'None', ' '] - components += [normal_highlight, left] unless left.empty? - components += [cursor_highlight, cursor] unless cursor.empty? - components += [normal_highlight, right] unless right.empty? - components += [cursor_highlight, ' '] if cursor.empty? - set_status *components - end - - def focus - unless @has_focus - @has_focus = true - redraw - end - end - - def unfocus - if @has_focus - @has_focus = false - redraw - end - end - - private - - # Returns the @abbrev string divided up into three sections, any of - # which may actually be zero width, depending on the location of the - # cursor: - # - left segment (to left of cursor) - # - cursor segment (character at cursor) - # - right segment (to right of cursor) - def abbrev_segments - left = @abbrev[0, @col] - cursor = @abbrev[@col, 1] - right = @abbrev[(@col + 1)..-1] || '' - [left, cursor, right] - end - - def set_status *args - # see ':help :echo' for why forcing a redraw here helps - # prevent the status line from getting inadvertantly cleared - # after our echo commands - ::VIM::command 'redraw' - while (highlight = args.shift) and (text = args.shift) do - text = VIM::escape_for_single_quotes text - ::VIM::command "echohl #{highlight}" - ::VIM::command "echon '#{text}'" - end - ::VIM::command 'echohl None' - end - end # class Prompt -end # module CommandT -ruby/command-t/scanner/buffer_scanner.rb [[[1 -42 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' -require 'command-t/vim/path_utilities' -require 'command-t/scanner' - -module CommandT - # Returns a list of all open buffers. - class BufferScanner < Scanner - include VIM::PathUtilities - - def paths - (0..(::VIM::Buffer.count - 1)).map do |n| - buffer = ::VIM::Buffer[n] - if buffer.name # beware, may be nil - relative_path_under_working_directory buffer.name - end - end.compact - end - end # class BufferScanner -end # module CommandT -ruby/command-t/scanner/file_scanner.rb [[[1 -94 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' -require 'command-t/scanner' - -module CommandT - # Reads the current directory recursively for the paths to all regular files. - class FileScanner < Scanner - class FileLimitExceeded < ::RuntimeError; end - - def initialize path = Dir.pwd, options = {} - @path = path - @max_depth = options[:max_depth] || 15 - @max_files = options[:max_files] || 10_000 - @scan_dot_directories = options[:scan_dot_directories] || false - end - - def paths - return @paths unless @paths.nil? - begin - @paths = [] - @depth = 0 - @files = 0 - @prefix_len = @path.chomp('/').length - add_paths_for_directory @path, @paths - rescue FileLimitExceeded - end - @paths - end - - def flush - @paths = nil - end - - def path= str - if @path != str - @path = str - flush - end - end - - private - - def path_excluded? path - # first strip common prefix (@path) from path to match VIM's behavior - path = path[(@prefix_len + 1)..-1] - path = VIM::escape_for_single_quotes path - ::VIM::evaluate("empty(expand(fnameescape('#{path}')))").to_i == 1 - end - - def add_paths_for_directory dir, accumulator - Dir.foreach(dir) do |entry| - next if ['.', '..'].include?(entry) - path = File.join(dir, entry) - unless path_excluded?(path) - if File.file?(path) - @files += 1 - raise FileLimitExceeded if @files > @max_files - accumulator << path[@prefix_len + 1..-1] - elsif File.directory?(path) - next if @depth >= @max_depth - next if (entry.match(/\A\./) && !@scan_dot_directories) - @depth += 1 - add_paths_for_directory path, accumulator - @depth -= 1 - end - end - end - rescue Errno::EACCES - # skip over directories for which we don't have access - end - end # class FileScanner -end # module CommandT -ruby/command-t/scanner.rb [[[1 -28 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' - -module CommandT - class Scanner; end -end # module CommandT -ruby/command-t/settings.rb [[[1 -77 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - # Convenience class for saving and restoring global settings. - class Settings - def initialize - save - end - - def save - @timeoutlen = get_number 'timeoutlen' - @report = get_number 'report' - @sidescroll = get_number 'sidescroll' - @sidescrolloff = get_number 'sidescrolloff' - @timeout = get_bool 'timeout' - @equalalways = get_bool 'equalalways' - @hlsearch = get_bool 'hlsearch' - @insertmode = get_bool 'insertmode' - @showcmd = get_bool 'showcmd' - end - - def restore - set_number 'timeoutlen', @timeoutlen - set_number 'report', @report - set_number 'sidescroll', @sidescroll - set_number 'sidescrolloff', @sidescrolloff - set_bool 'timeout', @timeout - set_bool 'equalalways', @equalalways - set_bool 'hlsearch', @hlsearch - set_bool 'insertmode', @insertmode - set_bool 'showcmd', @showcmd - end - - private - - def get_number setting - ::VIM::evaluate("&#{setting}").to_i - end - - def get_bool setting - ::VIM::evaluate("&#{setting}").to_i == 1 - end - - def set_number setting, value - ::VIM::set_option "#{setting}=#{value}" - end - - def set_bool setting, value - if value - ::VIM::set_option setting - else - ::VIM::set_option "no#{setting}" - end - end - end # class Settings -end # module CommandT -ruby/command-t/stub.rb [[[1 -46 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - class Stub - @@load_error = ['command-t.vim could not load the C extension', - 'Please see INSTALLATION and TROUBLE-SHOOTING in the help', - 'For more information type: :help command-t'] - - def show_file_finder - warn *@@load_error - end - - def flush - warn *@@load_error - end - - private - - def warn *msg - ::VIM::command 'echohl WarningMsg' - msg.each { |m| ::VIM::command "echo '#{m}'" } - ::VIM::command 'echohl none' - end - end # class Stub -end # module CommandT -ruby/command-t/vim/path_utilities.rb [[[1 -40 -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' - -module CommandT - module VIM - module PathUtilities - - private - - def relative_path_under_working_directory path - # any path under the working directory will be specified as a relative - # path to improve the readability of the buffer list etc - pwd = File.expand_path(VIM::pwd) + '/' - path.index(pwd) == 0 ? path[pwd.length..-1] : path - end - end # module PathUtilities - end # module VIM -end # module CommandT -ruby/command-t/vim/screen.rb [[[1 -32 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - module VIM - module Screen - def self.lines - ::VIM::evaluate('&lines').to_i - end - end # module Screen - end # module VIM -end # module CommandT -ruby/command-t/vim/window.rb [[[1 -38 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - module VIM - class Window - def self.select window - return true if $curwin == window - initial = $curwin - while true do - ::VIM::command 'wincmd w' # cycle through windows - return true if $curwin == window # have selected desired window - return false if $curwin == initial # have already looped through all - end - end - end # class Window - end # module VIM -end # module CommandT -ruby/command-t/vim.rb [[[1 -43 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim/screen' -require 'command-t/vim/window' - -module CommandT - module VIM - def self.has_syntax? - ::VIM::evaluate('has("syntax")').to_i != 0 - end - - def self.pwd - ::VIM::evaluate 'getcwd()' - end - - # Escape a string for safe inclusion in a Vim single-quoted string - # (single quotes escaped by doubling, everything else is literal) - def self.escape_for_single_quotes str - str.gsub "'", "''" - end - end # module VIM -end # module CommandT -ruby/command-t/ext.c [[[1 -65 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include "match.h" -#include "matcher.h" - -VALUE mCommandT = 0; // module CommandT -VALUE cCommandTMatch = 0; // class CommandT::Match -VALUE cCommandTMatcher = 0; // class CommandT::Matcher - -VALUE CommandT_option_from_hash(const char *option, VALUE hash) -{ - if (NIL_P(hash)) - return Qnil; - VALUE key = ID2SYM(rb_intern(option)); - if (rb_funcall(hash, rb_intern("has_key?"), 1, key) == Qtrue) - return rb_hash_aref(hash, key); - else - return Qnil; -} - -void Init_ext() -{ - // module CommandT - mCommandT = rb_define_module("CommandT"); - - // class CommandT::Match - cCommandTMatch = rb_define_class_under(mCommandT, "Match", rb_cObject); - - // methods - rb_define_method(cCommandTMatch, "initialize", CommandTMatch_initialize, -1); - rb_define_method(cCommandTMatch, "matches?", CommandTMatch_matches, 0); - rb_define_method(cCommandTMatch, "to_s", CommandTMatch_to_s, 0); - - // attributes - rb_define_attr(cCommandTMatch, "score", Qtrue, Qfalse); // reader: true, writer: false - - // class CommandT::Matcher - cCommandTMatcher = rb_define_class_under(mCommandT, "Matcher", rb_cObject); - - // methods - rb_define_method(cCommandTMatcher, "initialize", CommandTMatcher_initialize, -1); - rb_define_method(cCommandTMatcher, "sorted_matches_for", CommandTMatcher_sorted_matches_for, 2); - rb_define_method(cCommandTMatcher, "matches_for", CommandTMatcher_matches_for, 1); -} -ruby/command-t/match.c [[[1 -189 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include "match.h" -#include "ext.h" -#include "ruby_compat.h" - -// use a struct to make passing params during recursion easier -typedef struct -{ - char *str_p; // pointer to string to be searched - long str_len; // length of same - char *abbrev_p; // pointer to search string (abbreviation) - long abbrev_len; // length of same - double max_score_per_char; - int dot_file; // boolean: true if str is a dot-file - int always_show_dot_files; // boolean - int never_show_dot_files; // boolean -} matchinfo_t; - -double recursive_match(matchinfo_t *m, // sharable meta-data - long str_idx, // where in the path string to start - long abbrev_idx, // where in the search string to start - long last_idx, // location of last matched character - double score) // cumulative score so far -{ - double seen_score = 0; // remember best score seen via recursion - int dot_file_match = 0; // true if abbrev matches a dot-file - int dot_search = 0; // true if searching for a dot - - for (long i = abbrev_idx; i < m->abbrev_len; i++) - { - char c = m->abbrev_p[i]; - if (c == '.') - dot_search = 1; - int found = 0; - for (long j = str_idx; j < m->str_len; j++, str_idx++) - { - char d = m->str_p[j]; - if (d == '.') - { - if (j == 0 || m->str_p[j - 1] == '/') - { - m->dot_file = 1; // this is a dot-file - if (dot_search) // and we are searching for a dot - dot_file_match = 1; // so this must be a match - } - } - else if (d >= 'A' && d <= 'Z') - d += 'a' - 'A'; // add 32 to downcase - if (c == d) - { - found = 1; - dot_search = 0; - - // calculate score - double score_for_char = m->max_score_per_char; - long distance = j - last_idx; - if (distance > 1) - { - double factor = 1.0; - char last = m->str_p[j - 1]; - char curr = m->str_p[j]; // case matters, so get again - if (last == '/') - factor = 0.9; - else if (last == '-' || - last == '_' || - last == ' ' || - (last >= '0' && last <= '9')) - factor = 0.8; - else if (last >= 'a' && last <= 'z' && - curr >= 'A' && curr <= 'Z') - factor = 0.8; - else if (last == '.') - factor = 0.7; - else - // if no "special" chars behind char, factor diminishes - // as distance from last matched char increases - factor = (1.0 / distance) * 0.75; - score_for_char *= factor; - } - - if (++j < m->str_len) - { - // bump cursor one char to the right and - // use recursion to try and find a better match - double sub_score = recursive_match(m, j, i, last_idx, score); - if (sub_score > seen_score) - seen_score = sub_score; - } - - score += score_for_char; - last_idx = str_idx++; - break; - } - } - if (!found) - return 0.0; - } - if (m->dot_file) - { - if (m->never_show_dot_files || - (!dot_file_match && !m->always_show_dot_files)) - return 0.0; - } - return (score > seen_score) ? score : seen_score; -} - -// Match.new abbrev, string, options = {} -VALUE CommandTMatch_initialize(int argc, VALUE *argv, VALUE self) -{ - // process arguments: 2 mandatory, 1 optional - VALUE str, abbrev, options; - if (rb_scan_args(argc, argv, "21", &str, &abbrev, &options) == 2) - options = Qnil; - str = StringValue(str); - abbrev = StringValue(abbrev); // already downcased by caller - - // check optional options hash for overrides - VALUE always_show_dot_files = CommandT_option_from_hash("always_show_dot_files", options); - VALUE never_show_dot_files = CommandT_option_from_hash("never_show_dot_files", options); - - matchinfo_t m; - m.str_p = RSTRING_PTR(str); - m.str_len = RSTRING_LEN(str); - m.abbrev_p = RSTRING_PTR(abbrev); - m.abbrev_len = RSTRING_LEN(abbrev); - m.max_score_per_char = (1.0 / m.str_len + 1.0 / m.abbrev_len) / 2; - m.dot_file = 0; - m.always_show_dot_files = always_show_dot_files == Qtrue; - m.never_show_dot_files = never_show_dot_files == Qtrue; - - // calculate score - double score = 1.0; - if (m.abbrev_len == 0) // special case for zero-length search string - { - // filter out dot files - if (!m.always_show_dot_files) - { - for (long i = 0; i < m.str_len; i++) - { - char c = m.str_p[i]; - if (c == '.' && (i == 0 || m.str_p[i - 1] == '/')) - { - score = 0.0; - break; - } - } - } - } - else // normal case - score = recursive_match(&m, 0, 0, 0, 0.0); - - // clean-up and final book-keeping - rb_iv_set(self, "@score", rb_float_new(score)); - rb_iv_set(self, "@str", str); - return Qnil; -} - -VALUE CommandTMatch_matches(VALUE self) -{ - double score = NUM2DBL(rb_iv_get(self, "@score")); - return score > 0 ? Qtrue : Qfalse; -} - -VALUE CommandTMatch_to_s(VALUE self) -{ - return rb_iv_get(self, "@str"); -} -ruby/command-t/matcher.c [[[1 -164 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include /* for qsort() */ -#include /* for strcmp() */ -#include "matcher.h" -#include "ext.h" -#include "ruby_compat.h" - -// comparison function for use with qsort -int comp_alpha(const void *a, const void *b) -{ - VALUE a_val = *(VALUE *)a; - VALUE b_val = *(VALUE *)b; - ID to_s = rb_intern("to_s"); - - VALUE a_str = rb_funcall(a_val, to_s, 0); - VALUE b_str = rb_funcall(b_val, to_s, 0); - char *a_p = RSTRING_PTR(a_str); - long a_len = RSTRING_LEN(a_str); - char *b_p = RSTRING_PTR(b_str); - long b_len = RSTRING_LEN(b_str); - int order = 0; - if (a_len > b_len) - { - order = strncmp(a_p, b_p, b_len); - if (order == 0) - order = 1; // shorter string (b) wins - } - else if (a_len < b_len) - { - order = strncmp(a_p, b_p, a_len); - if (order == 0) - order = -1; // shorter string (a) wins - } - else - order = strncmp(a_p, b_p, a_len); - return order; -} - -// comparison function for use with qsort -int comp_score(const void *a, const void *b) -{ - VALUE a_val = *(VALUE *)a; - VALUE b_val = *(VALUE *)b; - ID score = rb_intern("score"); - double a_score = RFLOAT_VALUE(rb_funcall(a_val, score, 0)); - double b_score = RFLOAT_VALUE(rb_funcall(b_val, score, 0)); - if (a_score > b_score) - return -1; // a scores higher, a should appear sooner - else if (a_score < b_score) - return 1; // b scores higher, a should appear later - else - return comp_alpha(a, b); -} - -VALUE CommandTMatcher_initialize(int argc, VALUE *argv, VALUE self) -{ - // process arguments: 1 mandatory, 1 optional - VALUE scanner, options; - if (rb_scan_args(argc, argv, "11", &scanner, &options) == 1) - options = Qnil; - if (NIL_P(scanner)) - rb_raise(rb_eArgError, "nil scanner"); - rb_iv_set(self, "@scanner", scanner); - - // check optional options hash for overrides - VALUE always_show_dot_files = CommandT_option_from_hash("always_show_dot_files", options); - if (always_show_dot_files != Qtrue) - always_show_dot_files = Qfalse; - VALUE never_show_dot_files = CommandT_option_from_hash("never_show_dot_files", options); - if (never_show_dot_files != Qtrue) - never_show_dot_files = Qfalse; - rb_iv_set(self, "@always_show_dot_files", always_show_dot_files); - rb_iv_set(self, "@never_show_dot_files", never_show_dot_files); - return Qnil; -} - -VALUE CommandTMatcher_sorted_matches_for(VALUE self, VALUE abbrev, VALUE options) -{ - // process optional options hash - VALUE limit_option = CommandT_option_from_hash("limit", options); - - // get unsorted matches - VALUE matches = CommandTMatcher_matches_for(self, abbrev); - - abbrev = StringValue(abbrev); - if (RSTRING_LEN(abbrev) == 0 || - (RSTRING_LEN(abbrev) == 1 && RSTRING_PTR(abbrev)[0] == '.')) - // alphabetic order if search string is only "" or "." - qsort(RARRAY_PTR(matches), RARRAY_LEN(matches), sizeof(VALUE), comp_alpha); - else - // for all other non-empty search strings, sort by score - qsort(RARRAY_PTR(matches), RARRAY_LEN(matches), sizeof(VALUE), comp_score); - - // apply optional limit option - long limit = NIL_P(limit_option) ? 0 : NUM2LONG(limit_option); - if (limit == 0 || RARRAY_LEN(matches) < limit) - limit = RARRAY_LEN(matches); - - // will return an array of strings, not an array of Match objects - for (long i = 0; i < limit; i++) - { - VALUE str = rb_funcall(RARRAY_PTR(matches)[i], rb_intern("to_s"), 0); - RARRAY_PTR(matches)[i] = str; - } - - // trim off any items beyond the limit - if (limit < RARRAY_LEN(matches)) - (void)rb_funcall(matches, rb_intern("slice!"), 2, LONG2NUM(limit), - LONG2NUM(RARRAY_LEN(matches) - limit)); - return matches; -} - -VALUE CommandTMatcher_matches_for(VALUE self, VALUE abbrev) -{ - if (NIL_P(abbrev)) - rb_raise(rb_eArgError, "nil abbrev"); - VALUE matches = rb_ary_new(); - VALUE scanner = rb_iv_get(self, "@scanner"); - VALUE always_show_dot_files = rb_iv_get(self, "@always_show_dot_files"); - VALUE never_show_dot_files = rb_iv_get(self, "@never_show_dot_files"); - VALUE options = Qnil; - if (always_show_dot_files == Qtrue) - { - options = rb_hash_new(); - rb_hash_aset(options, ID2SYM(rb_intern("always_show_dot_files")), always_show_dot_files); - } - else if (never_show_dot_files == Qtrue) - { - options = rb_hash_new(); - rb_hash_aset(options, ID2SYM(rb_intern("never_show_dot_files")), never_show_dot_files); - } - abbrev = rb_funcall(abbrev, rb_intern("downcase"), 0); - VALUE paths = rb_funcall(scanner, rb_intern("paths"), 0); - for (long i = 0, max = RARRAY_LEN(paths); i < max; i++) - { - VALUE path = RARRAY_PTR(paths)[i]; - VALUE match = rb_funcall(cCommandTMatch, rb_intern("new"), 3, path, abbrev, options); - if (rb_funcall(match, rb_intern("matches?"), 0) == Qtrue) - rb_funcall(matches, rb_intern("push"), 1, match); - } - return matches; -} -ruby/command-t/ext.h [[[1 -36 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -extern VALUE mCommandT; // module CommandT -extern VALUE cCommandTMatch; // class CommandT::Match -extern VALUE cCommandTMatcher; // class CommandT::Matcher - -// Encapsulates common pattern of checking for an option in an optional -// options hash. The hash itself may be nil, but an exception will be -// raised if it is not nil and not a hash. -VALUE CommandT_option_from_hash(const char *option, VALUE hash); - -// Debugging macro. -#define ruby_inspect(obj) rb_funcall(rb_mKernel, rb_intern("p"), 1, obj) -ruby/command-t/match.h [[[1 -29 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -extern VALUE CommandTMatch_initialize(int argc, VALUE *argv, VALUE self); -extern VALUE CommandTMatch_matches(VALUE self); -extern VALUE CommandTMatch_score(VALUE self); -extern VALUE CommandTMatch_to_s(VALUE self); -ruby/command-t/matcher.h [[[1 -30 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -extern VALUE CommandTMatcher_initialize(int argc, VALUE *argv, VALUE self); -extern VALUE CommandTMatcher_sorted_matches_for(VALUE self, VALUE abbrev, VALUE options); - -// most likely the function will be subsumed by the sorted_matcher_for function -extern VALUE CommandTMatcher_matches_for(VALUE self, VALUE abbrev); -ruby/command-t/ruby_compat.h [[[1 -49 -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -// for compatibility with older versions of Ruby which don't declare RSTRING_PTR -#ifndef RSTRING_PTR -#define RSTRING_PTR(s) (RSTRING(s)->ptr) -#endif - -// for compatibility with older versions of Ruby which don't declare RSTRING_LEN -#ifndef RSTRING_LEN -#define RSTRING_LEN(s) (RSTRING(s)->len) -#endif - -// for compatibility with older versions of Ruby which don't declare RARRAY_PTR -#ifndef RARRAY_PTR -#define RARRAY_PTR(a) (RARRAY(a)->ptr) -#endif - -// for compatibility with older versions of Ruby which don't declare RARRAY_LEN -#ifndef RARRAY_LEN -#define RARRAY_LEN(a) (RARRAY(a)->len) -#endif - -// for compatibility with older versions of Ruby which don't declare RFLOAT_VALUE -#ifndef RFLOAT_VALUE -#define RFLOAT_VALUE(f) (RFLOAT(f)->value) -#endif -ruby/command-t/depend [[[1 -24 -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -CFLAGS += -std=c99 -Wall -Wextra -Wno-unused-parameter -doc/command-t.txt [[[1 -786 -*command-t.txt* Command-T plug-in for Vim *command-t* - -CONTENTS *command-t-contents* - - 1. Introduction |command-t-intro| - 2. Requirements |command-t-requirements| - 3. Installation |command-t-installation| - 3. Managing using Pathogen |command-t-pathogen| - 4. Trouble-shooting |command-t-trouble-shooting| - 5. Usage |command-t-usage| - 6. Commands |command-t-commands| - 7. Mappings |command-t-mappings| - 8. Options |command-t-options| - 9. Authors |command-t-authors| -10. Website |command-t-website| -11. Donations |command-t-donations| -12. License |command-t-license| -13. History |command-t-history| - - -INTRODUCTION *command-t-intro* - -The Command-T plug-in provides an extremely fast, intuitive mechanism for -opening files and buffers with a minimal number of keystrokes. It's named -"Command-T" because it is inspired by the "Go to File" window bound to -Command-T in TextMate. - -Files are selected by typing characters that appear in their paths, and are -ordered by an algorithm which knows that characters that appear in certain -locations (for example, immediately after a path separator) should be given -more weight. - -To search efficiently, especially in large projects, you should adopt a -"path-centric" rather than a "filename-centric" mentality. That is you should -think more about where the desired file is found rather than what it is -called. This means narrowing your search down by including some characters -from the upper path components rather than just entering characters from the -filename itself. - -Screencasts demonstrating the plug-in can be viewed at: - - https://wincent.com/products/command-t - - -REQUIREMENTS *command-t-requirements* - -The plug-in requires Vim compiled with Ruby support, a compatible Ruby -installation at the operating system level, and a C compiler to build -the Ruby extension. - - -1. Vim compiled with Ruby support - -You can check for Ruby support by launching Vim with the --version switch: - - vim --version - -If "+ruby" appears in the version information then your version of Vim has -Ruby support. - -Another way to check is to simply try using the :ruby command from within Vim -itself: - - :ruby 1 - -If your Vim lacks support you'll see an error message like this: - - E319: Sorry, the command is not available in this version - -The version of Vim distributed with Mac OS X does not include Ruby support, -while MacVim does; it is available from: - - http://github.com/b4winckler/macvim/downloads - -For Windows users, the Vim 7.2 executable available from www.vim.org does -include Ruby support, and is recommended over version 7.3 (which links against -Ruby 1.9, but apparently has some bugs that need to be resolved). - - -2. Ruby - -In addition to having Ruby support in Vim, your system itself must have a -compatible Ruby install. "Compatible" means the same version as Vim itself -links against. If you use a different version then Command-T is unlikely -to work (see TROUBLE-SHOOTING below). - -On Mac OS X Snow Leopard, the system comes with Ruby 1.8.7 and all recent -versions of MacVim (the 7.2 snapshots and 7.3) are linked against it. - -On Linux and similar platforms, the linked version of Ruby will depend on -your distribution. You can usually find this out by examining the -compilation and linking flags displayed by the |:version| command in Vim, and -by looking at the output of: - - :ruby puts RUBY_VERSION - -A suitable Ruby environment for Windows can be installed using the Ruby -1.8.7-p299 RubyInstaller available at: - - http://rubyinstaller.org/downloads/archives - -If using RubyInstaller be sure to download the installer executable, not the -7-zip archive. When installing mark the checkbox "Add Ruby executables to your -PATH" so that Vim can find them. - - -3. C compiler - -Part of Command-T is implemented in C as a Ruby extension for speed, allowing -it to work responsively even on directory hierarchies containing enormous -numbers of files. As such, a C compiler is required in order to build the -extension and complete the installation. - -On Mac OS X, this can be obtained by installing the Xcode Tools that come on -the Mac OS X install disc. - -On Windows, the RubyInstaller Development Kit can be used to conveniently -install the necessary tool chain: - - http://rubyinstaller.org/downloads/archives - -At the time of writing, the appropriate development kit for use with Ruby -1.8.7 is DevKit-3.4.5r3-20091110. - -To use the Development Kit extract the archive contents to your C:\Ruby -folder. - - -INSTALLATION *command-t-installation* - -Command-T is distributed as a "vimball" which means that it can be installed -by opening it in Vim and then sourcing it: - - :e command-t.vba - :so % - -The files will be installed in your |'runtimepath'|. To check where this is -you can issue: - - :echo &rtp - -The C extension must then be built, which can be done from the shell. If you -use a typical |'runtimepath'| then the files were installed inside ~/.vim and -you can build the extension with: - - cd ~/.vim/ruby/command-t - ruby extconf.rb - make - -Note: If you are an RVM user, you must perform the build using the same -version of Ruby that Vim itself is linked against. This will often be the -system Ruby, which can be selected before issuing the "make" command with: - - rvm use system - - -MANAGING USING PATHOGEN *command-t-pathogen* - -Pathogen is a plugin that allows you to maintain plugin installations in -separate, isolated subdirectories under the "bundle" directory in your -|'runtimepath'|. The following examples assume that you already have -Pathogen installed and configured, and that you are installing into -~/.vim/bundle. For more information about Pathogen, see: - - http://www.vim.org/scripts/script.php?script_id=2332 - -If you manage your entire ~/.vim folder using Git then you can add the -Command-T repository as a submodule: - - cd ~/.vim - git submodule add git://git.wincent.com/command-t.git bundle/command-t - git submodule init - -Or if you just wish to do a simple clone instead of using submodules: - - cd ~/.vim - git clone git://git.wincent.com/command-t.git bundle/command-t - -Once you have a local copy of the repository you can update it at any time -with: - - cd ~/.vim/bundle/command-t - git pull - -Or you can switch to a specific release with: - - cd ~/.vim/bundle/command-t - git checkout 0.8b - -After installing or updating you must build the extension: - - cd ~/.vim/bundle/command-t - rake make - -While the Vimball installation automatically generates the help tags, under -Pathogen it is necessary to do so explicitly from inside Vim: - - :call pathogen#helptags() - - -TROUBLE-SHOOTING *command-t-trouble-shooting* - -Most installation problems are caused by a mismatch between the version of -Ruby on the host operating system, and the version of Ruby that Vim itself -linked against at compile time. For example, if one is 32-bit and the other is -64-bit, or one is from the Ruby 1.9 series and the other is from the 1.8 -series, then the plug-in is not likely to work. - -As such, on Mac OS X, I recommend using the standard Ruby that comes with the -system (currently 1.8.7) along with the latest version of MacVim (currently -version 7.3). If you wish to use custom builds of Ruby or of MacVim (not -recommmended) then you will have to take extra care to ensure that the exact -same Ruby environment is in effect when building Ruby, Vim and the Command-T -extension. - -For Windows, the following combination is known to work: - - - Vim 7.2 from http://www.vim.org/download.php: - ftp://ftp.vim.org/pub/vim/pc/gvim72.exe - - Ruby 1.8.7-p299 from http://rubyinstaller.org/downloads/archives: - http://rubyforge.org/frs/download.php/71492/rubyinstaller-1.8.7-p299.exe - - DevKit 3.4.5r3-20091110 from http://rubyinstaller.org/downloads/archives: - http://rubyforge.org/frs/download.php/66888/devkit-3.4.5r3-20091110.7z - -If a problem occurs the first thing you should do is inspect the output of: - - ruby extconf.rb - make - -During the installation, and: - - vim --version - -And compare the compilation and linker flags that were passed to the -extension and to Vim itself when they were built. If the Ruby-related -flags or architecture flags are different then it is likely that something -has changed in your Ruby environment and the extension may not work until -you eliminate the discrepancy. - - -USAGE *command-t-usage* - -Bring up the Command-T file window by typing: - - t - -This mapping is set up automatically for you, provided you do not already have -a mapping for t or |:CommandT|. You can also bring up the file window -by issuing the command: - - :CommandT - -A prompt will appear at the bottom of the screen along with a file window -showing all of the files in the current directory (as returned by the -|:pwd| command). - -For the most efficient file navigation within a project it's recommended that -you |:cd| into the root directory of your project when starting to work on it. -If you wish to open a file from outside of the project folder you can pass in -an optional path argument (relative or absolute) to |:CommandT|: - - :CommandT ../path/to/other/files - -Type letters in the prompt to narrow down the selection, showing only the -files whose paths contain those letters in the specified order. Letters do not -need to appear consecutively in a path in order for it to be classified as a -match. - -Once the desired file has been selected it can be opened by pressing . -(By default files are opened in the current window, but there are other -mappings that you can use to open in a vertical or horizontal split, or in -a new tab.) Note that if you have |'nohidden'| set and there are unsaved -changes in the current window when you press then opening in the current -window would fail; in this case Command-T will open the file in a new split. - -The following mappings are active when the prompt has focus: - - delete the character to the left of the cursor - delete the character at the cursor - move the cursor one character to the left - move the cursor one character to the left - move the cursor one character to the right - move the cursor one character to the right - move the cursor to the start (left) - move the cursor to the end (right) - clear the contents of the prompt - change focus to the file listing - -The following mappings are active when the file listing has focus: - - change focus to the prompt - -The following mappings are active when either the prompt or the file listing -has focus: - - open the selected file - open the selected file in a new split window - open the selected file in a new split window - open the selected file in a new vertical split window - open the selected file in a new tab - select next file in the file listing - select next file in the file listing - select next file in the file listing - select previous file in the file listing - select previous file in the file listing - select previous file in the file listing - cancel (dismisses file listing) - -The following is also available on terminals which support it: - - cancel (dismisses file listing) - -Note that the default mappings can be overriden by setting options in your -~/.vimrc file (see the OPTIONS section for a full list of available options). - -In addition, when the file listing has focus, typing a character will cause -the selection to jump to the first path which begins with that character. -Typing multiple characters consecutively can be used to distinguish between -paths which begin with the same prefix. - - -COMMANDS *command-t-commands* - - *:CommandT* -|:CommandT| Brings up the Command-T file window, starting in the - current working directory as returned by the|:pwd| - command. - - *:CommandTBuffer* -|:CommandTBuffer|Brings up the Command-T buffer window. - This works exactly like the standard file window, - except that the selection is limited to files that - you already have open in buffers. - - *:CommandTFlush* -|:CommandTFlush|Instructs the plug-in to flush its path cache, causing - the directory to be rescanned for new or deleted paths - the next time the file window is shown. In addition, all - configuration settings are re-evaluated, causing any - changes made to settings via the |:let| command to be picked - up. - - -MAPPINGS *command-t-mappings* - -By default Command-T comes with only two mappings: - - t bring up the Command-T file window - b bring up the Command-T buffer window - -However, Command-T won't overwrite a pre-existing mapping so if you prefer -to define different mappings use lines like these in your ~/.vimrc: - - nmap t :CommandT - nmap b :CommandTBuffer - -Replacing "t" or "b" with your mapping of choice. - -Note that in the case of MacVim you actually can map to Command-T (written -as in Vim) in your ~/.gvimrc file if you first unmap the existing menu -binding of Command-T to "New Tab": - - if has("gui_macvim") - macmenu &File.New\ Tab key= - map :CommandT - endif - -When the Command-T window is active a number of other additional mappings -become available for doing things like moving between and selecting matches. -These are fully described above in the USAGE section, and settings for -overriding the mappings are listed below under OPTIONS. - - -OPTIONS *command-t-options* - -A number of options may be set in your ~/.vimrc to influence the behaviour of -the plug-in. To set an option, you include a line like this in your ~/.vimrc: - - let g:CommandTMaxFiles=20000 - -To have Command-T pick up new settings immediately (that is, without having -to restart Vim) you can issue the |:CommandTFlush| command after making -changes via |:let|. - -Following is a list of all available options: - - *g:CommandTMaxFiles* - |g:CommandTMaxFiles| number (default 10000) - - The maximum number of files that will be considered when scanning the - current directory. Upon reaching this number scanning stops. This - limit applies only to file listings and is ignored for buffer - listings. - - *g:CommandTMaxDepth* - |g:CommandTMaxDepth| number (default 15) - - The maximum depth (levels of recursion) to be explored when scanning the - current directory. Any directories at levels beyond this depth will be - skipped. - - *g:CommandTMaxHeight* - |g:CommandTMaxHeight| number (default: 0) - - The maximum height in lines the match window is allowed to expand to. - If set to 0, the window will occupy as much of the available space as - needed to show matching entries. - - *g:CommandTAlwaysShowDotFiles* - |g:CommandTAlwaysShowDotFiles| boolean (default: 0) - - When showing the file listing Command-T will by default show dot-files - only if the entered search string contains a dot that could cause a - dot-file to match. When set to a non-zero value, this setting instructs - Command-T to always include matching dot-files in the match list - regardless of whether the search string contains a dot. See also - |g:CommandTNeverShowDotFiles|. Note that this setting only influences - the file listing; the buffer listing treats dot-files like any other - file. - - *g:CommandTNeverShowDotFiles* - |g:CommandTNeverShowDotFiles| boolean (default: 0) - - In the file listing, Command-T will by default show dot-files if the - entered search string contains a dot that could cause a dot-file to - match. When set to a non-zero value, this setting instructs Command-T to - never show dot-files under any circumstances. Note that it is - contradictory to set both this setting and - |g:CommandTAlwaysShowDotFiles| to true, and if you do so Vim will suffer - from headaches, nervous twitches, and sudden mood swings. This setting - has no effect in buffer listings, where dot files are treated like any - other file. - - *g:CommandTScanDotDirectories* - |g:CommandTScanDotDirectories| boolean (default: 0) - - Normally Command-T will not recurse into "dot-directories" (directories - whose names begin with a dot) while performing its initial scan. Set - this setting to a non-zero value to override this behavior and recurse. - Note that this setting is completely independent of the - |g:CommandTAlwaysShowDotFiles| and |g:CommandTNeverShowDotFiles| - settings; those apply only to the selection and display of matches - (after scanning has been performed), whereas - |g:CommandTScanDotDirectories| affects the behaviour at scan-time. - - Note also that even with this setting off you can still use Command-T to - open files inside a "dot-directory" such as ~/.vim, but you have to use - the |:cd| command to change into that directory first. For example: - - :cd ~/.vim - :CommandT - - *g:CommandTMatchWindowAtTop* - |g:CommandTMatchWindowAtTop| boolean (default: 0) - - When this setting is off (the default) the match window will appear at - the bottom so as to keep it near to the prompt. Turning it on causes the - match window to appear at the top instead. This may be preferable if you - want the best match (usually the first one) to appear in a fixed location - on the screen rather than moving as the number of matches changes during - typing. - - *g:CommandTMatchWindowReverse* - |g:CommandTMatchWindowReverse| boolean (default: 0) - - When this setting is off (the default) the matches will appear from - top to bottom with the topmost being selected. Turning it on causes the - matches to be reversed so the best match is at the bottom and the - initially selected match is the bottom most. This may be preferable if - you want the best match to appear in a fixed location on the screen - but still be near the prompt at the bottom. - -As well as the basic options listed above, there are a number of settings that -can be used to override the default key mappings used by Command-T. For -example, to set as the mapping for cancelling (dismissing) the Command-T -window, you would add the following to your ~/.vimrc: - - let g:CommandTCancelMap='' - -Multiple, alternative mappings may be specified using list syntax: - - let g:CommandTCancelMap=['', ''] - -Following is a list of all map settings and their defaults: - - Setting Default mapping(s) - - *g:CommandTBackspaceMap* - |g:CommandTBackspaceMap| - - *g:CommandTDeleteMap* - |g:CommandTDeleteMap| - - *g:CommandTAcceptSelectionMap* - |g:CommandTAcceptSelectionMap| - - *g:CommandTAcceptSelectionSplitMap* - |g:CommandTAcceptSelectionSplitMap| - - - *g:CommandTAcceptSelectionTabMap* - |g:CommandTAcceptSelectionTabMap| - - *g:CommandTAcceptSelectionVSplitMap* - |g:CommandTAcceptSelectionVSplitMap| - - *g:CommandTToggleFocusMap* - |g:CommandTToggleFocusMap| - - *g:CommandTCancelMap* - |g:CommandTCancelMap| - (not on all terminals) - - *g:CommandTSelectNextMap* - |g:CommandTSelectNextMap| - - - - *g:CommandTSelectPrevMap* - |g:CommandTSelectPrevMap| - - - - *g:CommandTClearMap* - |g:CommandTClearMap| - - *g:CommandTCursorLeftMap* - |g:CommandTCursorLeftMap| - - - *g:CommandTCursorRightMap* - |g:CommandTCursorRightMap| - - - *g:CommandTCursorEndMap* - |g:CommandTCursorEndMap| - - *g:CommandTCursorStartMap* - |g:CommandTCursorStartMap| - -In addition to the options provided by Command-T itself, some of Vim's own -settings can be used to control behavior: - - *command-t-wildignore* - |'wildignore'| string (default: '') - - Vim's |'wildignore'| setting is used to determine which files should be - excluded from listings. This is a comma-separated list of glob patterns. - It defaults to the empty string, but common settings include "*.o,*.obj" - (to exclude object files) or ".git,.svn" (to exclude SCM metadata - directories). For example: - - :set wildignore+=*.o,*.obj,.git - - A pattern such as "vendor/rails/**" would exclude all files and - subdirectories inside the "vendor/rails" directory (relative to - directory Command-T starts in). - - See the |'wildignore'| documentation for more information. - - -AUTHORS *command-t-authors* - -Command-T is written and maintained by Wincent Colaiuta . -Other contributors that have submitted patches include (in alphabetical -order): - - Daniel Hahler - Lucas de Vries - Matthew Todd - Mike Lundy - Scott Bronson - Steven Moazami - Sung Pae - Victor Hugo Borja - Zak Johnson - -As this was the first Vim plug-in I had ever written I was heavily influenced -by the design of the LustyExplorer plug-in by Stephen Bach, which I understand -is one of the largest Ruby-based Vim plug-ins to date. - -While the Command-T codebase doesn't contain any code directly copied from -LustyExplorer, I did use it as a reference for answers to basic questions (like -"How do you do 'X' in a Ruby-based Vim plug-in?"), and also copied some basic -architectural decisions (like the division of the code into Prompt, Settings -and MatchWindow classes). - -LustyExplorer is available from: - - http://www.vim.org/scripts/script.php?script_id=1890 - - -WEBSITE *command-t-website* - -The official website for Command-T is: - - https://wincent.com/products/command-t - -The latest release will always be available from there. - -Development in progress can be inspected via the project's Git repository -browser at: - - https://wincent.com/repos/command-t - -A copy of each release is also available from the official Vim scripts site -at: - - http://www.vim.org/scripts/script.php?script_id=3025 - -Bug reports should be submitted to the issue tracker at: - - https://wincent.com/issues - - -DONATIONS *command-t-donations* - -Command-T itself is free software released under the terms of the BSD license. -If you would like to support further development you can make a donation via -PayPal to win@wincent.com: - - https://wincent.com/products/command-t/donations - - -LICENSE *command-t-license* - -Copyright 2010-2011 Wincent Colaiuta. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - - -HISTORY *command-t-history* - -1.2.1 (30 April 2011) - -- Remove duplicate copy of the documentation that was causing "Duplicate tag" - errors -- Mitigate issue with distracting blinking cursor in non-GUI versions of Vim - (patch from Steven Moazami) - -1.2 (30 April 2011) - -- added |g:CommandTMatchWindowReverse| option, to reverse the order of items - in the match listing (patch from Steven Moazami) - -1.1b2 (26 March 2011) - -- fix a glitch in the release process; the plugin itself is unchanged since - 1.1b - -1.1b (26 March 2011) - -- add |:CommandTBuffer| command for quickly selecting among open buffers - -1.0.1 (5 January 2011) - -- work around bug when mapping |:CommandTFlush|, wherein the default mapping - for |:CommandT| would not be set up -- clean up when leaving the Command-T buffer via unexpected means (such as - with or similar) - -1.0 (26 November 2010) - -- make relative path simplification work on Windows - -1.0b (5 November 2010) - -- work around platform-specific Vim 7.3 bug seen by some users (wherein - Vim always falsely reports to Ruby that the buffer numbers is 0) -- re-use the buffer that is used to show the match listing, rather than - throwing it away and recreating it each time Command-T is shown; this - stops the buffer numbers from creeping up needlessly - -0.9 (8 October 2010) - -- use relative paths when opening files inside the current working directory - in order to keep buffer listings as brief as possible (patch from Matthew - Todd) - -0.8.1 (14 September 2010) - -- fix mapping issues for users who have set |'notimeout'| (patch from Sung - Pae) - -0.8 (19 August 2010) - -- overrides for the default mappings can now be lists of strings, allowing - multiple mappings to be defined for any given action -- t mapping only set up if no other map for |:CommandT| exists - (patch from Scott Bronson) -- prevent folds from appearing in the match listing -- tweaks to avoid the likelihood of "Not enough room" errors when trying to - open files -- watch out for "nil" windows when restoring window dimensions -- optimizations (avoid some repeated downcasing) -- move all Ruby files under the "command-t" subdirectory and avoid polluting - the "Vim" module namespace - -0.8b (11 July 2010) - -- large overhaul of the scoring algorithm to make the ordering of returned - results more intuitive; given the scope of the changes and room for - optimization of the new algorithm, this release is labelled as "beta" - -0.7 (10 June 2010) - -- handle more |'wildignore'| patterns by delegating to Vim's own |expand()| - function; with this change it is now viable to exclude patterns such as - 'vendor/rails/**' in addition to filename-only patterns like '*.o' and - '.git' (patch from Mike Lundy) -- always sort results alphabetically for empty search strings; this eliminates - filesystem-specific variations (patch from Mike Lundy) - -0.6 (28 April 2010) - -- |:CommandT| now accepts an optional parameter to specify the starting - directory, temporarily overriding the usual default of Vim's |:pwd| -- fix truncated paths when operating from root directory - -0.5.1 (11 April 2010) - -- fix for Ruby 1.9 compatibility regression introduced in 0.5 -- documentation enhancements, specifically targetted at Windows users - -0.5 (3 April 2010) - -- |:CommandTFlush| now re-evaluates settings, allowing changes made via |let| - to be picked up without having to restart Vim -- fix premature abort when scanning very deep directory hierarchies -- remove broken || key mapping on vt100 and xterm terminals -- provide settings for overriding default mappings -- minor performance optimization - -0.4 (27 March 2010) - -- add |g:CommandTMatchWindowAtTop| setting (patch from Zak Johnson) -- documentation fixes and enhancements -- internal refactoring and simplification - -0.3 (24 March 2010) - -- add |g:CommandTMaxHeight| setting for controlling the maximum height of the - match window (patch from Lucas de Vries) -- fix bug where |'list'| setting might be inappropriately set after dismissing - Command-T -- compatibility fix for different behaviour of "autoload" under Ruby 1.9.1 -- avoid "highlight group not found" warning when run under a version of Vim - that does not have syntax highlighting support -- open in split when opening normally would fail due to |'hidden'| and - |'modified'| values - -0.2 (23 March 2010) - -- compatibility fixes for compilation under Ruby 1.9 series -- compatibility fixes for compilation under Ruby 1.8.5 -- compatibility fixes for Windows and other non-UNIX platforms -- suppress "mapping already exists" message if t mapping is already - defined when plug-in is loaded -- exclude paths based on |'wildignore'| setting rather than a hardcoded - regular expression - -0.1 (22 March 2010) - -- initial public release - ------------------------------------------------------------------------------- -vim:tw=78:ft=help: -plugin/command-t.vim [[[1 -164 -" command-t.vim -" Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -" -" Redistribution and use in source and binary forms, with or without -" modification, are permitted provided that the following conditions are met: -" -" 1. Redistributions of source code must retain the above copyright notice, -" this list of conditions and the following disclaimer. -" 2. Redistributions in binary form must reproduce the above copyright notice, -" this list of conditions and the following disclaimer in the documentation -" and/or other materials provided with the distribution. -" -" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -" POSSIBILITY OF SUCH DAMAGE. - -if exists("g:command_t_loaded") - finish -endif -let g:command_t_loaded = 1 - -command CommandTBuffer call CommandTShowBufferFinder() -command -nargs=? -complete=dir CommandT call CommandTShowFileFinder() -command CommandTFlush call CommandTFlush() - -if !hasmapto(':CommandT') - silent! nmap t :CommandT -endif - -if !hasmapto(':CommandTBuffer') - silent! nmap b :CommandTBuffer -endif - -function s:CommandTRubyWarning() - echohl WarningMsg - echo "command-t.vim requires Vim to be compiled with Ruby support" - echo "For more information type: :help command-t" - echohl none -endfunction - -function s:CommandTShowBufferFinder() - if has('ruby') - ruby $command_t.show_buffer_finder - else - call s:CommandTRubyWarning() - endif -endfunction - -function s:CommandTShowFileFinder(arg) - if has('ruby') - ruby $command_t.show_file_finder - else - call s:CommandTRubyWarning() - endif -endfunction - -function s:CommandTFlush() - if has('ruby') - ruby $command_t.flush - else - call s:CommandTRubyWarning() - endif -endfunction - -if !has('ruby') - finish -endif - -function CommandTHandleKey(arg) - ruby $command_t.handle_key -endfunction - -function CommandTBackspace() - ruby $command_t.backspace -endfunction - -function CommandTDelete() - ruby $command_t.delete -endfunction - -function CommandTAcceptSelection() - ruby $command_t.accept_selection -endfunction - -function CommandTAcceptSelectionTab() - ruby $command_t.accept_selection :command => 'tabe' -endfunction - -function CommandTAcceptSelectionSplit() - ruby $command_t.accept_selection :command => 'sp' -endfunction - -function CommandTAcceptSelectionVSplit() - ruby $command_t.accept_selection :command => 'vs' -endfunction - -function CommandTToggleFocus() - ruby $command_t.toggle_focus -endfunction - -function CommandTCancel() - ruby $command_t.cancel -endfunction - -function CommandTSelectNext() - ruby $command_t.select_next -endfunction - -function CommandTSelectPrev() - ruby $command_t.select_prev -endfunction - -function CommandTClear() - ruby $command_t.clear -endfunction - -function CommandTCursorLeft() - ruby $command_t.cursor_left -endfunction - -function CommandTCursorRight() - ruby $command_t.cursor_right -endfunction - -function CommandTCursorEnd() - ruby $command_t.cursor_end -endfunction - -function CommandTCursorStart() - ruby $command_t.cursor_start -endfunction - -ruby << EOF - # require Ruby files - begin - # prepare controller - require 'command-t/vim' - require 'command-t/controller' - $command_t = CommandT::Controller.new - rescue LoadError - load_path_modified = false - ::VIM::evaluate('&runtimepath').to_s.split(',').each do |path| - lib = "#{path}/ruby" - if !$LOAD_PATH.include?(lib) and File.exist?(lib) - $LOAD_PATH << lib - load_path_modified = true - end - end - retry if load_path_modified - - # could get here if C extension was not compiled, or was compiled - # for the wrong architecture or Ruby version - require 'command-t/stub' - $command_t = CommandT::Stub.new - end -EOF diff --git a/vim/tmp/command_t/doc/command-t.txt b/vim/tmp/command_t/doc/command-t.txt deleted file mode 100644 index 65a64a3..0000000 --- a/vim/tmp/command_t/doc/command-t.txt +++ /dev/null @@ -1,786 +0,0 @@ -*command-t.txt* Command-T plug-in for Vim *command-t* - -CONTENTS *command-t-contents* - - 1. Introduction |command-t-intro| - 2. Requirements |command-t-requirements| - 3. Installation |command-t-installation| - 3. Managing using Pathogen |command-t-pathogen| - 4. Trouble-shooting |command-t-trouble-shooting| - 5. Usage |command-t-usage| - 6. Commands |command-t-commands| - 7. Mappings |command-t-mappings| - 8. Options |command-t-options| - 9. Authors |command-t-authors| -10. Website |command-t-website| -11. Donations |command-t-donations| -12. License |command-t-license| -13. History |command-t-history| - - -INTRODUCTION *command-t-intro* - -The Command-T plug-in provides an extremely fast, intuitive mechanism for -opening files and buffers with a minimal number of keystrokes. It's named -"Command-T" because it is inspired by the "Go to File" window bound to -Command-T in TextMate. - -Files are selected by typing characters that appear in their paths, and are -ordered by an algorithm which knows that characters that appear in certain -locations (for example, immediately after a path separator) should be given -more weight. - -To search efficiently, especially in large projects, you should adopt a -"path-centric" rather than a "filename-centric" mentality. That is you should -think more about where the desired file is found rather than what it is -called. This means narrowing your search down by including some characters -from the upper path components rather than just entering characters from the -filename itself. - -Screencasts demonstrating the plug-in can be viewed at: - - https://wincent.com/products/command-t - - -REQUIREMENTS *command-t-requirements* - -The plug-in requires Vim compiled with Ruby support, a compatible Ruby -installation at the operating system level, and a C compiler to build -the Ruby extension. - - -1. Vim compiled with Ruby support - -You can check for Ruby support by launching Vim with the --version switch: - - vim --version - -If "+ruby" appears in the version information then your version of Vim has -Ruby support. - -Another way to check is to simply try using the :ruby command from within Vim -itself: - - :ruby 1 - -If your Vim lacks support you'll see an error message like this: - - E319: Sorry, the command is not available in this version - -The version of Vim distributed with Mac OS X does not include Ruby support, -while MacVim does; it is available from: - - http://github.com/b4winckler/macvim/downloads - -For Windows users, the Vim 7.2 executable available from www.vim.org does -include Ruby support, and is recommended over version 7.3 (which links against -Ruby 1.9, but apparently has some bugs that need to be resolved). - - -2. Ruby - -In addition to having Ruby support in Vim, your system itself must have a -compatible Ruby install. "Compatible" means the same version as Vim itself -links against. If you use a different version then Command-T is unlikely -to work (see TROUBLE-SHOOTING below). - -On Mac OS X Snow Leopard, the system comes with Ruby 1.8.7 and all recent -versions of MacVim (the 7.2 snapshots and 7.3) are linked against it. - -On Linux and similar platforms, the linked version of Ruby will depend on -your distribution. You can usually find this out by examining the -compilation and linking flags displayed by the |:version| command in Vim, and -by looking at the output of: - - :ruby puts RUBY_VERSION - -A suitable Ruby environment for Windows can be installed using the Ruby -1.8.7-p299 RubyInstaller available at: - - http://rubyinstaller.org/downloads/archives - -If using RubyInstaller be sure to download the installer executable, not the -7-zip archive. When installing mark the checkbox "Add Ruby executables to your -PATH" so that Vim can find them. - - -3. C compiler - -Part of Command-T is implemented in C as a Ruby extension for speed, allowing -it to work responsively even on directory hierarchies containing enormous -numbers of files. As such, a C compiler is required in order to build the -extension and complete the installation. - -On Mac OS X, this can be obtained by installing the Xcode Tools that come on -the Mac OS X install disc. - -On Windows, the RubyInstaller Development Kit can be used to conveniently -install the necessary tool chain: - - http://rubyinstaller.org/downloads/archives - -At the time of writing, the appropriate development kit for use with Ruby -1.8.7 is DevKit-3.4.5r3-20091110. - -To use the Development Kit extract the archive contents to your C:\Ruby -folder. - - -INSTALLATION *command-t-installation* - -Command-T is distributed as a "vimball" which means that it can be installed -by opening it in Vim and then sourcing it: - - :e command-t.vba - :so % - -The files will be installed in your |'runtimepath'|. To check where this is -you can issue: - - :echo &rtp - -The C extension must then be built, which can be done from the shell. If you -use a typical |'runtimepath'| then the files were installed inside ~/.vim and -you can build the extension with: - - cd ~/.vim/ruby/command-t - ruby extconf.rb - make - -Note: If you are an RVM user, you must perform the build using the same -version of Ruby that Vim itself is linked against. This will often be the -system Ruby, which can be selected before issuing the "make" command with: - - rvm use system - - -MANAGING USING PATHOGEN *command-t-pathogen* - -Pathogen is a plugin that allows you to maintain plugin installations in -separate, isolated subdirectories under the "bundle" directory in your -|'runtimepath'|. The following examples assume that you already have -Pathogen installed and configured, and that you are installing into -~/.vim/bundle. For more information about Pathogen, see: - - http://www.vim.org/scripts/script.php?script_id=2332 - -If you manage your entire ~/.vim folder using Git then you can add the -Command-T repository as a submodule: - - cd ~/.vim - git submodule add git://git.wincent.com/command-t.git bundle/command-t - git submodule init - -Or if you just wish to do a simple clone instead of using submodules: - - cd ~/.vim - git clone git://git.wincent.com/command-t.git bundle/command-t - -Once you have a local copy of the repository you can update it at any time -with: - - cd ~/.vim/bundle/command-t - git pull - -Or you can switch to a specific release with: - - cd ~/.vim/bundle/command-t - git checkout 0.8b - -After installing or updating you must build the extension: - - cd ~/.vim/bundle/command-t - rake make - -While the Vimball installation automatically generates the help tags, under -Pathogen it is necessary to do so explicitly from inside Vim: - - :call pathogen#helptags() - - -TROUBLE-SHOOTING *command-t-trouble-shooting* - -Most installation problems are caused by a mismatch between the version of -Ruby on the host operating system, and the version of Ruby that Vim itself -linked against at compile time. For example, if one is 32-bit and the other is -64-bit, or one is from the Ruby 1.9 series and the other is from the 1.8 -series, then the plug-in is not likely to work. - -As such, on Mac OS X, I recommend using the standard Ruby that comes with the -system (currently 1.8.7) along with the latest version of MacVim (currently -version 7.3). If you wish to use custom builds of Ruby or of MacVim (not -recommmended) then you will have to take extra care to ensure that the exact -same Ruby environment is in effect when building Ruby, Vim and the Command-T -extension. - -For Windows, the following combination is known to work: - - - Vim 7.2 from http://www.vim.org/download.php: - ftp://ftp.vim.org/pub/vim/pc/gvim72.exe - - Ruby 1.8.7-p299 from http://rubyinstaller.org/downloads/archives: - http://rubyforge.org/frs/download.php/71492/rubyinstaller-1.8.7-p299.exe - - DevKit 3.4.5r3-20091110 from http://rubyinstaller.org/downloads/archives: - http://rubyforge.org/frs/download.php/66888/devkit-3.4.5r3-20091110.7z - -If a problem occurs the first thing you should do is inspect the output of: - - ruby extconf.rb - make - -During the installation, and: - - vim --version - -And compare the compilation and linker flags that were passed to the -extension and to Vim itself when they were built. If the Ruby-related -flags or architecture flags are different then it is likely that something -has changed in your Ruby environment and the extension may not work until -you eliminate the discrepancy. - - -USAGE *command-t-usage* - -Bring up the Command-T file window by typing: - - t - -This mapping is set up automatically for you, provided you do not already have -a mapping for t or |:CommandT|. You can also bring up the file window -by issuing the command: - - :CommandT - -A prompt will appear at the bottom of the screen along with a file window -showing all of the files in the current directory (as returned by the -|:pwd| command). - -For the most efficient file navigation within a project it's recommended that -you |:cd| into the root directory of your project when starting to work on it. -If you wish to open a file from outside of the project folder you can pass in -an optional path argument (relative or absolute) to |:CommandT|: - - :CommandT ../path/to/other/files - -Type letters in the prompt to narrow down the selection, showing only the -files whose paths contain those letters in the specified order. Letters do not -need to appear consecutively in a path in order for it to be classified as a -match. - -Once the desired file has been selected it can be opened by pressing . -(By default files are opened in the current window, but there are other -mappings that you can use to open in a vertical or horizontal split, or in -a new tab.) Note that if you have |'nohidden'| set and there are unsaved -changes in the current window when you press then opening in the current -window would fail; in this case Command-T will open the file in a new split. - -The following mappings are active when the prompt has focus: - - delete the character to the left of the cursor - delete the character at the cursor - move the cursor one character to the left - move the cursor one character to the left - move the cursor one character to the right - move the cursor one character to the right - move the cursor to the start (left) - move the cursor to the end (right) - clear the contents of the prompt - change focus to the file listing - -The following mappings are active when the file listing has focus: - - change focus to the prompt - -The following mappings are active when either the prompt or the file listing -has focus: - - open the selected file - open the selected file in a new split window - open the selected file in a new split window - open the selected file in a new vertical split window - open the selected file in a new tab - select next file in the file listing - select next file in the file listing - select next file in the file listing - select previous file in the file listing - select previous file in the file listing - select previous file in the file listing - cancel (dismisses file listing) - -The following is also available on terminals which support it: - - cancel (dismisses file listing) - -Note that the default mappings can be overriden by setting options in your -~/.vimrc file (see the OPTIONS section for a full list of available options). - -In addition, when the file listing has focus, typing a character will cause -the selection to jump to the first path which begins with that character. -Typing multiple characters consecutively can be used to distinguish between -paths which begin with the same prefix. - - -COMMANDS *command-t-commands* - - *:CommandT* -|:CommandT| Brings up the Command-T file window, starting in the - current working directory as returned by the|:pwd| - command. - - *:CommandTBuffer* -|:CommandTBuffer|Brings up the Command-T buffer window. - This works exactly like the standard file window, - except that the selection is limited to files that - you already have open in buffers. - - *:CommandTFlush* -|:CommandTFlush|Instructs the plug-in to flush its path cache, causing - the directory to be rescanned for new or deleted paths - the next time the file window is shown. In addition, all - configuration settings are re-evaluated, causing any - changes made to settings via the |:let| command to be picked - up. - - -MAPPINGS *command-t-mappings* - -By default Command-T comes with only two mappings: - - t bring up the Command-T file window - b bring up the Command-T buffer window - -However, Command-T won't overwrite a pre-existing mapping so if you prefer -to define different mappings use lines like these in your ~/.vimrc: - - nmap t :CommandT - nmap b :CommandTBuffer - -Replacing "t" or "b" with your mapping of choice. - -Note that in the case of MacVim you actually can map to Command-T (written -as in Vim) in your ~/.gvimrc file if you first unmap the existing menu -binding of Command-T to "New Tab": - - if has("gui_macvim") - macmenu &File.New\ Tab key= - map :CommandT - endif - -When the Command-T window is active a number of other additional mappings -become available for doing things like moving between and selecting matches. -These are fully described above in the USAGE section, and settings for -overriding the mappings are listed below under OPTIONS. - - -OPTIONS *command-t-options* - -A number of options may be set in your ~/.vimrc to influence the behaviour of -the plug-in. To set an option, you include a line like this in your ~/.vimrc: - - let g:CommandTMaxFiles=20000 - -To have Command-T pick up new settings immediately (that is, without having -to restart Vim) you can issue the |:CommandTFlush| command after making -changes via |:let|. - -Following is a list of all available options: - - *g:CommandTMaxFiles* - |g:CommandTMaxFiles| number (default 10000) - - The maximum number of files that will be considered when scanning the - current directory. Upon reaching this number scanning stops. This - limit applies only to file listings and is ignored for buffer - listings. - - *g:CommandTMaxDepth* - |g:CommandTMaxDepth| number (default 15) - - The maximum depth (levels of recursion) to be explored when scanning the - current directory. Any directories at levels beyond this depth will be - skipped. - - *g:CommandTMaxHeight* - |g:CommandTMaxHeight| number (default: 0) - - The maximum height in lines the match window is allowed to expand to. - If set to 0, the window will occupy as much of the available space as - needed to show matching entries. - - *g:CommandTAlwaysShowDotFiles* - |g:CommandTAlwaysShowDotFiles| boolean (default: 0) - - When showing the file listing Command-T will by default show dot-files - only if the entered search string contains a dot that could cause a - dot-file to match. When set to a non-zero value, this setting instructs - Command-T to always include matching dot-files in the match list - regardless of whether the search string contains a dot. See also - |g:CommandTNeverShowDotFiles|. Note that this setting only influences - the file listing; the buffer listing treats dot-files like any other - file. - - *g:CommandTNeverShowDotFiles* - |g:CommandTNeverShowDotFiles| boolean (default: 0) - - In the file listing, Command-T will by default show dot-files if the - entered search string contains a dot that could cause a dot-file to - match. When set to a non-zero value, this setting instructs Command-T to - never show dot-files under any circumstances. Note that it is - contradictory to set both this setting and - |g:CommandTAlwaysShowDotFiles| to true, and if you do so Vim will suffer - from headaches, nervous twitches, and sudden mood swings. This setting - has no effect in buffer listings, where dot files are treated like any - other file. - - *g:CommandTScanDotDirectories* - |g:CommandTScanDotDirectories| boolean (default: 0) - - Normally Command-T will not recurse into "dot-directories" (directories - whose names begin with a dot) while performing its initial scan. Set - this setting to a non-zero value to override this behavior and recurse. - Note that this setting is completely independent of the - |g:CommandTAlwaysShowDotFiles| and |g:CommandTNeverShowDotFiles| - settings; those apply only to the selection and display of matches - (after scanning has been performed), whereas - |g:CommandTScanDotDirectories| affects the behaviour at scan-time. - - Note also that even with this setting off you can still use Command-T to - open files inside a "dot-directory" such as ~/.vim, but you have to use - the |:cd| command to change into that directory first. For example: - - :cd ~/.vim - :CommandT - - *g:CommandTMatchWindowAtTop* - |g:CommandTMatchWindowAtTop| boolean (default: 0) - - When this setting is off (the default) the match window will appear at - the bottom so as to keep it near to the prompt. Turning it on causes the - match window to appear at the top instead. This may be preferable if you - want the best match (usually the first one) to appear in a fixed location - on the screen rather than moving as the number of matches changes during - typing. - - *g:CommandTMatchWindowReverse* - |g:CommandTMatchWindowReverse| boolean (default: 0) - - When this setting is off (the default) the matches will appear from - top to bottom with the topmost being selected. Turning it on causes the - matches to be reversed so the best match is at the bottom and the - initially selected match is the bottom most. This may be preferable if - you want the best match to appear in a fixed location on the screen - but still be near the prompt at the bottom. - -As well as the basic options listed above, there are a number of settings that -can be used to override the default key mappings used by Command-T. For -example, to set as the mapping for cancelling (dismissing) the Command-T -window, you would add the following to your ~/.vimrc: - - let g:CommandTCancelMap='' - -Multiple, alternative mappings may be specified using list syntax: - - let g:CommandTCancelMap=['', ''] - -Following is a list of all map settings and their defaults: - - Setting Default mapping(s) - - *g:CommandTBackspaceMap* - |g:CommandTBackspaceMap| - - *g:CommandTDeleteMap* - |g:CommandTDeleteMap| - - *g:CommandTAcceptSelectionMap* - |g:CommandTAcceptSelectionMap| - - *g:CommandTAcceptSelectionSplitMap* - |g:CommandTAcceptSelectionSplitMap| - - - *g:CommandTAcceptSelectionTabMap* - |g:CommandTAcceptSelectionTabMap| - - *g:CommandTAcceptSelectionVSplitMap* - |g:CommandTAcceptSelectionVSplitMap| - - *g:CommandTToggleFocusMap* - |g:CommandTToggleFocusMap| - - *g:CommandTCancelMap* - |g:CommandTCancelMap| - (not on all terminals) - - *g:CommandTSelectNextMap* - |g:CommandTSelectNextMap| - - - - *g:CommandTSelectPrevMap* - |g:CommandTSelectPrevMap| - - - - *g:CommandTClearMap* - |g:CommandTClearMap| - - *g:CommandTCursorLeftMap* - |g:CommandTCursorLeftMap| - - - *g:CommandTCursorRightMap* - |g:CommandTCursorRightMap| - - - *g:CommandTCursorEndMap* - |g:CommandTCursorEndMap| - - *g:CommandTCursorStartMap* - |g:CommandTCursorStartMap| - -In addition to the options provided by Command-T itself, some of Vim's own -settings can be used to control behavior: - - *command-t-wildignore* - |'wildignore'| string (default: '') - - Vim's |'wildignore'| setting is used to determine which files should be - excluded from listings. This is a comma-separated list of glob patterns. - It defaults to the empty string, but common settings include "*.o,*.obj" - (to exclude object files) or ".git,.svn" (to exclude SCM metadata - directories). For example: - - :set wildignore+=*.o,*.obj,.git - - A pattern such as "vendor/rails/**" would exclude all files and - subdirectories inside the "vendor/rails" directory (relative to - directory Command-T starts in). - - See the |'wildignore'| documentation for more information. - - -AUTHORS *command-t-authors* - -Command-T is written and maintained by Wincent Colaiuta . -Other contributors that have submitted patches include (in alphabetical -order): - - Daniel Hahler - Lucas de Vries - Matthew Todd - Mike Lundy - Scott Bronson - Steven Moazami - Sung Pae - Victor Hugo Borja - Zak Johnson - -As this was the first Vim plug-in I had ever written I was heavily influenced -by the design of the LustyExplorer plug-in by Stephen Bach, which I understand -is one of the largest Ruby-based Vim plug-ins to date. - -While the Command-T codebase doesn't contain any code directly copied from -LustyExplorer, I did use it as a reference for answers to basic questions (like -"How do you do 'X' in a Ruby-based Vim plug-in?"), and also copied some basic -architectural decisions (like the division of the code into Prompt, Settings -and MatchWindow classes). - -LustyExplorer is available from: - - http://www.vim.org/scripts/script.php?script_id=1890 - - -WEBSITE *command-t-website* - -The official website for Command-T is: - - https://wincent.com/products/command-t - -The latest release will always be available from there. - -Development in progress can be inspected via the project's Git repository -browser at: - - https://wincent.com/repos/command-t - -A copy of each release is also available from the official Vim scripts site -at: - - http://www.vim.org/scripts/script.php?script_id=3025 - -Bug reports should be submitted to the issue tracker at: - - https://wincent.com/issues - - -DONATIONS *command-t-donations* - -Command-T itself is free software released under the terms of the BSD license. -If you would like to support further development you can make a donation via -PayPal to win@wincent.com: - - https://wincent.com/products/command-t/donations - - -LICENSE *command-t-license* - -Copyright 2010-2011 Wincent Colaiuta. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - - -HISTORY *command-t-history* - -1.2.1 (30 April 2011) - -- Remove duplicate copy of the documentation that was causing "Duplicate tag" - errors -- Mitigate issue with distracting blinking cursor in non-GUI versions of Vim - (patch from Steven Moazami) - -1.2 (30 April 2011) - -- added |g:CommandTMatchWindowReverse| option, to reverse the order of items - in the match listing (patch from Steven Moazami) - -1.1b2 (26 March 2011) - -- fix a glitch in the release process; the plugin itself is unchanged since - 1.1b - -1.1b (26 March 2011) - -- add |:CommandTBuffer| command for quickly selecting among open buffers - -1.0.1 (5 January 2011) - -- work around bug when mapping |:CommandTFlush|, wherein the default mapping - for |:CommandT| would not be set up -- clean up when leaving the Command-T buffer via unexpected means (such as - with or similar) - -1.0 (26 November 2010) - -- make relative path simplification work on Windows - -1.0b (5 November 2010) - -- work around platform-specific Vim 7.3 bug seen by some users (wherein - Vim always falsely reports to Ruby that the buffer numbers is 0) -- re-use the buffer that is used to show the match listing, rather than - throwing it away and recreating it each time Command-T is shown; this - stops the buffer numbers from creeping up needlessly - -0.9 (8 October 2010) - -- use relative paths when opening files inside the current working directory - in order to keep buffer listings as brief as possible (patch from Matthew - Todd) - -0.8.1 (14 September 2010) - -- fix mapping issues for users who have set |'notimeout'| (patch from Sung - Pae) - -0.8 (19 August 2010) - -- overrides for the default mappings can now be lists of strings, allowing - multiple mappings to be defined for any given action -- t mapping only set up if no other map for |:CommandT| exists - (patch from Scott Bronson) -- prevent folds from appearing in the match listing -- tweaks to avoid the likelihood of "Not enough room" errors when trying to - open files -- watch out for "nil" windows when restoring window dimensions -- optimizations (avoid some repeated downcasing) -- move all Ruby files under the "command-t" subdirectory and avoid polluting - the "Vim" module namespace - -0.8b (11 July 2010) - -- large overhaul of the scoring algorithm to make the ordering of returned - results more intuitive; given the scope of the changes and room for - optimization of the new algorithm, this release is labelled as "beta" - -0.7 (10 June 2010) - -- handle more |'wildignore'| patterns by delegating to Vim's own |expand()| - function; with this change it is now viable to exclude patterns such as - 'vendor/rails/**' in addition to filename-only patterns like '*.o' and - '.git' (patch from Mike Lundy) -- always sort results alphabetically for empty search strings; this eliminates - filesystem-specific variations (patch from Mike Lundy) - -0.6 (28 April 2010) - -- |:CommandT| now accepts an optional parameter to specify the starting - directory, temporarily overriding the usual default of Vim's |:pwd| -- fix truncated paths when operating from root directory - -0.5.1 (11 April 2010) - -- fix for Ruby 1.9 compatibility regression introduced in 0.5 -- documentation enhancements, specifically targetted at Windows users - -0.5 (3 April 2010) - -- |:CommandTFlush| now re-evaluates settings, allowing changes made via |let| - to be picked up without having to restart Vim -- fix premature abort when scanning very deep directory hierarchies -- remove broken || key mapping on vt100 and xterm terminals -- provide settings for overriding default mappings -- minor performance optimization - -0.4 (27 March 2010) - -- add |g:CommandTMatchWindowAtTop| setting (patch from Zak Johnson) -- documentation fixes and enhancements -- internal refactoring and simplification - -0.3 (24 March 2010) - -- add |g:CommandTMaxHeight| setting for controlling the maximum height of the - match window (patch from Lucas de Vries) -- fix bug where |'list'| setting might be inappropriately set after dismissing - Command-T -- compatibility fix for different behaviour of "autoload" under Ruby 1.9.1 -- avoid "highlight group not found" warning when run under a version of Vim - that does not have syntax highlighting support -- open in split when opening normally would fail due to |'hidden'| and - |'modified'| values - -0.2 (23 March 2010) - -- compatibility fixes for compilation under Ruby 1.9 series -- compatibility fixes for compilation under Ruby 1.8.5 -- compatibility fixes for Windows and other non-UNIX platforms -- suppress "mapping already exists" message if t mapping is already - defined when plug-in is loaded -- exclude paths based on |'wildignore'| setting rather than a hardcoded - regular expression - -0.1 (22 March 2010) - -- initial public release - ------------------------------------------------------------------------------- -vim:tw=78:ft=help: diff --git a/vim/tmp/command_t/plugin/command-t.vim b/vim/tmp/command_t/plugin/command-t.vim deleted file mode 100644 index 7ef6bcd..0000000 --- a/vim/tmp/command_t/plugin/command-t.vim +++ /dev/null @@ -1,164 +0,0 @@ -" command-t.vim -" Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -" -" Redistribution and use in source and binary forms, with or without -" modification, are permitted provided that the following conditions are met: -" -" 1. Redistributions of source code must retain the above copyright notice, -" this list of conditions and the following disclaimer. -" 2. Redistributions in binary form must reproduce the above copyright notice, -" this list of conditions and the following disclaimer in the documentation -" and/or other materials provided with the distribution. -" -" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -" POSSIBILITY OF SUCH DAMAGE. - -if exists("g:command_t_loaded") - finish -endif -let g:command_t_loaded = 1 - -command CommandTBuffer call CommandTShowBufferFinder() -command -nargs=? -complete=dir CommandT call CommandTShowFileFinder() -command CommandTFlush call CommandTFlush() - -if !hasmapto(':CommandT') - silent! nmap t :CommandT -endif - -if !hasmapto(':CommandTBuffer') - silent! nmap b :CommandTBuffer -endif - -function s:CommandTRubyWarning() - echohl WarningMsg - echo "command-t.vim requires Vim to be compiled with Ruby support" - echo "For more information type: :help command-t" - echohl none -endfunction - -function s:CommandTShowBufferFinder() - if has('ruby') - ruby $command_t.show_buffer_finder - else - call s:CommandTRubyWarning() - endif -endfunction - -function s:CommandTShowFileFinder(arg) - if has('ruby') - ruby $command_t.show_file_finder - else - call s:CommandTRubyWarning() - endif -endfunction - -function s:CommandTFlush() - if has('ruby') - ruby $command_t.flush - else - call s:CommandTRubyWarning() - endif -endfunction - -if !has('ruby') - finish -endif - -function CommandTHandleKey(arg) - ruby $command_t.handle_key -endfunction - -function CommandTBackspace() - ruby $command_t.backspace -endfunction - -function CommandTDelete() - ruby $command_t.delete -endfunction - -function CommandTAcceptSelection() - ruby $command_t.accept_selection -endfunction - -function CommandTAcceptSelectionTab() - ruby $command_t.accept_selection :command => 'tabe' -endfunction - -function CommandTAcceptSelectionSplit() - ruby $command_t.accept_selection :command => 'sp' -endfunction - -function CommandTAcceptSelectionVSplit() - ruby $command_t.accept_selection :command => 'vs' -endfunction - -function CommandTToggleFocus() - ruby $command_t.toggle_focus -endfunction - -function CommandTCancel() - ruby $command_t.cancel -endfunction - -function CommandTSelectNext() - ruby $command_t.select_next -endfunction - -function CommandTSelectPrev() - ruby $command_t.select_prev -endfunction - -function CommandTClear() - ruby $command_t.clear -endfunction - -function CommandTCursorLeft() - ruby $command_t.cursor_left -endfunction - -function CommandTCursorRight() - ruby $command_t.cursor_right -endfunction - -function CommandTCursorEnd() - ruby $command_t.cursor_end -endfunction - -function CommandTCursorStart() - ruby $command_t.cursor_start -endfunction - -ruby << EOF - # require Ruby files - begin - # prepare controller - require 'command-t/vim' - require 'command-t/controller' - $command_t = CommandT::Controller.new - rescue LoadError - load_path_modified = false - ::VIM::evaluate('&runtimepath').to_s.split(',').each do |path| - lib = "#{path}/ruby" - if !$LOAD_PATH.include?(lib) and File.exist?(lib) - $LOAD_PATH << lib - load_path_modified = true - end - end - retry if load_path_modified - - # could get here if C extension was not compiled, or was compiled - # for the wrong architecture or Ruby version - require 'command-t/stub' - $command_t = CommandT::Stub.new - end -EOF diff --git a/vim/tmp/command_t/ruby/command-t/controller.rb b/vim/tmp/command_t/ruby/command-t/controller.rb deleted file mode 100644 index 29e61b6..0000000 --- a/vim/tmp/command_t/ruby/command-t/controller.rb +++ /dev/null @@ -1,317 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/finder/buffer_finder' -require 'command-t/finder/file_finder' -require 'command-t/match_window' -require 'command-t/prompt' -require 'command-t/vim/path_utilities' - -module CommandT - class Controller - include VIM::PathUtilities - - def initialize - @prompt = Prompt.new - @buffer_finder = CommandT::BufferFinder.new - set_up_file_finder - set_up_max_height - end - - def show_buffer_finder - @path = VIM::pwd - @active_finder = @buffer_finder - show - end - - def show_file_finder - # optional parameter will be desired starting directory, or "" - @path = File.expand_path(::VIM::evaluate('a:arg'), VIM::pwd) - @file_finder.path = @path - @active_finder = @file_finder - show - rescue Errno::ENOENT - # probably a problem with the optional parameter - @match_window.print_no_such_file_or_directory - end - - def hide - @match_window.close - if VIM::Window.select @initial_window - if @initial_buffer.number == 0 - # upstream bug: buffer number misreported as 0 - # see: https://wincent.com/issues/1617 - ::VIM::command "silent b #{@initial_buffer.name}" - else - ::VIM::command "silent b #{@initial_buffer.number}" - end - end - end - - def flush - set_up_max_height - set_up_file_finder - end - - def handle_key - key = ::VIM::evaluate('a:arg').to_i.chr - if @focus == @prompt - @prompt.add! key - list_matches - else - @match_window.find key - end - end - - def backspace - if @focus == @prompt - @prompt.backspace! - list_matches - end - end - - def delete - if @focus == @prompt - @prompt.delete! - list_matches - end - end - - def accept_selection options = {} - selection = @match_window.selection - hide - open_selection(selection, options) unless selection.nil? - end - - def toggle_focus - @focus.unfocus # old focus - @focus = @focus == @prompt ? @match_window : @prompt - @focus.focus # new focus - end - - def cancel - hide - end - - def select_next - @match_window.select_next - end - - def select_prev - @match_window.select_prev - end - - def clear - @prompt.clear! - list_matches - end - - def cursor_left - @prompt.cursor_left if @focus == @prompt - end - - def cursor_right - @prompt.cursor_right if @focus == @prompt - end - - def cursor_end - @prompt.cursor_end if @focus == @prompt - end - - def cursor_start - @prompt.cursor_start if @focus == @prompt - end - - def leave - @match_window.leave - end - - def unload - @match_window.unload - end - - private - - def show - @initial_window = $curwin - @initial_buffer = $curbuf - @match_window = MatchWindow.new \ - :prompt => @prompt, - :match_window_at_top => get_bool('g:CommandTMatchWindowAtTop'), - :match_window_reverse => get_bool('g:CommandTMatchWindowReverse') - @focus = @prompt - @prompt.focus - register_for_key_presses - clear # clears prompt and lists matches - end - - def set_up_max_height - @max_height = get_number('g:CommandTMaxHeight') || 0 - end - - def set_up_file_finder - @file_finder = CommandT::FileFinder.new nil, - :max_files => get_number('g:CommandTMaxFiles'), - :max_depth => get_number('g:CommandTMaxDepth'), - :always_show_dot_files => get_bool('g:CommandTAlwaysShowDotFiles'), - :never_show_dot_files => get_bool('g:CommandTNeverShowDotFiles'), - :scan_dot_directories => get_bool('g:CommandTScanDotDirectories') - end - - def exists? name - ::VIM::evaluate("exists(\"#{name}\")").to_i != 0 - end - - def get_number name - exists?(name) ? ::VIM::evaluate("#{name}").to_i : nil - end - - def get_bool name - exists?(name) ? ::VIM::evaluate("#{name}").to_i != 0 : nil - end - - def get_string name - exists?(name) ? ::VIM::evaluate("#{name}").to_s : nil - end - - # expect a string or a list of strings - def get_list_or_string name - return nil unless exists?(name) - list_or_string = ::VIM::evaluate("#{name}") - if list_or_string.kind_of?(Array) - list_or_string.map { |item| item.to_s } - else - list_or_string.to_s - end - end - - # Backslash-escape space, \, |, %, #, " - def sanitize_path_string str - # for details on escaping command-line mode arguments see: :h : - # (that is, help on ":") in the Vim documentation. - str.gsub(/[ \\|%#"]/, '\\\\\0') - end - - def default_open_command - if !get_bool('&hidden') && get_bool('&modified') - 'sp' - else - 'e' - end - end - - def ensure_appropriate_window_selection - # normally we try to open the selection in the current window, but there - # is one exception: - # - # - we don't touch any "unlisted" buffer with buftype "nofile" (such as - # NERDTree or MiniBufExplorer); this is to avoid things like the "Not - # enough room" error which occurs when trying to open in a split in a - # shallow (potentially 1-line) buffer like MiniBufExplorer is current - # - # Other "unlisted" buffers, such as those with buftype "help" are treated - # normally. - initial = $curwin - while true do - break unless ::VIM::evaluate('&buflisted').to_i == 0 && - ::VIM::evaluate('&buftype').to_s == 'nofile' - ::VIM::command 'wincmd w' # try next window - break if $curwin == initial # have already tried all - end - end - - def open_selection selection, options = {} - command = options[:command] || default_open_command - selection = File.expand_path selection, @path - selection = relative_path_under_working_directory selection - selection = sanitize_path_string selection - ensure_appropriate_window_selection - ::VIM::command "silent #{command} #{selection}" - end - - def map key, function, param = nil - ::VIM::command "noremap #{key} " \ - ":call CommandT#{function}(#{param})" - end - - def xterm? - !!(::VIM::evaluate('&term') =~ /\Axterm/) - end - - def vt100? - !!(::VIM::evaluate('&term') =~ /\Avt100/) - end - - def register_for_key_presses - # "normal" keys (interpreted literally) - numbers = ('0'..'9').to_a.join - lowercase = ('a'..'z').to_a.join - uppercase = lowercase.upcase - punctuation = '<>`@#~!"$%&/()=+*-_.,;:?\\\'{}[] ' # and space - (numbers + lowercase + uppercase + punctuation).each_byte do |b| - map "", 'HandleKey', b - end - - # "special" keys (overridable by settings) - { 'Backspace' => '', - 'Delete' => '', - 'AcceptSelection' => '', - 'AcceptSelectionSplit' => ['', ''], - 'AcceptSelectionTab' => '', - 'AcceptSelectionVSplit' => '', - 'ToggleFocus' => '', - 'Cancel' => ['', ''], - 'SelectNext' => ['', '', ''], - 'SelectPrev' => ['', '', ''], - 'Clear' => '', - 'CursorLeft' => ['', ''], - 'CursorRight' => ['', ''], - 'CursorEnd' => '', - 'CursorStart' => '' }.each do |key, value| - if override = get_list_or_string("g:CommandT#{key}Map") - [override].flatten.each do |mapping| - map mapping, key - end - else - [value].flatten.each do |mapping| - map mapping, key unless mapping == '' && (xterm? || vt100?) - end - end - end - end - - # Returns the desired maximum number of matches, based on available - # vertical space and the g:CommandTMaxHeight option. - def match_limit - limit = VIM::Screen.lines - 5 - limit = 1 if limit < 0 - limit = [limit, @max_height].min if @max_height > 0 - limit - end - - def list_matches - matches = @active_finder.sorted_matches_for @prompt.abbrev, :limit => match_limit - @match_window.matches = matches - end - end # class Controller -end # module commandT diff --git a/vim/tmp/command_t/ruby/command-t/depend b/vim/tmp/command_t/ruby/command-t/depend deleted file mode 100644 index bfa9552..0000000 --- a/vim/tmp/command_t/ruby/command-t/depend +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -CFLAGS += -std=c99 -Wall -Wextra -Wno-unused-parameter diff --git a/vim/tmp/command_t/ruby/command-t/ext.c b/vim/tmp/command_t/ruby/command-t/ext.c deleted file mode 100644 index c5026cc..0000000 --- a/vim/tmp/command_t/ruby/command-t/ext.c +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include "match.h" -#include "matcher.h" - -VALUE mCommandT = 0; // module CommandT -VALUE cCommandTMatch = 0; // class CommandT::Match -VALUE cCommandTMatcher = 0; // class CommandT::Matcher - -VALUE CommandT_option_from_hash(const char *option, VALUE hash) -{ - if (NIL_P(hash)) - return Qnil; - VALUE key = ID2SYM(rb_intern(option)); - if (rb_funcall(hash, rb_intern("has_key?"), 1, key) == Qtrue) - return rb_hash_aref(hash, key); - else - return Qnil; -} - -void Init_ext() -{ - // module CommandT - mCommandT = rb_define_module("CommandT"); - - // class CommandT::Match - cCommandTMatch = rb_define_class_under(mCommandT, "Match", rb_cObject); - - // methods - rb_define_method(cCommandTMatch, "initialize", CommandTMatch_initialize, -1); - rb_define_method(cCommandTMatch, "matches?", CommandTMatch_matches, 0); - rb_define_method(cCommandTMatch, "to_s", CommandTMatch_to_s, 0); - - // attributes - rb_define_attr(cCommandTMatch, "score", Qtrue, Qfalse); // reader: true, writer: false - - // class CommandT::Matcher - cCommandTMatcher = rb_define_class_under(mCommandT, "Matcher", rb_cObject); - - // methods - rb_define_method(cCommandTMatcher, "initialize", CommandTMatcher_initialize, -1); - rb_define_method(cCommandTMatcher, "sorted_matches_for", CommandTMatcher_sorted_matches_for, 2); - rb_define_method(cCommandTMatcher, "matches_for", CommandTMatcher_matches_for, 1); -} diff --git a/vim/tmp/command_t/ruby/command-t/ext.h b/vim/tmp/command_t/ruby/command-t/ext.h deleted file mode 100644 index 89ff076..0000000 --- a/vim/tmp/command_t/ruby/command-t/ext.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -extern VALUE mCommandT; // module CommandT -extern VALUE cCommandTMatch; // class CommandT::Match -extern VALUE cCommandTMatcher; // class CommandT::Matcher - -// Encapsulates common pattern of checking for an option in an optional -// options hash. The hash itself may be nil, but an exception will be -// raised if it is not nil and not a hash. -VALUE CommandT_option_from_hash(const char *option, VALUE hash); - -// Debugging macro. -#define ruby_inspect(obj) rb_funcall(rb_mKernel, rb_intern("p"), 1, obj) diff --git a/vim/tmp/command_t/ruby/command-t/extconf.rb b/vim/tmp/command_t/ruby/command-t/extconf.rb deleted file mode 100644 index 58503b6..0000000 --- a/vim/tmp/command_t/ruby/command-t/extconf.rb +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'mkmf' - -def missing item - puts "couldn't find #{item} (required)" - exit 1 -end - -have_header('ruby.h') or missing('ruby.h') -create_makefile('ext') diff --git a/vim/tmp/command_t/ruby/command-t/finder.rb b/vim/tmp/command_t/ruby/command-t/finder.rb deleted file mode 100644 index a3d0b09..0000000 --- a/vim/tmp/command_t/ruby/command-t/finder.rb +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/ext' # CommandT::Matcher - -module CommandT - # Encapsulates a Scanner instance (which builds up a list of available files - # in a directory) and a Matcher instance (which selects from that list based - # on a search string). - # - # Specialized subclasses use different kinds of scanners adapted for - # different kinds of search (files, buffers). - class Finder - def initialize path = Dir.pwd, options = {} - raise RuntimeError, 'Subclass responsibility' - end - - # Options: - # :limit (integer): limit the number of returned matches - def sorted_matches_for str, options = {} - @matcher.sorted_matches_for str, options - end - - def flush - @scanner.flush - end - - def path= path - @scanner.path = path - end - end # class Finder -end # CommandT diff --git a/vim/tmp/command_t/ruby/command-t/finder/buffer_finder.rb b/vim/tmp/command_t/ruby/command-t/finder/buffer_finder.rb deleted file mode 100644 index 2319c24..0000000 --- a/vim/tmp/command_t/ruby/command-t/finder/buffer_finder.rb +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/ext' # CommandT::Matcher -require 'command-t/scanner/buffer_scanner' -require 'command-t/finder' - -module CommandT - class BufferFinder < Finder - def initialize - @scanner = BufferScanner.new - @matcher = Matcher.new @scanner, :always_show_dot_files => true - end - end # class BufferFinder -end # CommandT diff --git a/vim/tmp/command_t/ruby/command-t/finder/file_finder.rb b/vim/tmp/command_t/ruby/command-t/finder/file_finder.rb deleted file mode 100644 index a9ed231..0000000 --- a/vim/tmp/command_t/ruby/command-t/finder/file_finder.rb +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/ext' # CommandT::Matcher -require 'command-t/finder' -require 'command-t/scanner/file_scanner' - -module CommandT - class FileFinder < Finder - def initialize path = Dir.pwd, options = {} - @scanner = FileScanner.new path, options - @matcher = Matcher.new @scanner, options - end - end # class FileFinder -end # CommandT diff --git a/vim/tmp/command_t/ruby/command-t/match.c b/vim/tmp/command_t/ruby/command-t/match.c deleted file mode 100644 index e32fb0b..0000000 --- a/vim/tmp/command_t/ruby/command-t/match.c +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include "match.h" -#include "ext.h" -#include "ruby_compat.h" - -// use a struct to make passing params during recursion easier -typedef struct -{ - char *str_p; // pointer to string to be searched - long str_len; // length of same - char *abbrev_p; // pointer to search string (abbreviation) - long abbrev_len; // length of same - double max_score_per_char; - int dot_file; // boolean: true if str is a dot-file - int always_show_dot_files; // boolean - int never_show_dot_files; // boolean -} matchinfo_t; - -double recursive_match(matchinfo_t *m, // sharable meta-data - long str_idx, // where in the path string to start - long abbrev_idx, // where in the search string to start - long last_idx, // location of last matched character - double score) // cumulative score so far -{ - double seen_score = 0; // remember best score seen via recursion - int dot_file_match = 0; // true if abbrev matches a dot-file - int dot_search = 0; // true if searching for a dot - - for (long i = abbrev_idx; i < m->abbrev_len; i++) - { - char c = m->abbrev_p[i]; - if (c == '.') - dot_search = 1; - int found = 0; - for (long j = str_idx; j < m->str_len; j++, str_idx++) - { - char d = m->str_p[j]; - if (d == '.') - { - if (j == 0 || m->str_p[j - 1] == '/') - { - m->dot_file = 1; // this is a dot-file - if (dot_search) // and we are searching for a dot - dot_file_match = 1; // so this must be a match - } - } - else if (d >= 'A' && d <= 'Z') - d += 'a' - 'A'; // add 32 to downcase - if (c == d) - { - found = 1; - dot_search = 0; - - // calculate score - double score_for_char = m->max_score_per_char; - long distance = j - last_idx; - if (distance > 1) - { - double factor = 1.0; - char last = m->str_p[j - 1]; - char curr = m->str_p[j]; // case matters, so get again - if (last == '/') - factor = 0.9; - else if (last == '-' || - last == '_' || - last == ' ' || - (last >= '0' && last <= '9')) - factor = 0.8; - else if (last >= 'a' && last <= 'z' && - curr >= 'A' && curr <= 'Z') - factor = 0.8; - else if (last == '.') - factor = 0.7; - else - // if no "special" chars behind char, factor diminishes - // as distance from last matched char increases - factor = (1.0 / distance) * 0.75; - score_for_char *= factor; - } - - if (++j < m->str_len) - { - // bump cursor one char to the right and - // use recursion to try and find a better match - double sub_score = recursive_match(m, j, i, last_idx, score); - if (sub_score > seen_score) - seen_score = sub_score; - } - - score += score_for_char; - last_idx = str_idx++; - break; - } - } - if (!found) - return 0.0; - } - if (m->dot_file) - { - if (m->never_show_dot_files || - (!dot_file_match && !m->always_show_dot_files)) - return 0.0; - } - return (score > seen_score) ? score : seen_score; -} - -// Match.new abbrev, string, options = {} -VALUE CommandTMatch_initialize(int argc, VALUE *argv, VALUE self) -{ - // process arguments: 2 mandatory, 1 optional - VALUE str, abbrev, options; - if (rb_scan_args(argc, argv, "21", &str, &abbrev, &options) == 2) - options = Qnil; - str = StringValue(str); - abbrev = StringValue(abbrev); // already downcased by caller - - // check optional options hash for overrides - VALUE always_show_dot_files = CommandT_option_from_hash("always_show_dot_files", options); - VALUE never_show_dot_files = CommandT_option_from_hash("never_show_dot_files", options); - - matchinfo_t m; - m.str_p = RSTRING_PTR(str); - m.str_len = RSTRING_LEN(str); - m.abbrev_p = RSTRING_PTR(abbrev); - m.abbrev_len = RSTRING_LEN(abbrev); - m.max_score_per_char = (1.0 / m.str_len + 1.0 / m.abbrev_len) / 2; - m.dot_file = 0; - m.always_show_dot_files = always_show_dot_files == Qtrue; - m.never_show_dot_files = never_show_dot_files == Qtrue; - - // calculate score - double score = 1.0; - if (m.abbrev_len == 0) // special case for zero-length search string - { - // filter out dot files - if (!m.always_show_dot_files) - { - for (long i = 0; i < m.str_len; i++) - { - char c = m.str_p[i]; - if (c == '.' && (i == 0 || m.str_p[i - 1] == '/')) - { - score = 0.0; - break; - } - } - } - } - else // normal case - score = recursive_match(&m, 0, 0, 0, 0.0); - - // clean-up and final book-keeping - rb_iv_set(self, "@score", rb_float_new(score)); - rb_iv_set(self, "@str", str); - return Qnil; -} - -VALUE CommandTMatch_matches(VALUE self) -{ - double score = NUM2DBL(rb_iv_get(self, "@score")); - return score > 0 ? Qtrue : Qfalse; -} - -VALUE CommandTMatch_to_s(VALUE self) -{ - return rb_iv_get(self, "@str"); -} diff --git a/vim/tmp/command_t/ruby/command-t/match.h b/vim/tmp/command_t/ruby/command-t/match.h deleted file mode 100644 index c3ce929..0000000 --- a/vim/tmp/command_t/ruby/command-t/match.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -extern VALUE CommandTMatch_initialize(int argc, VALUE *argv, VALUE self); -extern VALUE CommandTMatch_matches(VALUE self); -extern VALUE CommandTMatch_score(VALUE self); -extern VALUE CommandTMatch_to_s(VALUE self); diff --git a/vim/tmp/command_t/ruby/command-t/match_window.rb b/vim/tmp/command_t/ruby/command-t/match_window.rb deleted file mode 100644 index f984287..0000000 --- a/vim/tmp/command_t/ruby/command-t/match_window.rb +++ /dev/null @@ -1,387 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'ostruct' -require 'command-t/settings' - -module CommandT - class MatchWindow - @@selection_marker = '> ' - @@marker_length = @@selection_marker.length - @@unselected_marker = ' ' * @@marker_length - @@buffer = nil - - def initialize options = {} - @prompt = options[:prompt] - @reverse_list = options[:match_window_reverse] - - # save existing window dimensions so we can restore them later - @windows = [] - (0..(::VIM::Window.count - 1)).each do |i| - window = OpenStruct.new :index => i, :height => ::VIM::Window[i].height - @windows << window - end - - # global settings (must manually save and restore) - @settings = Settings.new - ::VIM::set_option 'timeout' # ensure mappings timeout - ::VIM::set_option 'timeoutlen=0' # respond immediately to mappings - ::VIM::set_option 'nohlsearch' # don't highlight search strings - ::VIM::set_option 'noinsertmode' # don't make Insert mode the default - ::VIM::set_option 'noshowcmd' # don't show command info on last line - ::VIM::set_option 'report=9999' # don't show "X lines changed" reports - ::VIM::set_option 'sidescroll=0' # don't sidescroll in jumps - ::VIM::set_option 'sidescrolloff=0' # don't sidescroll automatically - ::VIM::set_option 'noequalalways' # don't auto-balance window sizes - - # show match window - split_location = options[:match_window_at_top] ? 'topleft' : 'botright' - if @@buffer # still have buffer from last time - ::VIM::command "silent! #{split_location} #{@@buffer.number}sbuffer" - raise "Can't re-open GoToFile buffer" unless $curbuf.number == @@buffer.number - $curwin.height = 1 - else # creating match window for first time and set it up - split_command = "silent! #{split_location} 1split GoToFile" - [ - split_command, - 'setlocal bufhidden=unload', # unload buf when no longer displayed - 'setlocal buftype=nofile', # buffer is not related to any file - 'setlocal nomodifiable', # prevent manual edits - 'setlocal noswapfile', # don't create a swapfile - 'setlocal nowrap', # don't soft-wrap - 'setlocal nonumber', # don't show line numbers - 'setlocal nolist', # don't use List mode (visible tabs etc) - 'setlocal foldcolumn=0', # don't show a fold column at side - 'setlocal foldlevel=99', # don't fold anything - 'setlocal nocursorline', # don't highlight line cursor is on - 'setlocal nospell', # spell-checking off - 'setlocal nobuflisted', # don't show up in the buffer list - 'setlocal textwidth=0' # don't hard-wrap (break long lines) - ].each { |command| ::VIM::command command } - - # sanity check: make sure the buffer really was created - raise "Can't find GoToFile buffer" unless $curbuf.name.match /GoToFile\z/ - @@buffer = $curbuf - end - - # syntax coloring - if VIM::has_syntax? - ::VIM::command "syntax match CommandTSelection \"^#{@@selection_marker}.\\+$\"" - ::VIM::command 'syntax match CommandTNoEntries "^-- NO MATCHES --$"' - ::VIM::command 'syntax match CommandTNoEntries "^-- NO SUCH FILE OR DIRECTORY --$"' - ::VIM::command 'highlight link CommandTSelection Visual' - ::VIM::command 'highlight link CommandTNoEntries Error' - ::VIM::evaluate 'clearmatches()' - - # hide cursor - @cursor_highlight = get_cursor_highlight - hide_cursor - end - - # perform cleanup using an autocmd to ensure we don't get caught out - # by some unexpected means of dismissing or leaving the Command-T window - # (eg. , etc) - ::VIM::command 'autocmd! * ' - ::VIM::command 'autocmd BufLeave ruby $command_t.leave' - ::VIM::command 'autocmd BufUnload ruby $command_t.unload' - - @has_focus = false - @selection = nil - @abbrev = '' - @window = $curwin - end - - def close - # Workaround for upstream bug in Vim 7.3 on some platforms - # - # On some platforms, $curbuf.number always returns 0. One workaround is - # to build Vim with --disable-largefile, but as this is producing lots of - # support requests, implement the following fallback to the buffer name - # instead, at least until upstream gets fixed. - # - # For more details, see: https://wincent.com/issues/1617 - if $curbuf.number == 0 - # use bwipeout as bunload fails if passed the name of a hidden buffer - ::VIM::command 'bwipeout! GoToFile' - @@buffer = nil - else - ::VIM::command "bunload! #{@@buffer.number}" - end - end - - def leave - close - unload - end - - def unload - restore_window_dimensions - @settings.restore - @prompt.dispose - show_cursor - end - - def add! char - @abbrev += char - end - - def backspace! - @abbrev.chop! - end - - def select_next - if @selection < @matches.length - 1 - @selection += 1 - print_match(@selection - 1) # redraw old selection (removes marker) - print_match(@selection) # redraw new selection (adds marker) - move_cursor_to_selected_line - else - # (possibly) loop or scroll - end - end - - def select_prev - if @selection > 0 - @selection -= 1 - print_match(@selection + 1) # redraw old selection (removes marker) - print_match(@selection) # redraw new selection (adds marker) - move_cursor_to_selected_line - else - # (possibly) loop or scroll - end - end - - def matches= matches - matches = matches.reverse if @reverse_list - if matches != @matches - @matches = matches - @selection = @reverse_list ? @matches.length - 1 : 0 - print_matches - move_cursor_to_selected_line - end - end - - def focus - unless @has_focus - @has_focus = true - if VIM::has_syntax? - ::VIM::command 'highlight link CommandTSelection Search' - end - end - end - - def unfocus - if @has_focus - @has_focus = false - if VIM::has_syntax? - ::VIM::command 'highlight link CommandTSelection Visual' - end - end - end - - def find char - # is this a new search or the continuation of a previous one? - now = Time.now - if @last_key_time.nil? or @last_key_time < (now - 0.5) - @find_string = char - else - @find_string += char - end - @last_key_time = now - - # see if there's anything up ahead that matches - @matches.each_with_index do |match, idx| - if match[0, @find_string.length].casecmp(@find_string) == 0 - old_selection = @selection - @selection = idx - print_match(old_selection) # redraw old selection (removes marker) - print_match(@selection) # redraw new selection (adds marker) - break - end - end - end - - # Returns the currently selected item as a String. - def selection - @matches[@selection] - end - - def print_no_such_file_or_directory - print_error 'NO SUCH FILE OR DIRECTORY' - end - - private - - def move_cursor_to_selected_line - # on some non-GUI terminals, the cursor doesn't hide properly - # so we move the cursor to prevent it from blinking away in the - # upper-left corner in a distracting fashion - @window.cursor = [@selection + 1, 0] - end - - def print_error msg - return unless VIM::Window.select(@window) - unlock - clear - @window.height = 1 - @@buffer[1] = "-- #{msg} --" - lock - end - - def restore_window_dimensions - # sort from tallest to shortest - @windows.sort! { |a, b| b.height <=> a.height } - - # starting with the tallest ensures that there are no constraints - # preventing windows on the side of vertical splits from regaining - # their original full size - @windows.each do |w| - # beware: window may be nil - window = ::VIM::Window[w.index] - window.height = w.height if window - end - end - - def match_text_for_idx idx - match = truncated_match @matches[idx] - if idx == @selection - prefix = @@selection_marker - suffix = padding_for_selected_match match - else - prefix = @@unselected_marker - suffix = '' - end - prefix + match + suffix - end - - # Print just the specified match. - def print_match idx - return unless VIM::Window.select(@window) - unlock - @@buffer[idx + 1] = match_text_for_idx idx - lock - end - - # Print all matches. - def print_matches - match_count = @matches.length - if match_count == 0 - print_error 'NO MATCHES' - else - return unless VIM::Window.select(@window) - unlock - clear - actual_lines = 1 - @window_width = @window.width # update cached value - max_lines = VIM::Screen.lines - 5 - max_lines = 1 if max_lines < 0 - actual_lines = match_count > max_lines ? max_lines : match_count - @window.height = actual_lines - (1..actual_lines).each do |line| - idx = line - 1 - if @@buffer.count >= line - @@buffer[line] = match_text_for_idx idx - else - @@buffer.append line - 1, match_text_for_idx(idx) - end - end - lock - end - end - - # Prepare padding for match text (trailing spaces) so that selection - # highlighting extends all the way to the right edge of the window. - def padding_for_selected_match str - len = str.length - if len >= @window_width - @@marker_length - '' - else - ' ' * (@window_width - @@marker_length - len) - end - end - - # Convert "really/long/path" into "really...path" based on available - # window width. - def truncated_match str - len = str.length - available_width = @window_width - @@marker_length - return str if len <= available_width - left = (available_width / 2) - 1 - right = (available_width / 2) - 2 + (available_width % 2) - str[0, left] + '...' + str[-right, right] - end - - def clear - # range = % (whole buffer) - # action = d (delete) - # register = _ (black hole register, don't record deleted text) - ::VIM::command 'silent %d _' - end - - def get_cursor_highlight - # as :highlight returns nothing and only prints, - # must redirect its output to a variable - ::VIM::command 'silent redir => g:command_t_cursor_highlight' - - # force 0 verbosity to ensure origin information isn't printed as well - ::VIM::command 'silent! 0verbose highlight Cursor' - ::VIM::command 'silent redir END' - - # there are 3 possible formats to check for, each needing to be - # transformed in a certain way in order to reapply the highlight: - # Cursor xxx guifg=bg guibg=fg -> :hi! Cursor guifg=bg guibg=fg - # Cursor xxx links to SomethingElse -> :hi! link Cursor SomethingElse - # Cursor xxx cleared -> :hi! clear Cursor - highlight = ::VIM::evaluate 'g:command_t_cursor_highlight' - if highlight =~ /^Cursor\s+xxx\s+links to (\w+)/ - "link Cursor #{$~[1]}" - elsif highlight =~ /^Cursor\s+xxx\s+cleared/ - 'clear Cursor' - elsif highlight =~ /Cursor\s+xxx\s+(.+)/ - "Cursor #{$~[1]}" - else # likely cause E411 Cursor highlight group not found - nil - end - end - - def hide_cursor - if @cursor_highlight - ::VIM::command 'highlight Cursor NONE' - end - end - - def show_cursor - if @cursor_highlight - ::VIM::command "highlight #{@cursor_highlight}" - end - end - - def lock - ::VIM::command 'setlocal nomodifiable' - end - - def unlock - ::VIM::command 'setlocal modifiable' - end - end -end diff --git a/vim/tmp/command_t/ruby/command-t/matcher.c b/vim/tmp/command_t/ruby/command-t/matcher.c deleted file mode 100644 index 7cd8a3e..0000000 --- a/vim/tmp/command_t/ruby/command-t/matcher.c +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include /* for qsort() */ -#include /* for strcmp() */ -#include "matcher.h" -#include "ext.h" -#include "ruby_compat.h" - -// comparison function for use with qsort -int comp_alpha(const void *a, const void *b) -{ - VALUE a_val = *(VALUE *)a; - VALUE b_val = *(VALUE *)b; - ID to_s = rb_intern("to_s"); - - VALUE a_str = rb_funcall(a_val, to_s, 0); - VALUE b_str = rb_funcall(b_val, to_s, 0); - char *a_p = RSTRING_PTR(a_str); - long a_len = RSTRING_LEN(a_str); - char *b_p = RSTRING_PTR(b_str); - long b_len = RSTRING_LEN(b_str); - int order = 0; - if (a_len > b_len) - { - order = strncmp(a_p, b_p, b_len); - if (order == 0) - order = 1; // shorter string (b) wins - } - else if (a_len < b_len) - { - order = strncmp(a_p, b_p, a_len); - if (order == 0) - order = -1; // shorter string (a) wins - } - else - order = strncmp(a_p, b_p, a_len); - return order; -} - -// comparison function for use with qsort -int comp_score(const void *a, const void *b) -{ - VALUE a_val = *(VALUE *)a; - VALUE b_val = *(VALUE *)b; - ID score = rb_intern("score"); - double a_score = RFLOAT_VALUE(rb_funcall(a_val, score, 0)); - double b_score = RFLOAT_VALUE(rb_funcall(b_val, score, 0)); - if (a_score > b_score) - return -1; // a scores higher, a should appear sooner - else if (a_score < b_score) - return 1; // b scores higher, a should appear later - else - return comp_alpha(a, b); -} - -VALUE CommandTMatcher_initialize(int argc, VALUE *argv, VALUE self) -{ - // process arguments: 1 mandatory, 1 optional - VALUE scanner, options; - if (rb_scan_args(argc, argv, "11", &scanner, &options) == 1) - options = Qnil; - if (NIL_P(scanner)) - rb_raise(rb_eArgError, "nil scanner"); - rb_iv_set(self, "@scanner", scanner); - - // check optional options hash for overrides - VALUE always_show_dot_files = CommandT_option_from_hash("always_show_dot_files", options); - if (always_show_dot_files != Qtrue) - always_show_dot_files = Qfalse; - VALUE never_show_dot_files = CommandT_option_from_hash("never_show_dot_files", options); - if (never_show_dot_files != Qtrue) - never_show_dot_files = Qfalse; - rb_iv_set(self, "@always_show_dot_files", always_show_dot_files); - rb_iv_set(self, "@never_show_dot_files", never_show_dot_files); - return Qnil; -} - -VALUE CommandTMatcher_sorted_matches_for(VALUE self, VALUE abbrev, VALUE options) -{ - // process optional options hash - VALUE limit_option = CommandT_option_from_hash("limit", options); - - // get unsorted matches - VALUE matches = CommandTMatcher_matches_for(self, abbrev); - - abbrev = StringValue(abbrev); - if (RSTRING_LEN(abbrev) == 0 || - (RSTRING_LEN(abbrev) == 1 && RSTRING_PTR(abbrev)[0] == '.')) - // alphabetic order if search string is only "" or "." - qsort(RARRAY_PTR(matches), RARRAY_LEN(matches), sizeof(VALUE), comp_alpha); - else - // for all other non-empty search strings, sort by score - qsort(RARRAY_PTR(matches), RARRAY_LEN(matches), sizeof(VALUE), comp_score); - - // apply optional limit option - long limit = NIL_P(limit_option) ? 0 : NUM2LONG(limit_option); - if (limit == 0 || RARRAY_LEN(matches) < limit) - limit = RARRAY_LEN(matches); - - // will return an array of strings, not an array of Match objects - for (long i = 0; i < limit; i++) - { - VALUE str = rb_funcall(RARRAY_PTR(matches)[i], rb_intern("to_s"), 0); - RARRAY_PTR(matches)[i] = str; - } - - // trim off any items beyond the limit - if (limit < RARRAY_LEN(matches)) - (void)rb_funcall(matches, rb_intern("slice!"), 2, LONG2NUM(limit), - LONG2NUM(RARRAY_LEN(matches) - limit)); - return matches; -} - -VALUE CommandTMatcher_matches_for(VALUE self, VALUE abbrev) -{ - if (NIL_P(abbrev)) - rb_raise(rb_eArgError, "nil abbrev"); - VALUE matches = rb_ary_new(); - VALUE scanner = rb_iv_get(self, "@scanner"); - VALUE always_show_dot_files = rb_iv_get(self, "@always_show_dot_files"); - VALUE never_show_dot_files = rb_iv_get(self, "@never_show_dot_files"); - VALUE options = Qnil; - if (always_show_dot_files == Qtrue) - { - options = rb_hash_new(); - rb_hash_aset(options, ID2SYM(rb_intern("always_show_dot_files")), always_show_dot_files); - } - else if (never_show_dot_files == Qtrue) - { - options = rb_hash_new(); - rb_hash_aset(options, ID2SYM(rb_intern("never_show_dot_files")), never_show_dot_files); - } - abbrev = rb_funcall(abbrev, rb_intern("downcase"), 0); - VALUE paths = rb_funcall(scanner, rb_intern("paths"), 0); - for (long i = 0, max = RARRAY_LEN(paths); i < max; i++) - { - VALUE path = RARRAY_PTR(paths)[i]; - VALUE match = rb_funcall(cCommandTMatch, rb_intern("new"), 3, path, abbrev, options); - if (rb_funcall(match, rb_intern("matches?"), 0) == Qtrue) - rb_funcall(matches, rb_intern("push"), 1, match); - } - return matches; -} diff --git a/vim/tmp/command_t/ruby/command-t/matcher.h b/vim/tmp/command_t/ruby/command-t/matcher.h deleted file mode 100644 index 6207e37..0000000 --- a/vim/tmp/command_t/ruby/command-t/matcher.h +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -extern VALUE CommandTMatcher_initialize(int argc, VALUE *argv, VALUE self); -extern VALUE CommandTMatcher_sorted_matches_for(VALUE self, VALUE abbrev, VALUE options); - -// most likely the function will be subsumed by the sorted_matcher_for function -extern VALUE CommandTMatcher_matches_for(VALUE self, VALUE abbrev); diff --git a/vim/tmp/command_t/ruby/command-t/prompt.rb b/vim/tmp/command_t/ruby/command-t/prompt.rb deleted file mode 100644 index 743e873..0000000 --- a/vim/tmp/command_t/ruby/command-t/prompt.rb +++ /dev/null @@ -1,165 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - # Abuse the status line as a prompt. - class Prompt - attr_accessor :abbrev - - def initialize - @abbrev = '' # abbreviation entered so far - @col = 0 # cursor position - @has_focus = false - end - - # Erase whatever is displayed in the prompt line, - # effectively disposing of the prompt - def dispose - ::VIM::command 'echo' - ::VIM::command 'redraw' - end - - # Clear any entered text. - def clear! - @abbrev = '' - @col = 0 - redraw - end - - # Insert a character at (before) the current cursor position. - def add! char - left, cursor, right = abbrev_segments - @abbrev = left + char + cursor + right - @col += 1 - redraw - end - - # Delete a character to the left of the current cursor position. - def backspace! - if @col > 0 - left, cursor, right = abbrev_segments - @abbrev = left.chop! + cursor + right - @col -= 1 - redraw - end - end - - # Delete a character at the current cursor position. - def delete! - if @col < @abbrev.length - left, cursor, right = abbrev_segments - @abbrev = left + right - redraw - end - end - - def cursor_left - if @col > 0 - @col -= 1 - redraw - end - end - - def cursor_right - if @col < @abbrev.length - @col += 1 - redraw - end - end - - def cursor_end - if @col < @abbrev.length - @col = @abbrev.length - redraw - end - end - - def cursor_start - if @col != 0 - @col = 0 - redraw - end - end - - def redraw - if @has_focus - prompt_highlight = 'Comment' - normal_highlight = 'None' - cursor_highlight = 'Underlined' - else - prompt_highlight = 'NonText' - normal_highlight = 'NonText' - cursor_highlight = 'NonText' - end - left, cursor, right = abbrev_segments - components = [prompt_highlight, '>>', 'None', ' '] - components += [normal_highlight, left] unless left.empty? - components += [cursor_highlight, cursor] unless cursor.empty? - components += [normal_highlight, right] unless right.empty? - components += [cursor_highlight, ' '] if cursor.empty? - set_status *components - end - - def focus - unless @has_focus - @has_focus = true - redraw - end - end - - def unfocus - if @has_focus - @has_focus = false - redraw - end - end - - private - - # Returns the @abbrev string divided up into three sections, any of - # which may actually be zero width, depending on the location of the - # cursor: - # - left segment (to left of cursor) - # - cursor segment (character at cursor) - # - right segment (to right of cursor) - def abbrev_segments - left = @abbrev[0, @col] - cursor = @abbrev[@col, 1] - right = @abbrev[(@col + 1)..-1] || '' - [left, cursor, right] - end - - def set_status *args - # see ':help :echo' for why forcing a redraw here helps - # prevent the status line from getting inadvertantly cleared - # after our echo commands - ::VIM::command 'redraw' - while (highlight = args.shift) and (text = args.shift) do - text = VIM::escape_for_single_quotes text - ::VIM::command "echohl #{highlight}" - ::VIM::command "echon '#{text}'" - end - ::VIM::command 'echohl None' - end - end # class Prompt -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/ruby_compat.h b/vim/tmp/command_t/ruby/command-t/ruby_compat.h deleted file mode 100644 index e7960a2..0000000 --- a/vim/tmp/command_t/ruby/command-t/ruby_compat.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2010 Wincent Colaiuta. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -#include - -// for compatibility with older versions of Ruby which don't declare RSTRING_PTR -#ifndef RSTRING_PTR -#define RSTRING_PTR(s) (RSTRING(s)->ptr) -#endif - -// for compatibility with older versions of Ruby which don't declare RSTRING_LEN -#ifndef RSTRING_LEN -#define RSTRING_LEN(s) (RSTRING(s)->len) -#endif - -// for compatibility with older versions of Ruby which don't declare RARRAY_PTR -#ifndef RARRAY_PTR -#define RARRAY_PTR(a) (RARRAY(a)->ptr) -#endif - -// for compatibility with older versions of Ruby which don't declare RARRAY_LEN -#ifndef RARRAY_LEN -#define RARRAY_LEN(a) (RARRAY(a)->len) -#endif - -// for compatibility with older versions of Ruby which don't declare RFLOAT_VALUE -#ifndef RFLOAT_VALUE -#define RFLOAT_VALUE(f) (RFLOAT(f)->value) -#endif diff --git a/vim/tmp/command_t/ruby/command-t/scanner.rb b/vim/tmp/command_t/ruby/command-t/scanner.rb deleted file mode 100644 index 5e5e3c9..0000000 --- a/vim/tmp/command_t/ruby/command-t/scanner.rb +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' - -module CommandT - class Scanner; end -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/scanner/buffer_scanner.rb b/vim/tmp/command_t/ruby/command-t/scanner/buffer_scanner.rb deleted file mode 100644 index aa85497..0000000 --- a/vim/tmp/command_t/ruby/command-t/scanner/buffer_scanner.rb +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' -require 'command-t/vim/path_utilities' -require 'command-t/scanner' - -module CommandT - # Returns a list of all open buffers. - class BufferScanner < Scanner - include VIM::PathUtilities - - def paths - (0..(::VIM::Buffer.count - 1)).map do |n| - buffer = ::VIM::Buffer[n] - if buffer.name # beware, may be nil - relative_path_under_working_directory buffer.name - end - end.compact - end - end # class BufferScanner -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/scanner/file_scanner.rb b/vim/tmp/command_t/ruby/command-t/scanner/file_scanner.rb deleted file mode 100644 index 4ea15c8..0000000 --- a/vim/tmp/command_t/ruby/command-t/scanner/file_scanner.rb +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' -require 'command-t/scanner' - -module CommandT - # Reads the current directory recursively for the paths to all regular files. - class FileScanner < Scanner - class FileLimitExceeded < ::RuntimeError; end - - def initialize path = Dir.pwd, options = {} - @path = path - @max_depth = options[:max_depth] || 15 - @max_files = options[:max_files] || 10_000 - @scan_dot_directories = options[:scan_dot_directories] || false - end - - def paths - return @paths unless @paths.nil? - begin - @paths = [] - @depth = 0 - @files = 0 - @prefix_len = @path.chomp('/').length - add_paths_for_directory @path, @paths - rescue FileLimitExceeded - end - @paths - end - - def flush - @paths = nil - end - - def path= str - if @path != str - @path = str - flush - end - end - - private - - def path_excluded? path - # first strip common prefix (@path) from path to match VIM's behavior - path = path[(@prefix_len + 1)..-1] - path = VIM::escape_for_single_quotes path - ::VIM::evaluate("empty(expand(fnameescape('#{path}')))").to_i == 1 - end - - def add_paths_for_directory dir, accumulator - Dir.foreach(dir) do |entry| - next if ['.', '..'].include?(entry) - path = File.join(dir, entry) - unless path_excluded?(path) - if File.file?(path) - @files += 1 - raise FileLimitExceeded if @files > @max_files - accumulator << path[@prefix_len + 1..-1] - elsif File.directory?(path) - next if @depth >= @max_depth - next if (entry.match(/\A\./) && !@scan_dot_directories) - @depth += 1 - add_paths_for_directory path, accumulator - @depth -= 1 - end - end - end - rescue Errno::EACCES - # skip over directories for which we don't have access - end - end # class FileScanner -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/settings.rb b/vim/tmp/command_t/ruby/command-t/settings.rb deleted file mode 100644 index c15016a..0000000 --- a/vim/tmp/command_t/ruby/command-t/settings.rb +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - # Convenience class for saving and restoring global settings. - class Settings - def initialize - save - end - - def save - @timeoutlen = get_number 'timeoutlen' - @report = get_number 'report' - @sidescroll = get_number 'sidescroll' - @sidescrolloff = get_number 'sidescrolloff' - @timeout = get_bool 'timeout' - @equalalways = get_bool 'equalalways' - @hlsearch = get_bool 'hlsearch' - @insertmode = get_bool 'insertmode' - @showcmd = get_bool 'showcmd' - end - - def restore - set_number 'timeoutlen', @timeoutlen - set_number 'report', @report - set_number 'sidescroll', @sidescroll - set_number 'sidescrolloff', @sidescrolloff - set_bool 'timeout', @timeout - set_bool 'equalalways', @equalalways - set_bool 'hlsearch', @hlsearch - set_bool 'insertmode', @insertmode - set_bool 'showcmd', @showcmd - end - - private - - def get_number setting - ::VIM::evaluate("&#{setting}").to_i - end - - def get_bool setting - ::VIM::evaluate("&#{setting}").to_i == 1 - end - - def set_number setting, value - ::VIM::set_option "#{setting}=#{value}" - end - - def set_bool setting, value - if value - ::VIM::set_option setting - else - ::VIM::set_option "no#{setting}" - end - end - end # class Settings -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/stub.rb b/vim/tmp/command_t/ruby/command-t/stub.rb deleted file mode 100644 index 6e8b074..0000000 --- a/vim/tmp/command_t/ruby/command-t/stub.rb +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - class Stub - @@load_error = ['command-t.vim could not load the C extension', - 'Please see INSTALLATION and TROUBLE-SHOOTING in the help', - 'For more information type: :help command-t'] - - def show_file_finder - warn *@@load_error - end - - def flush - warn *@@load_error - end - - private - - def warn *msg - ::VIM::command 'echohl WarningMsg' - msg.each { |m| ::VIM::command "echo '#{m}'" } - ::VIM::command 'echohl none' - end - end # class Stub -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/vim.rb b/vim/tmp/command_t/ruby/command-t/vim.rb deleted file mode 100644 index b4e40fc..0000000 --- a/vim/tmp/command_t/ruby/command-t/vim.rb +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim/screen' -require 'command-t/vim/window' - -module CommandT - module VIM - def self.has_syntax? - ::VIM::evaluate('has("syntax")').to_i != 0 - end - - def self.pwd - ::VIM::evaluate 'getcwd()' - end - - # Escape a string for safe inclusion in a Vim single-quoted string - # (single quotes escaped by doubling, everything else is literal) - def self.escape_for_single_quotes str - str.gsub "'", "''" - end - end # module VIM -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/vim/path_utilities.rb b/vim/tmp/command_t/ruby/command-t/vim/path_utilities.rb deleted file mode 100644 index 8564300..0000000 --- a/vim/tmp/command_t/ruby/command-t/vim/path_utilities.rb +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2010-2011 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -require 'command-t/vim' - -module CommandT - module VIM - module PathUtilities - - private - - def relative_path_under_working_directory path - # any path under the working directory will be specified as a relative - # path to improve the readability of the buffer list etc - pwd = File.expand_path(VIM::pwd) + '/' - path.index(pwd) == 0 ? path[pwd.length..-1] : path - end - end # module PathUtilities - end # module VIM -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/vim/screen.rb b/vim/tmp/command_t/ruby/command-t/vim/screen.rb deleted file mode 100644 index fb7ba33..0000000 --- a/vim/tmp/command_t/ruby/command-t/vim/screen.rb +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - module VIM - module Screen - def self.lines - ::VIM::evaluate('&lines').to_i - end - end # module Screen - end # module VIM -end # module CommandT diff --git a/vim/tmp/command_t/ruby/command-t/vim/window.rb b/vim/tmp/command_t/ruby/command-t/vim/window.rb deleted file mode 100644 index 1e53d56..0000000 --- a/vim/tmp/command_t/ruby/command-t/vim/window.rb +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright 2010 Wincent Colaiuta. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. - -module CommandT - module VIM - class Window - def self.select window - return true if $curwin == window - initial = $curwin - while true do - ::VIM::command 'wincmd w' # cycle through windows - return true if $curwin == window # have selected desired window - return false if $curwin == initial # have already looped through all - end - end - end # class Window - end # module VIM -end # module CommandT diff --git a/vim/tmp/conque/autoload/conque_term.vim b/vim/tmp/conque/autoload/conque_term.vim deleted file mode 100644 index 2780c7d..0000000 --- a/vim/tmp/conque/autoload/conque_term.vim +++ /dev/null @@ -1,1590 +0,0 @@ -" FILE: plugin/conque_term.vim {{{ -" -" AUTHOR: Nico Raffo -" MODIFIED: 2010-05-27 -" VERSION: 1.1, for Vim 7.0 -" LICENSE: -" Conque - pty interaction in Vim -" Copyright (C) 2009-2010 Nico Raffo -" -" MIT License -" -" Permission is hereby granted, free of charge, to any person obtaining a copy -" of this software and associated documentation files (the "Software"), to deal -" in the Software without restriction, including without limitation the rights -" to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -" copies of the Software, and to permit persons to whom the Software is -" furnished to do so, subject to the following conditions: -" -" The above copyright notice and this permission notice shall be included in -" all copies or substantial portions of the Software. -" -" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -" THE SOFTWARE. -" }}} - - -" ********************************************************************************************************** -" **** VIM FUNCTIONS *************************************************************************************** -" ********************************************************************************************************** - -" launch conque -function! conque_term#open(...) "{{{ - let command = get(a:000, 0, '') - let hooks = get(a:000, 1, []) - - " bare minimum validation - if has('python') != 1 - echohl WarningMsg | echomsg "Conque requires the Python interface to be installed" | echohl None - return 0 - endif - if empty(command) - echohl WarningMsg | echomsg "No command found" | echohl None - return 0 - else - let l:cargs = split(command, '\s') - if !executable(l:cargs[0]) - echohl WarningMsg | echomsg "Not an executable: " . l:cargs[0] | echohl None - return 0 - endif - endif - - " set buffer window options - let g:ConqueTerm_BufName = substitute(command, ' ', '\\ ', 'g') . "\\ -\\ " . g:ConqueTerm_Idx - call conque_term#set_buffer_settings(command, hooks) - let b:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx - let g:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx - let g:ConqueTerm_Idx += 1 - - " open command - try - let l:config = '{"color":' . string(g:ConqueTerm_Color) . ',"TERM":"' . g:ConqueTerm_TERM . '"}' - execute 'python ' . b:ConqueTerm_Var . ' = Conque()' - execute "python " . b:ConqueTerm_Var . ".open('" . conque_term#python_escape(command) . "', " . l:config . ")" - catch - echohl WarningMsg | echomsg "Unable to open command: " . command | echohl None - return 0 - endtry - - " set buffer mappings and auto commands - call conque_term#set_mappings('start') - - startinsert! - return 1 -endfunction "}}} - -" set buffer options -function! conque_term#set_buffer_settings(command, pre_hooks) "{{{ - - " optional hooks to execute, e.g. 'split' - for h in a:pre_hooks - sil exe h - endfor - sil exe "edit " . g:ConqueTerm_BufName - - " buffer settings - setlocal nocompatible " conque won't work in compatible mode - setlocal nopaste " conque won't work in paste mode - setlocal buftype=nofile " this buffer is not a file, you can't save it - setlocal nonumber " hide line numbers - setlocal foldcolumn=0 " reasonable left margin - setlocal nowrap " default to no wrap (esp with MySQL) - setlocal noswapfile " don't bother creating a .swp file - setlocal updatetime=50 " trigger cursorhold event after 50ms / XXX - global - setlocal scrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal sidescrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal sidescroll=1 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal foldmethod=manual " don't fold on {{{}}} and stuff - setlocal bufhidden=hide " when buffer is no longer displayed, don't wipe it out - setfiletype conque_term " useful - sil exe "setlocal syntax=" . g:ConqueTerm_Syntax - -endfunction " }}} - -" set key mappings and auto commands -function! conque_term#set_mappings(action) "{{{ - - " set action - if a:action == 'toggle' - if exists('b:conque_on') && b:conque_on == 1 - let l:action = 'stop' - echohl WarningMsg | echomsg "Terminal is paused" | echohl None - else - let l:action = 'start' - echohl WarningMsg | echomsg "Terminal is resumed" | echohl None - endif - else - let l:action = a:action - endif - - " if mappings are being removed, add 'un' - let map_modifier = 'nore' - if l:action == 'stop' - let map_modifier = 'un' - endif - - " remove all auto commands - if l:action == 'stop' - execute 'autocmd! ' . b:ConqueTerm_Var - - else - execute 'augroup ' . b:ConqueTerm_Var - - " handle unexpected closing of shell, passes HUP to parent and all child processes - execute 'autocmd ' . b:ConqueTerm_Var . ' BufUnload python ' . b:ConqueTerm_Var . '.proc.signal(1)' - - " check for resized/scrolled buffer when entering buffer - execute 'autocmd ' . b:ConqueTerm_Var . ' BufEnter python ' . b:ConqueTerm_Var . '.update_window_size()' - execute 'autocmd ' . b:ConqueTerm_Var . ' VimResized python ' . b:ConqueTerm_Var . '.update_window_size()' - - " set/reset updatetime on entering/exiting buffer - autocmd BufEnter set updatetime=50 - autocmd BufLeave set updatetime=2000 - - " check for resized/scrolled buffer when entering insert mode - " XXX - messed up since we enter insert mode at each updatetime - "execute 'autocmd InsertEnter python ' . b:ConqueTerm_Var . '.screen.align()' - - " read more output when this isn't the current buffer - if g:ConqueTerm_ReadUnfocused == 1 - execute 'autocmd ' . b:ConqueTerm_Var . ' CursorHold * call conque_term#read_all()' - endif - - " poll for more output - sil execute 'autocmd ' . b:ConqueTerm_Var . ' CursorHoldI python ' . b:ConqueTerm_Var . '.auto_read()' - endif - - " use F22 key to get more input - if l:action == 'start' - sil exe 'i' . map_modifier . 'map "\\"' - sil exe 'i' . map_modifier . 'map "\\"' - else - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - endif - - " map ASCII 1-31 - for c in range(1, 31) - " - if c == 27 - continue - endif - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(chr(' . c . '))' - else - sil exe 'i' . map_modifier . 'map ' - endif - endfor - if l:action == 'start' - sil exe 'n' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(chr(3))' - else - sil exe 'n' . map_modifier . 'map ' - endif - - " leave insert mode - if !exists('g:ConqueTerm_EscKey') || g:ConqueTerm_EscKey == '' - " use to send to terminal - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(chr(27))' - else - sil exe 'i' . map_modifier . 'map ' - endif - else - " use to send to terminal - if l:action == 'start' - sil exe 'i' . map_modifier . 'map ' . g:ConqueTerm_EscKey . ' ' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(chr(27))' - else - sil exe 'i' . map_modifier . 'map ' . g:ConqueTerm_EscKey - sil exe 'i' . map_modifier . 'map ' - endif - endif - - " Map in insert mode - if exists('g:ConqueTerm_CWInsert') && g:ConqueTerm_CWInsert == 1 - inoremap j j - inoremap k k - inoremap h h - inoremap l l - inoremap w w - endif - - " map ASCII 33-127 - for i in range(33, 127) - " - if i == 124 - if l:action == 'start' - sil exe "i" . map_modifier . "map :python " . b:ConqueTerm_Var . ".write(chr(124))" - else - sil exe "i" . map_modifier . "map " - endif - continue - endif - if l:action == 'start' - sil exe "i" . map_modifier . "map " . nr2char(i) . " :python " . b:ConqueTerm_Var . ".write(chr(" . i . "))" - else - sil exe "i" . map_modifier . "map " . nr2char(i) - endif - endfor - - " map ASCII 128-255 - for i in range(128, 255) - if l:action == 'start' - sil exe "i" . map_modifier . "map " . nr2char(i) . " :python " . b:ConqueTerm_Var . ".write('" . nr2char(i) . "')" - else - sil exe "i" . map_modifier . "map " . nr2char(i) - endif - endfor - - " Special cases - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(u"\u0008")' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(" ")' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(u"\u001b[A")' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(u"\u001b[B")' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(u"\u001b[C")' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . '.write(u"\u001b[D")' - else - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - endif - - " send selected text into conque - if l:action == 'start' - sil exe 'v' . map_modifier . 'map :call conque_term#send_selected(visualmode())' - else - sil exe 'v' . map_modifier . 'map ' - endif - - " remap paste keys - if l:action == 'start' - sil exe 'n' . map_modifier . 'map p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))a' - sil exe 'n' . map_modifier . 'map P :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))a' - sil exe 'n' . map_modifier . 'map ]p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))a' - sil exe 'n' . map_modifier . 'map [p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))a' - else - sil exe 'n' . map_modifier . 'map p' - sil exe 'n' . map_modifier . 'map P' - sil exe 'n' . map_modifier . 'map ]p' - sil exe 'n' . map_modifier . 'map [p' - endif - if has('gui_running') - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :python ' . b:ConqueTerm_Var . ".write(vim.eval('@+'))a" - else - sil exe 'i' . map_modifier . 'map ' - endif - endif - - " disable other normal mode keys which insert text - if l:action == 'start' - sil exe 'n' . map_modifier . 'map r :echo "Replace mode disabled in shell."' - sil exe 'n' . map_modifier . 'map R :echo "Replace mode disabled in shell."' - sil exe 'n' . map_modifier . 'map c :echo "Change mode disabled in shell."' - sil exe 'n' . map_modifier . 'map C :echo "Change mode disabled in shell."' - sil exe 'n' . map_modifier . 'map s :echo "Change mode disabled in shell."' - sil exe 'n' . map_modifier . 'map S :echo "Change mode disabled in shell."' - else - sil exe 'n' . map_modifier . 'map r' - sil exe 'n' . map_modifier . 'map R' - sil exe 'n' . map_modifier . 'map c' - sil exe 'n' . map_modifier . 'map C' - sil exe 'n' . map_modifier . 'map s' - sil exe 'n' . map_modifier . 'map S' - endif - - " set conque as on or off - if l:action == 'start' - let b:conque_on = 1 - else - let b:conque_on = 0 - endif - - " map command to start stop the shell - if a:action == 'start' - nnoremap :call conque_term#set_mappings('toggle') - endif - -endfunction " }}} - - -" send selected text from another buffer -function! conque_term#send_selected(type) "{{{ - let reg_save = @@ - - " save user's sb settings - let sb_save = &switchbuf - set switchbuf=usetab - - " yank current selection - sil exe "normal! `<" . a:type . "`>y" - - " format yanked text - let @@ = substitute(@@, '^[\r\n]*', '', '') - let @@ = substitute(@@, '[\r\n]*$', '', '') - - " execute yanked text - sil exe ":sb " . g:ConqueTerm_BufName - sil exe 'python ' . g:ConqueTerm_Var . '.paste_selection()' - - " reset original values - let @@ = reg_save - sil exe 'set switchbuf=' . sb_save - - " scroll buffer left - startinsert! - normal 0zH -endfunction "}}} - -" read from all known conque buffers -function! conque_term#read_all() "{{{ - " don't run this if we're in a conque buffer - if exists('b:ConqueTerm_Var') - return - endif - - try - for i in range(1, g:ConqueTerm_Idx - 1) - execute 'python ConqueTerm_' . string(i) . '.read(1)' - endfor - catch - " probably a deleted buffer - endtry - - " restart updatetime - call feedkeys("f\e") -endfunction "}}} - -" util function to add enough \s to pass a string to python -function! conque_term#python_escape(input) "{{{ - let l:cleaned = a:input - let l:cleaned = substitute(l:cleaned, '\\', '\\\\', 'g') - let l:cleaned = substitute(l:cleaned, '\n', '\\n', 'g') - let l:cleaned = substitute(l:cleaned, '\r', '\\r', 'g') - let l:cleaned = substitute(l:cleaned, "'", "\\\\'", 'g') - return l:cleaned -endfunction "}}} - -" ********************************************************************************************************** -" **** PYTHON ********************************************************************************************** -" ********************************************************************************************************** - -if has('python') - -python << EOF - -import vim, re, time, math - -# CONFIG CONSTANTS {{{ - -CONQUE_CTL = { - 7:'bel', # bell - 8:'bs', # backspace - 9:'tab', # tab - 10:'nl', # new line - 13:'cr' # carriage return -} -# 11 : 'vt', # vertical tab -# 12 : 'ff', # form feed -# 14 : 'so', # shift out -# 15 : 'si' # shift in - -# Escape sequences -CONQUE_ESCAPE = { - 'm':'font', - 'J':'clear_screen', - 'K':'clear_line', - '@':'add_spaces', - 'A':'cursor_up', - 'B':'cursor_down', - 'C':'cursor_right', - 'D':'cursor_left', - 'G':'cursor_to_column', - 'H':'cursor', - 'P':'delete_chars', - 'f':'cursor', - 'g':'tab_clear', - 'r':'set_coords', - 'h':'set', - 'l':'reset' -} -# 'L':'insert_lines', -# 'M':'delete_lines', -# 'd':'cusor_vpos', - -# Alternate escape sequences, no [ -CONQUE_ESCAPE_PLAIN = { - 'D':'scroll_up', - 'E':'next_line', - 'H':'set_tab', - 'M':'scroll_down' -} -# 'N':'single_shift_2', -# 'O':'single_shift_3', -# '=':'alternate_keypad', -# '>':'numeric_keypad', -# '7':'save_cursor', -# '8':'restore_cursor', - -# Uber alternate escape sequences, with # or ? -CONQUE_ESCAPE_QUESTION = { - '1h':'new_line_mode', - '3h':'132_cols', - '4h':'smooth_scrolling', - '5h':'reverse_video', - '6h':'relative_origin', - '7h':'set_auto_wrap', - '8h':'set_auto_repeat', - '9h':'set_interlacing_mode', - '1l':'set_cursor_key', - '2l':'set_vt52', - '3l':'80_cols', - '4l':'set_jump_scrolling', - '5l':'normal_video', - '6l':'absolute_origin', - '7l':'reset_auto_wrap', - '8l':'reset_auto_repeat', - '9l':'reset_interlacing_mode' -} - -CONQUE_ESCAPE_HASH = { - '8':'screen_alignment_test' -} -# '3':'double_height_top', -# '4':'double_height_bottom', -# '5':'single_height_single_width', -# '6':'single_height_double_width', - -# Font codes {{{ -CONQUE_FONT = { - 0: {'description':'Normal (default)', 'attributes': {'cterm':'NONE','ctermfg':'NONE','ctermbg':'NONE','gui':'NONE','guifg':'NONE','guibg':'NONE'}, 'normal':True}, - 1: {'description':'Bold', 'attributes': {'cterm':'BOLD','gui':'BOLD'}, 'normal':False}, - 4: {'description':'Underlined', 'attributes': {'cterm':'UNDERLINE','gui':'UNDERLINE'}, 'normal':False}, - 5: {'description':'Blink (appears as Bold)', 'attributes': {'cterm':'BOLD','gui':'BOLD'}, 'normal':False}, - 7: {'description':'Inverse', 'attributes': {'cterm':'REVERSE','gui':'REVERSE'}, 'normal':False}, - 8: {'description':'Invisible (hidden)', 'attributes': {'ctermfg':'0','ctermbg':'0','guifg':'#000000','guibg':'#000000'}, 'normal':False}, - 22: {'description':'Normal (neither bold nor faint)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 24: {'description':'Not underlined', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 25: {'description':'Steady (not blinking)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 27: {'description':'Positive (not inverse)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True}, - 28: {'description':'Visible (not hidden)', 'attributes': {'ctermfg':'NONE','ctermbg':'NONE','guifg':'NONE','guibg':'NONE'}, 'normal':True}, - 30: {'description':'Set foreground color to Black', 'attributes': {'ctermfg':'16','guifg':'#000000'}, 'normal':False}, - 31: {'description':'Set foreground color to Red', 'attributes': {'ctermfg':'1','guifg':'#ff0000'}, 'normal':False}, - 32: {'description':'Set foreground color to Green', 'attributes': {'ctermfg':'2','guifg':'#00ff00'}, 'normal':False}, - 33: {'description':'Set foreground color to Yellow', 'attributes': {'ctermfg':'3','guifg':'#ffff00'}, 'normal':False}, - 34: {'description':'Set foreground color to Blue', 'attributes': {'ctermfg':'4','guifg':'#0000ff'}, 'normal':False}, - 35: {'description':'Set foreground color to Magenta', 'attributes': {'ctermfg':'5','guifg':'#990099'}, 'normal':False}, - 36: {'description':'Set foreground color to Cyan', 'attributes': {'ctermfg':'6','guifg':'#009999'}, 'normal':False}, - 37: {'description':'Set foreground color to White', 'attributes': {'ctermfg':'7','guifg':'#ffffff'}, 'normal':False}, - 39: {'description':'Set foreground color to default (original)', 'attributes': {'ctermfg':'NONE','guifg':'NONE'}, 'normal':True}, - 40: {'description':'Set background color to Black', 'attributes': {'ctermbg':'16','guibg':'#000000'}, 'normal':False}, - 41: {'description':'Set background color to Red', 'attributes': {'ctermbg':'1','guibg':'#ff0000'}, 'normal':False}, - 42: {'description':'Set background color to Green', 'attributes': {'ctermbg':'2','guibg':'#00ff00'}, 'normal':False}, - 43: {'description':'Set background color to Yellow', 'attributes': {'ctermbg':'3','guibg':'#ffff00'}, 'normal':False}, - 44: {'description':'Set background color to Blue', 'attributes': {'ctermbg':'4','guibg':'#0000ff'}, 'normal':False}, - 45: {'description':'Set background color to Magenta', 'attributes': {'ctermbg':'5','guibg':'#990099'}, 'normal':False}, - 46: {'description':'Set background color to Cyan', 'attributes': {'ctermbg':'6','guibg':'#009999'}, 'normal':False}, - 47: {'description':'Set background color to White', 'attributes': {'ctermbg':'7','guibg':'#ffffff'}, 'normal':False}, - 49: {'description':'Set background color to default (original).', 'attributes': {'ctermbg':'NONE','guibg':'NONE'}, 'normal':True}, - 90: {'description':'Set foreground color to Black', 'attributes': {'ctermfg':'8','guifg':'#000000'}, 'normal':False}, - 91: {'description':'Set foreground color to Red', 'attributes': {'ctermfg':'9','guifg':'#ff0000'}, 'normal':False}, - 92: {'description':'Set foreground color to Green', 'attributes': {'ctermfg':'10','guifg':'#00ff00'}, 'normal':False}, - 93: {'description':'Set foreground color to Yellow', 'attributes': {'ctermfg':'11','guifg':'#ffff00'}, 'normal':False}, - 94: {'description':'Set foreground color to Blue', 'attributes': {'ctermfg':'12','guifg':'#0000ff'}, 'normal':False}, - 95: {'description':'Set foreground color to Magenta', 'attributes': {'ctermfg':'13','guifg':'#990099'}, 'normal':False}, - 96: {'description':'Set foreground color to Cyan', 'attributes': {'ctermfg':'14','guifg':'#009999'}, 'normal':False}, - 97: {'description':'Set foreground color to White', 'attributes': {'ctermfg':'15','guifg':'#ffffff'}, 'normal':False}, - 100: {'description':'Set background color to Black', 'attributes': {'ctermbg':'8','guibg':'#000000'}, 'normal':False}, - 101: {'description':'Set background color to Red', 'attributes': {'ctermbg':'9','guibg':'#ff0000'}, 'normal':False}, - 102: {'description':'Set background color to Green', 'attributes': {'ctermbg':'10','guibg':'#00ff00'}, 'normal':False}, - 103: {'description':'Set background color to Yellow', 'attributes': {'ctermbg':'11','guibg':'#ffff00'}, 'normal':False}, - 104: {'description':'Set background color to Blue', 'attributes': {'ctermbg':'12','guibg':'#0000ff'}, 'normal':False}, - 105: {'description':'Set background color to Magenta', 'attributes': {'ctermbg':'13','guibg':'#990099'}, 'normal':False}, - 106: {'description':'Set background color to Cyan', 'attributes': {'ctermbg':'14','guibg':'#009999'}, 'normal':False}, - 107: {'description':'Set background color to White', 'attributes': {'ctermbg':'15','guibg':'#ffffff'}, 'normal':False} -} -# }}} - -# regular expression matching (almost) all control sequences -CONQUE_SEQ_REGEX = re.compile(ur"(\u001b\[?\??#?[0-9;]*[a-zA-Z@]|\u001b\][0-9];.*?\u0007|[\u0007-\u000f])", re.UNICODE) -CONQUE_SEQ_REGEX_CTL = re.compile(ur"^[\u0007-\u000f]$", re.UNICODE) -CONQUE_SEQ_REGEX_CSI = re.compile(ur"^\u001b\[", re.UNICODE) -CONQUE_SEQ_REGEX_TITLE = re.compile(ur"^\u001b\]", re.UNICODE) -CONQUE_SEQ_REGEX_HASH = re.compile(ur"^\u001b#", re.UNICODE) -CONQUE_SEQ_REGEX_ESC = re.compile(ur"^\u001b", re.UNICODE) - -# match table output -CONQUE_TABLE_OUTPUT = re.compile("^\s*\|\s.*\s\|\s*$|^\s*\+[=+-]+\+\s*$") - -# }}} - -################################################################################################### -class Conque: - - # CLASS PROPERTIES {{{ - - # screen object - screen = None - - # subprocess object - proc = None - - # terminal dimensions and scrolling region - columns = 80 # same as $COLUMNS - lines = 24 # same as $LINES - working_columns = 80 # can be changed by CSI ? 3 l/h - working_lines = 24 # can be changed by CSI r - - # top/bottom of the scroll region - top = 1 # relative to top of screen - bottom = 24 # relative to top of screen - - # cursor position - l = 1 # current cursor line - c = 1 # current cursor column - - # autowrap mode - autowrap = True - - # absolute coordinate mode - absolute_coords = True - - # tabstop positions - tabstops = [] - - # enable colors - enable_colors = True - - # color changes - color_changes = {} - - # color history - color_history = {} - - # don't wrap table output - unwrap_tables = True - - # wrap CUF/CUB around line breaks - wrap_cursor = False - - # }}} - - # constructor - def __init__(self): # {{{ - self.screen = ConqueScreen() - # }}} - - # start program and initialize this instance - def open(self, command, options): # {{{ - - # int vars - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - # init color - self.enable_colors = options['color'] - - # init tabstops - self.init_tabstops() - - # open command - self.proc = ConqueSubprocess() - self.proc.open(command, { 'TERM' : options['TERM'], 'CONQUE' : '1', 'LINES' : str(self.lines), 'COLUMNS' : str(self.columns)}) - # }}} - - # write to pty - def write(self, input): # {{{ - - - # check if window size has changed - self.update_window_size() - - # write and read - self.proc.write(input) - self.read(1) - # }}} - - # read from pty, and update buffer - def read(self, timeout = 1): # {{{ - # read from subprocess - output = self.proc.read(timeout) - # and strip null chars - output = output.replace(chr(0), '') - - if output == '': - return - - - - - - chunks = CONQUE_SEQ_REGEX.split(output) - - - - - - # don't go through all the csi regex if length is one (no matches) - if len(chunks) == 1: - - self.plain_text(chunks[0]) - - else: - for s in chunks: - if s == '': - continue - - - - - - - # Check for control character match {{{ - if CONQUE_SEQ_REGEX_CTL.match(s[0]): - - nr = ord(s[0]) - if nr in CONQUE_CTL: - getattr(self, 'ctl_' + CONQUE_CTL[nr])() - else: - - pass - # }}} - - # check for escape sequence match {{{ - elif CONQUE_SEQ_REGEX_CSI.match(s): - - if s[-1] in CONQUE_ESCAPE: - csi = self.parse_csi(s[2:]) - - getattr(self, 'csi_' + CONQUE_ESCAPE[s[-1]])(csi) - else: - - pass - # }}} - - # check for title match {{{ - elif CONQUE_SEQ_REGEX_TITLE.match(s): - - self.change_title(s[2], s[4:-1]) - # }}} - - # check for hash match {{{ - elif CONQUE_SEQ_REGEX_HASH.match(s): - - if s[-1] in CONQUE_ESCAPE_HASH: - getattr(self, 'hash_' + CONQUE_ESCAPE_HASH[s[-1]])() - else: - - pass - # }}} - - # check for other escape match {{{ - elif CONQUE_SEQ_REGEX_ESC.match(s): - - if s[-1] in CONQUE_ESCAPE_PLAIN: - getattr(self, 'esc_' + CONQUE_ESCAPE_PLAIN[s[-1]])() - else: - - pass - # }}} - - # else process plain text {{{ - else: - self.plain_text(s) - # }}} - - # set cursor position - self.screen.set_cursor(self.l, self.c) - - vim.command('redraw') - - - # }}} - - # for polling - def auto_read(self): # {{{ - self.read(1) - if self.c == 1: - vim.command('call feedkeys("\", "t")') - else: - vim.command('call feedkeys("\", "t")') - self.screen.set_cursor(self.l, self.c) - # }}} - - ############################################################################################### - # Plain text # {{{ - - def plain_text(self, input): - - current_line = self.screen[self.l] - - if len(current_line) < self.working_columns: - current_line = current_line + ' ' * (self.c - len(current_line)) - - # if line is wider than screen - if self.c + len(input) - 1 > self.working_columns: - # Table formatting hack - if self.unwrap_tables and CONQUE_TABLE_OUTPUT.match(input): - self.screen[self.l] = current_line[ : self.c - 1] + input + current_line[ self.c + len(input) - 1 : ] - self.apply_color(self.c, self.c + len(input)) - self.c += len(input) - return - - diff = self.c + len(input) - self.working_columns - 1 - # if autowrap is enabled - if self.autowrap: - self.screen[self.l] = current_line[ : self.c - 1] + input[ : -1 * diff ] - self.apply_color(self.c, self.working_columns) - self.ctl_nl() - self.ctl_cr() - remaining = input[ -1 * diff : ] - - self.plain_text(remaining) - else: - self.screen[self.l] = current_line[ : self.c - 1] + input[ : -1 * diff - 1 ] + input[-1] - self.apply_color(self.c, self.working_columns) - self.c = self.working_columns - - # no autowrap - else: - self.screen[self.l] = current_line[ : self.c - 1] + input + current_line[ self.c + len(input) - 1 : ] - self.apply_color(self.c, self.c + len(input)) - self.c += len(input) - - def apply_color(self, start, end): - - - # stop here if coloration is disabled - if not self.enable_colors: - return - - real_line = self.screen.get_real_line(self.l) - - # check for previous overlapping coloration - - to_del = [] - if self.color_history.has_key(real_line): - for i in range(len(self.color_history[real_line])): - syn = self.color_history[real_line][i] - - if syn['start'] >= start and syn['start'] < end: - - vim.command('syn clear ' + syn['name']) - to_del.append(i) - # outside - if syn['end'] > end: - - self.exec_highlight(real_line, end, syn['end'], syn['highlight']) - elif syn['end'] > start and syn['end'] <= end: - - vim.command('syn clear ' + syn['name']) - to_del.append(i) - # outside - if syn['start'] < start: - - self.exec_highlight(real_line, syn['start'], start, syn['highlight']) - - if len(to_del) > 0: - to_del.reverse() - for di in to_del: - del self.color_history[real_line][di] - - # if there are no new colors - if len(self.color_changes) == 0: - return - - highlight = '' - for attr in self.color_changes.keys(): - highlight = highlight + ' ' + attr + '=' + self.color_changes[attr] - - # execute the highlight - self.exec_highlight(real_line, start, end, highlight) - - def exec_highlight(self, real_line, start, end, highlight): - unique_key = str(self.proc.pid) - - syntax_name = 'EscapeSequenceAt_' + unique_key + '_' + str(self.l) + '_' + str(start) + '_' + str(len(self.color_history) + 1) - syntax_options = ' contains=ALLBUT,ConqueString,MySQLString,MySQLKeyword oneline' - syntax_region = 'syntax match ' + syntax_name + ' /\%' + str(real_line) + 'l\%>' + str(start - 1) + 'c.*\%<' + str(end + 1) + 'c/' + syntax_options - syntax_highlight = 'highlight ' + syntax_name + highlight - - vim.command(syntax_region) - vim.command(syntax_highlight) - - # add syntax name to history - if not self.color_history.has_key(real_line): - self.color_history[real_line] = [] - - self.color_history[real_line].append({'name':syntax_name, 'start':start, 'end':end, 'highlight':highlight}) - - # }}} - - ############################################################################################### - # Control functions {{{ - - def ctl_nl(self): - # if we're in a scrolling region, scroll instead of moving cursor down - if self.lines != self.working_lines and self.l == self.bottom: - del self.screen[self.top] - self.screen.insert(self.bottom, '') - elif self.l == self.bottom: - self.screen.append('') - else: - self.l += 1 - - self.color_changes = {} - - def ctl_cr(self): - self.c = 1 - - self.color_changes = {} - - def ctl_bs(self): - if self.c > 1: - self.c += -1 - - def ctl_bel(self): - print 'BELL' - - def ctl_tab(self): - # default tabstop location - ts = self.working_columns - - # check set tabstops - for i in range(self.c, len(self.tabstops)): - if self.tabstops[i]: - ts = i + 1 - break - - - - self.c = ts - - # }}} - - ############################################################################################### - # CSI functions {{{ - - def csi_font(self, csi): # {{{ - if not self.enable_colors: - return - - # defaults to 0 - if len(csi['vals']) == 0: - csi['vals'] = [0] - - # 256 xterm color foreground - if len(csi['vals']) == 3 and csi['vals'][0] == 38 and csi['vals'][1] == 5: - self.color_changes['ctermfg'] = str(csi['vals'][2]) - self.color_changes['guifg'] = '#' + self.xterm_to_rgb(csi['vals'][2]) - - # 256 xterm color background - elif len(csi['vals']) == 3 and csi['vals'][0] == 48 and csi['vals'][1] == 5: - self.color_changes['ctermbg'] = str(csi['vals'][2]) - self.color_changes['guibg'] = '#' + self.xterm_to_rgb(csi['vals'][2]) - - # 16 colors - else: - for val in csi['vals']: - if CONQUE_FONT.has_key(val): - - # ignore starting normal colors - if CONQUE_FONT[val]['normal'] and len(self.color_changes) == 0: - - continue - # clear color changes - elif CONQUE_FONT[val]['normal']: - - self.color_changes = {} - # save these color attributes for next plain_text() call - else: - - for attr in CONQUE_FONT[val]['attributes'].keys(): - if self.color_changes.has_key(attr) and (attr == 'cterm' or attr == 'gui'): - self.color_changes[attr] += ',' + CONQUE_FONT[val]['attributes'][attr] - else: - self.color_changes[attr] = CONQUE_FONT[val]['attributes'][attr] - # }}} - - def csi_clear_line(self, csi): # {{{ - - - # this escape defaults to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - - - - # 0 means cursor right - if csi['val'] == 0: - self.screen[self.l] = self.screen[self.l][0 : self.c - 1] - - # 1 means cursor left - elif csi['val'] == 1: - self.screen[self.l] = ' ' * (self.c) + self.screen[self.l][self.c : ] - - # clear entire line - elif csi['val'] == 2: - self.screen[self.l] = '' - - # clear colors - if csi['val'] == 2 or (csi['val'] == 0 and self.c == 1): - real_line = self.screen.get_real_line(self.l) - if self.color_history.has_key(real_line): - for syn in self.color_history[real_line]: - vim.command('syn clear ' + syn['name']) - - - - # }}} - - def csi_cursor_right(self, csi): # {{{ - # we use 1 even if escape explicitly specifies 0 - if csi['val'] == 0: - csi['val'] = 1 - - - - - if self.wrap_cursor and self.c + csi['val'] > self.working_columns: - self.l += int(math.floor( (self.c + csi['val']) / self.working_columns )) - self.c = (self.c + csi['val']) % self.working_columns - return - - self.c = self.bound(self.c + csi['val'], 1, self.working_columns) - # }}} - - def csi_cursor_left(self, csi): # {{{ - # we use 1 even if escape explicitly specifies 0 - if csi['val'] == 0: - csi['val'] = 1 - - if self.wrap_cursor and csi['val'] >= self.c: - self.l += int(math.floor( (self.c - csi['val']) / self.working_columns )) - self.c = self.working_columns - (csi['val'] - self.c) % self.working_columns - return - - self.c = self.bound(self.c - csi['val'], 1, self.working_columns) - # }}} - - def csi_cursor_to_column(self, csi): # {{{ - self.c = self.bound(csi['val'], 1, self.working_columns) - # }}} - - def csi_cursor_up(self, csi): # {{{ - self.l = self.bound(self.l - csi['val'], self.top, self.bottom) - - self.color_changes = {} - # }}} - - def csi_cursor_down(self, csi): # {{{ - self.l = self.bound(self.l + csi['val'], self.top, self.bottom) - - self.color_changes = {} - # }}} - - def csi_clear_screen(self, csi): # {{{ - # default to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - # 2 == clear entire screen - if csi['val'] == 2: - self.l = 1 - self.c = 1 - self.screen.clear() - - # 0 == clear down - elif csi['val'] == 0: - for l in range(self.bound(self.l + 1, 1, self.lines), self.lines + 1): - self.screen[l] = '' - - # clear end of current line - self.csi_clear_line(self.parse_csi('K')) - - # 1 == clear up - elif csi['val'] == 1: - for l in range(1, self.bound(self.l, 1, self.lines + 1)): - self.screen[l] = '' - - # clear beginning of current line - self.csi_clear_line(self.parse_csi('1K')) - - # clear coloration - if csi['val'] == 2 or csi['val'] == 0: - real_line = self.screen.get_real_line(self.l) - for line in self.color_history.keys(): - if line >= real_line: - for syn in self.color_history[line]: - vim.command('syn clear ' + syn['name']) - - self.color_changes = {} - # }}} - - def csi_delete_chars(self, csi): # {{{ - self.screen[self.l] = self.screen[self.l][ : self.c ] + self.screen[self.l][ self.c + csi['val'] : ] - # }}} - - def csi_add_spaces(self, csi): # {{{ - self.screen[self.l] = self.screen[self.l][ : self.c - 1] + ' ' * csi['val'] + self.screen[self.l][self.c : ] - # }}} - - def csi_cursor(self, csi): # {{{ - if len(csi['vals']) == 2: - new_line = csi['vals'][0] - new_col = csi['vals'][1] - else: - new_line = 1 - new_col = 1 - - if self.absolute_coords: - self.l = self.bound(new_line, 1, self.lines) - else: - self.l = self.bound(self.top + new_line - 1, self.top, self.bottom) - - self.c = self.bound(new_col, 1, self.working_columns) - if self.c > len(self.screen[self.l]): - self.screen[self.l] = self.screen[self.l] + ' ' * (self.c - len(self.screen[self.l])) - - # }}} - - def csi_set_coords(self, csi): # {{{ - if len(csi['vals']) == 2: - new_start = csi['vals'][0] - new_end = csi['vals'][1] - else: - new_start = 1 - new_end = vim.current.window.height - - self.top = new_start - self.bottom = new_end - self.working_lines = new_end - new_start + 1 - - # if cursor is outside scrolling region, reset it - if self.l < self.top: - self.l = self.top - elif self.l > self.bottom: - self.l = self.bottom - - self.color_changes = {} - # }}} - - def csi_tab_clear(self, csi): # {{{ - # this escape defaults to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - - - if csi['val'] == 0: - self.tabstops[self.c - 1] = False - elif csi['val'] == 3: - for i in range(0, self.columns + 1): - self.tabstops[i] = False - # }}} - - def csi_set(self, csi): # {{{ - # 132 cols - if csi['val'] == 3: - self.csi_clear_screen(self.parse_csi('2J')) - self.working_columns = 132 - - # relative_origin - elif csi['val'] == 6: - self.absolute_coords = False - - # set auto wrap - elif csi['val'] == 7: - self.autowrap = True - - - self.color_changes = {} - # }}} - - def csi_reset(self, csi): # {{{ - # 80 cols - if csi['val'] == 3: - self.csi_clear_screen(self.parse_csi('2J')) - self.working_columns = 80 - - # absolute origin - elif csi['val'] == 6: - self.absolute_coords = True - - # reset auto wrap - elif csi['val'] == 7: - self.autowrap = False - - - self.color_changes = {} - # }}} - - # }}} - - ############################################################################################### - # ESC functions {{{ - - def esc_scroll_up(self): # {{{ - self.ctl_nl() - - self.color_changes = {} - # }}} - - def esc_next_line(self): # {{{ - self.ctl_nl() - self.c = 1 - # }}} - - def esc_set_tab(self): # {{{ - - if self.c <= len(self.tabstops): - self.tabstops[self.c - 1] = True - # }}} - - def esc_scroll_down(self): # {{{ - if self.l == self.top: - del self.screen[self.bottom] - self.screen.insert(self.top, '') - else: - self.l += -1 - - self.color_changes = {} - # }}} - - # }}} - - ############################################################################################### - # HASH functions {{{ - - def hash_screen_alignment_test(self): # {{{ - self.csi_clear_screen(self.parse_csi('2J')) - self.working_lines = self.lines - for l in range(1, self.lines + 1): - self.screen[l] = 'E' * self.working_columns - # }}} - - # }}} - - ############################################################################################### - # Random stuff {{{ - - def change_title(self, key, val): - - - if key == '0' or key == '2': - - vim.command('setlocal statusline=' + re.escape(val)) - - def paste(self): - self.write(vim.eval('@@')) - self.read(50) - - def paste_selection(self): - self.write(vim.eval('@@')) - - def update_window_size(self): - # resize if needed - if vim.current.window.width != self.columns or vim.current.window.height != self.lines: - - # reset all window size attributes to default - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - # reset screen object attributes - self.l = self.screen.reset_size(self.l) - - # reset tabstops - self.init_tabstops() - - - - # signal process that screen size has changed - self.proc.window_resize(self.lines, self.columns) - - def init_tabstops(self): - for i in range(0, self.columns + 1): - if i % 8 == 0: - self.tabstops.append(True) - else: - self.tabstops.append(False) - - # }}} - - ############################################################################################### - # Utility {{{ - - def parse_csi(self, s): # {{{ - attr = { 'key' : s[-1], 'flag' : '', 'val' : 1, 'vals' : [] } - - if len(s) == 1: - return attr - - full = s[0:-1] - - if full[0] == '?': - full = full[1:] - attr['flag'] = '?' - - if full != '': - vals = full.split(';') - for val in vals: - - val = re.sub("\D", "", val) - - if val != '': - attr['vals'].append(int(val)) - - if len(attr['vals']) == 1: - attr['val'] = int(attr['vals'][0]) - - return attr - # }}} - - def bound(self, val, min, max): # {{{ - if val > max: - return max - - if val < min: - return min - - return val - # }}} - - def xterm_to_rgb(self, color_code): # {{{ - if color_code < 16: - ascii_colors = ['000000', 'CD0000', '00CD00', 'CDCD00', '0000EE', 'CD00CD', '00CDCD', 'E5E5E5', - '7F7F7F', 'FF0000', '00FF00', 'FFFF00', '5C5CFF', 'FF00FF', '00FFFF', 'FFFFFF'] - return ascii_colors[color_code] - - elif color_code < 232: - cc = int(color_code) - 16 - - p1 = "%02x" % (math.floor(cc / 36) * (255/5)) - p2 = "%02x" % (math.floor((cc % 36) / 6) * (255/5)) - p3 = "%02x" % (math.floor(cc % 6) * (255/5)) - - return p1 + p2 + p3 - else: - grey_tone = "%02x" % math.floor((255/24) * (color_code - 232)) - return grey_tone + grey_tone + grey_tone - # }}} - - # }}} - - -import os, signal, pty, tty, select, fcntl, termios, struct - -################################################################################################### -class ConqueSubprocess: - - # process id - pid = 0 - - # stdout+stderr file descriptor - fd = None - - # constructor - def __init__(self): # {{{ - self.pid = 0 - # }}} - - # create the pty or whatever (whatever == windows) - def open(self, command, env = {}): # {{{ - command_arr = command.split() - executable = command_arr[0] - args = command_arr - - try: - self.pid, self.fd = pty.fork() - - except: - pass - - - # child proc, replace with command after altering terminal attributes - if self.pid == 0: - - # set requested environment variables - for k in env.keys(): - os.environ[k] = env[k] - - # set some attributes - try: - attrs = tty.tcgetattr(1) - attrs[0] = attrs[0] ^ tty.IGNBRK - attrs[0] = attrs[0] | tty.BRKINT | tty.IXANY | tty.IMAXBEL - attrs[2] = attrs[2] | tty.HUPCL - attrs[3] = attrs[3] | tty.ICANON | tty.ECHO | tty.ISIG | tty.ECHOKE - attrs[6][tty.VMIN] = 1 - attrs[6][tty.VTIME] = 0 - tty.tcsetattr(1, tty.TCSANOW, attrs) - except: - pass - - os.execvp(executable, args) - - # else master, do nothing - else: - pass - - # }}} - - # read from pty - # XXX - select.poll() doesn't work in OS X!!!!!!! - def read(self, timeout = 1): # {{{ - - output = '' - read_timeout = float(timeout) / 1000 - - try: - # what, no do/while? - while 1: - s_read, s_write, s_error = select.select( [ self.fd ], [], [], read_timeout) - - lines = '' - for s_fd in s_read: - try: - lines = os.read( self.fd, 32 ) - except: - pass - output = output + lines - - if lines == '': - break - except: - pass - - return output - # }}} - - # I guess this one's not bad - def write(self, input): # {{{ - try: - os.write(self.fd, input) - except: - pass - # }}} - - # signal process - def signal(self, signum): # {{{ - try: - os.kill(self.pid, signum) - except: - pass - # }}} - - # get process status - def get_status(self): #{{{ - - p_status = True - - try: - if os.waitpid( self.pid, os.WNOHANG )[0]: - p_status = False - except: - p_status = False - - return p_status - - # }}} - - # update window size in kernel, then send SIGWINCH to fg process - def window_resize(self, lines, columns): # {{{ - try: - fcntl.ioctl(self.fd, termios.TIOCSWINSZ, struct.pack("HHHH", lines, columns, 0, 0)) - os.kill(self.pid, signal.SIGWINCH) - except: - pass - - # }}} - - -################################################################################################### -# ConqueScreen is an extention of the vim.current.buffer object -# It restricts the working indices of the buffer object to the scroll region which pty is expecting -# It also uses 1-based indexes, to match escape sequence commands -# -# E.g.: -# s = ConqueScreen() -# ... -# s[5] = 'Set 5th line in terminal to this line' -# s.append('Add new line to terminal') -# s[5] = 'Since previous append() command scrolled the terminal down, this is a different line than first cb[5] call' -# - -import vim - -class ConqueScreen(object): - - # CLASS PROPERTIES {{{ - - # the buffer - buffer = None - - # screen and scrolling regions - screen_top = 1 - - # screen width - screen_width = 80 - screen_height = 80 - - # }}} - - def __init__(self): # {{{ - self.buffer = vim.current.buffer - - self.screen_top = 1 - self.screen_width = vim.current.window.width - self.screen_height = vim.current.window.height - # }}} - - ############################################################################################### - # List overload {{{ - def __len__(self): # {{{ - return len(self.buffer) - # }}} - - def __getitem__(self, key): # {{{ - real_line = self.get_real_idx(key) - - # if line is past buffer end, add lines to buffer - if real_line >= len(self.buffer): - for i in range(len(self.buffer), real_line + 1): - self.append(' ' * self.screen_width) - - return self.buffer[ real_line ] - # }}} - - def __setitem__(self, key, value): # {{{ - real_line = self.get_real_idx(key) - - # if line is past end of screen, append - if real_line == len(self.buffer): - self.buffer.append(value) - else: - self.buffer[ real_line ] = value - # }}} - - def __delitem__(self, key): # {{{ - del self.buffer[ self.screen_top + key - 2 ] - # }}} - - def append(self, value): # {{{ - if len(self.buffer) > self.screen_top + self.screen_height - 1: - self.buffer[len(self.buffer) - 1] = value - else: - self.buffer.append(value) - - if len(self.buffer) > self.screen_top + self.screen_height - 1: - self.screen_top += 1 - if vim.current.buffer.number == self.buffer.number: - vim.command('normal G') - # }}} - - def insert(self, line, value): # {{{ - - l = self.screen_top + line - 2 - self.buffer[l:l] = [ value ] - - # }}} - # }}} - - ############################################################################################### - # Util {{{ - def get_top(self): # {{{ - return self.screen_top - # }}} - - def get_real_idx(self, line): # {{{ - return (self.screen_top + line - 2) - # }}} - - def get_real_line(self, line): # {{{ - return (self.screen_top + line - 1) - # }}} - - def set_screen_width(self, width): # {{{ - self.screen_width = width - # }}} - - # }}} - - ############################################################################################### - def clear(self): # {{{ - self.buffer.append(' ') - vim.command('normal Gzt') - self.screen_top = len(self.buffer) - # }}} - - def set_cursor(self, line, column): # {{{ - # figure out line - real_line = self.screen_top + line - 1 - if real_line > len(self.buffer): - for l in range(len(self.buffer) - 1, real_line): - self.buffer.append('') - - # figure out column - real_column = column - if len(self.buffer[real_line - 1]) < real_column: - self.buffer[real_line - 1] = self.buffer[real_line - 1] + ' ' * (real_column - len(self.buffer[real_line - 1])) - - # python version is occasionally grumpy - try: - vim.current.window.cursor = (real_line, real_column - 1) - except: - vim.command('call cursor(' + str(real_line) + ', ' + str(real_column) + ')') - # }}} - - def reset_size(self, line): # {{{ - - - - - # save cursor line number - real_line = self.screen_top + line - - # reset screen size - self.screen_width = vim.current.window.width - self.screen_height = vim.current.window.height - self.screen_top = len(self.buffer) - vim.current.window.height + 1 - if self.screen_top < 1: - self.screen_top = 1 - - - # align bottom of buffer to bottom of screen - vim.command('normal ' + str(self.screen_height) + 'kG') - - # return new relative line number - return (real_line - self.screen_top) - # }}} - - def scroll_to_bottom(self): # {{{ - vim.current.window.cursor = (len(self.buffer) - 1, 1) - # }}} - - def align(self): # {{{ - # align bottom of buffer to bottom of screen - vim.command('normal ' + str(self.screen_height) + 'kG') - # }}} - - -EOF - -endif - diff --git a/vim/tmp/conque/doc/conque_term.txt b/vim/tmp/conque/doc/conque_term.txt deleted file mode 100644 index ff8ca54..0000000 --- a/vim/tmp/conque/doc/conque_term.txt +++ /dev/null @@ -1,156 +0,0 @@ -*ConqueTerm* Plugin to run a shell in a buffer - -The ConqueTerm plugin will convert a buffer into a terminal emulator, allowing -you to run a shell or shell application in the buffer. - - *conque_term-usage* - -Type :ConqueTerm to launch an application in the current buffer. E.g. - - :ConqueTerm bash - :ConqueTerm mysql -h localhost -u joe_lunchbox Menu - :ConqueTerm man top - -Use :ConqueTermSplit or :ConqueTermVSplit to open Conque in a new horizontal -or vertical buffer. - -Keys pressed in insert mode will be sent to the shell, along with output from -the 'p' command in normal mode. - -Press the key twice to send a single to the shell. Pressing this -key once will leave insert mode like normal. - -Press in any buffer to send a visual selection to the shell. - - - *conque_term-settings* - -Set the following in your .vimrc (default values shown) - -" Enable colors. Setting this to 0 will make your terminal faster. -let g:ConqueTerm_Color = 1 - -" Set your terminal type. I strong recommend leaving this as vt100, -" however more features may be enabled with xterm. -let g:ConqueTerm_TERM = 'vt100' - -" Set buffer syntax. Conque has highlighting for MySQL, but not much else. -let g:ConqueTerm_Syntax = 'conque' - -" Continue updating shell when it's not the current, focused buffer -let g:ConqueTerm_ReadUnfocused = 1 - - - *conque_term-requirements* - -The following minimum requirements are needed to run Conque. Conque will not -run on Windows without a Cygwin-like environment. - - - Vim 7.1 - - Python 2.3 - - Supported operating systems: *nix, Mac, or Cygwin - -Tested on: - - Vim 7.2 / Python 2.6 / Ubuntu 9.10 (Gnome & GTK) - - Vim 7.2 / Python 2.6 / FreeBSD 8.0 (GTK) - - Vim 7.1 / Python 2.6 / FreeBSD 8.0 (GTK) - x Vim 7.0 / Python 2.6 / FreeBSD 8.0 (GTK) - * feedkeys() doesn't restart updatetime - - Vim 7.2 / Python 2.4 / OpenSolaris 2009.06 (Gnome) - - Vim 7.2 / Python 2.4 / CentOS 5.3 (no GUI) - - Vim 7.1 / Python 2.3 / RHEL 4 (no GUI) - - Vim 7.2 / Python 2.5 / Cygwin (Windows Vista 64b) - - MacVim 7.2 / Python 2.3 / OS X 10.6.2 - - *conque_term-bugs* - -The following are known limitations: - - - Font/color highlighting is imperfect and slow. If you don't care about - color in your shell, set g:ConqueTerm_Color = 0 in your .vimrc - - Conque only supports the extended ASCII character set for input, not utf-8. - - VT100 escape sequence support is not complete. - - Alt/Meta key support in Vim isn't great in general, and conque is no - exception. Pressing x or instead of works in - most cases. - - *conque_term-todo* - - - Fix pasting from named registers - - Polling unfucused conque buffers (Top explodes when window resizes) - - Enable graphics character set - - Consider supporting xterm escapes - - Improve color logic - - Find a solution to UTF-8 input (See InsertCharPre in Vim todo.txt) - - Find an alternative to updatetime polling (See Vim todo.txt) - - Find a graceful solution to Meta key input - - Windows support - (See PyConsole http://www.vim.org/scripts/script.php?script_id=1974) - - Always: look for performance improvements - - - *conque_term-contribute* - -The two contributions most in need are improvements to Vim itself. I currently -use hacks to simulate a key press event and repeating CursorHold event. The -Vim todo.txt document lists proposed improvements to give users this behavior -without hacks. Having a key press event should allow Conque to work with multi- -byte input. If you are a Vim developer, please consider prioritizing these two -items: - - - todo.txt (Autocommands, line ~3137) - 8 Add an event like CursorHold that is triggered repeatedly, not just - once after typing something. - - - todo.txt (Autocommands, proposed event list, line ~3189) - InsertCharPre - user typed character Insert mode, before inserting the - char. Pattern is matched with text before the cursor. Set v:char to the - character, can be changed. (not triggered when 'paste' is set). - -Bugs, suggestions and patches are all welcome. - -For more information visit http://conque.googlecode.com - -Check out the latest from svn at http://conque.googlecode.com/svn/trunk/ - - *conque_term-changelog* - - - 1.0 / 2010-02- - * Complete python rewrite - * Add support for ncurses based applications - * Add continuous polling, instead of using - * Improve speed - * Improve syntax highlighting - - - 0.6 / 2009-12-18 - * Fix GVim errors with non-english locale - * No functional changes - - - 0.5 / 2009-12-02 - * Various performance enhancements and bugfixes. - * Rewritten escape sequence processing - - - 0.4 / 2009-10-30 - * Improved history and tab completion - * Fix escape sequence formatting and improve highlighting - * Send selected text to shell from any buffer - * Add special handling of "vi" and "man" commands - * Improve error handling - * Add key mappings for - * Various bugfixes - - - 0.3 / 2009-10-13 - * Apply escape sequence coloring to output, e.g. ls --color - * Clean up syntax files for portability - * Fix several Vim 7.1 bugs - * Bugfixes for multiple shell buffers - * Add experimental shell folding option - - - 0.2 / 2009-10-01 - * Rewritten subprocess management module in python instead of c - * Added support for OS X, partial support for Windows - * Improved tab completion - - - 0.1 / 2009-09-03 - * Initial release - diff --git a/vim/tmp/conque/plugin/conque_term.vim b/vim/tmp/conque/plugin/conque_term.vim deleted file mode 100644 index 07f96e0..0000000 --- a/vim/tmp/conque/plugin/conque_term.vim +++ /dev/null @@ -1,93 +0,0 @@ -" FILE: plugin/conque_term.vim {{{ -" AUTHOR: Nico Raffo -" MODIFIED: 2010-05-27 -" VERSION: 1.1, for Vim 7.0 -" LICENSE: -" Conque - pty interaction in Vim -" Copyright (C) 2009-2010 Nico Raffo -" -" MIT License -" -" Permission is hereby granted, free of charge, to any person obtaining a copy -" of this software and associated documentation files (the "Software"), to deal -" in the Software without restriction, including without limitation the rights -" to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -" copies of the Software, and to permit persons to whom the Software is -" furnished to do so, subject to the following conditions: -" -" The above copyright notice and this permission notice shall be included in -" all copies or substantial portions of the Software. -" -" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -" THE SOFTWARE. -" }}} - -" See docs/conque_term.txt for help or type :help conque_term - -if exists('g:ConqueTerm_Loaded') || v:version < 700 - finish -endif - -" ********************************************************************************************************** -" **** CONFIG ********************************************************************************************** -" ********************************************************************************************************** - -" Choose key mapping to leave insert mode {{{ -" If you choose something other than '', then will be sent to terminal -" Using a different key will usually fix Alt/Meta key issues -if !exists('g:ConqueTerm_EscKey') - let g:ConqueTerm_EscKey = '' -endif " }}} - -" Enable color. {{{ -" If your apps use a lot of color it will slow down the shell. -if !exists('g:ConqueTerm_Color') - let g:ConqueTerm_Color = 1 -endif " }}} - -" TERM environment setting {{{ -if !exists('g:ConqueTerm_TERM') - let g:ConqueTerm_TERM = 'vt100' -endif " }}} - -" Syntax for your buffer {{{ -if !exists('g:ConqueTerm_Syntax') - let g:ConqueTerm_Syntax = 'conque_term' -endif " }}} - -" Keep on updating the shell window after you've switched to another buffer {{{ -if !exists('g:ConqueTerm_ReadUnfocused') - let g:ConqueTerm_ReadUnfocused = 0 -endif " }}} - -" Use this regular expression to highlight prompt {{{ -if !exists('g:ConqueTerm_PromptRegex') - let g:ConqueTerm_PromptRegex = '^\w\+@[0-9A-Za-z_.-]\+:[0-9A-Za-z_./\~,:-]\+\$' -endif " }}} - -" Allow user to use keys to switch window in insert mode. {{{ -if !exists('g:ConqueTerm_CWInsert') - let g:ConqueTerm_CWInsert = 0 -endif " }}} - -" ********************************************************************************************************** -" **** Startup ********************************************************************************************* -" ********************************************************************************************************** - -" Startup {{{ - -let g:ConqueTerm_Loaded = 1 -let g:ConqueTerm_Idx = 1 - -command! -nargs=+ -complete=shellcmd ConqueTerm call conque_term#open() -command! -nargs=+ -complete=shellcmd ConqueTermSplit call conque_term#open(, ['belowright split']) -command! -nargs=+ -complete=shellcmd ConqueTermVSplit call conque_term#open(, ['belowright vsplit']) -command! -nargs=+ -complete=shellcmd ConqueTermTab call conque_term#open(, ['tabnew']) - -" }}} - diff --git a/vim/tmp/conque/syntax/conque_term.vim b/vim/tmp/conque/syntax/conque_term.vim deleted file mode 100644 index 7607913..0000000 --- a/vim/tmp/conque/syntax/conque_term.vim +++ /dev/null @@ -1,75 +0,0 @@ - -" ******************************************************************************************************************* -" MySQL ************************************************************************************************************* -" ******************************************************************************************************************* - -syn match MySQLTableHead "^ *|.*| *$" nextgroup=MySQLTableDivide contains=MySQLTableBar oneline skipwhite skipnl -syn match MySQLTableBody "^ *|.*| *$" nextgroup=MySQLTableBody,MySQLTableEnd contains=MySQLTableBar,MySQLNull,MySQLBool,MySQLNumber,MySQLStorageClass oneline skipwhite skipnl -syn match MySQLTableEnd "^ *+[+=-]\++ *$" oneline -syn match MySQLTableDivide "^ *+[+=-]\++ *$" nextgroup=MySQLTableBody oneline skipwhite skipnl -syn match MySQLTableStart "^ *+[+=-]\++ *$" nextgroup=MySQLTableHead oneline skipwhite skipnl -syn match MySQLNull " NULL " contained contains=MySQLTableBar -syn match MySQLStorageClass " PRI " contained -syn match MySQLStorageClass " MUL " contained -syn match MySQLStorageClass " UNI " contained -syn match MySQLStorageClass " CURRENT_TIMESTAMP " contained -syn match MySQLStorageClass " auto_increment " contained -syn match MySQLTableBar "|" contained -syn match MySQLNumber "|\? *\d\+ *|" contained contains=MySQLTableBar -syn match MySQLQueryStat "^\d\+ rows\? in set.*" oneline -syn match MySQLPromptLine "^.\?mysql> .*$" contains=MySQLKeyword,MySQLPrompt,MySQLString oneline -syn match MySQLPromptLine "^ -> .*$" contains=MySQLKeyword,MySQLPrompt,MySQLString oneline -syn match MySQLPrompt "^.\?mysql>" contained oneline -syn match MySQLPrompt "^ ->" contained oneline -syn case ignore -syn keyword MySQLKeyword select count max sum avg date show table tables status like as from left right outer inner join contained -syn keyword MySQLKeyword where group by having limit offset order desc asc show contained -syn case match -syn region MySQLString start=+'+ end=+'+ skip=+\\'+ contained oneline -syn region MySQLString start=+"+ end=+"+ skip=+\\"+ contained oneline -syn region MySQLString start=+`+ end=+`+ skip=+\\`+ contained oneline - -hi def link MySQLPrompt Identifier -hi def link MySQLTableHead Title -hi def link MySQLTableBody Normal -hi def link MySQLBool Boolean -hi def link MySQLStorageClass StorageClass -hi def link MySQLNumber Number -hi def link MySQLKeyword Keyword -hi def link MySQLString String - -" terms which have no reasonable default highlight group to link to -hi MySQLTableHead term=bold cterm=bold gui=bold -if &background == 'dark' - hi MySQLTableEnd term=NONE cterm=NONE gui=NONE ctermfg=238 guifg=#444444 - hi MySQLTableDivide term=NONE cterm=NONE gui=NONE ctermfg=238 guifg=#444444 - hi MySQLTableStart term=NONE cterm=NONE gui=NONE ctermfg=238 guifg=#444444 - hi MySQLTableBar term=NONE cterm=NONE gui=NONE ctermfg=238 guifg=#444444 - hi MySQLNull term=NONE cterm=NONE gui=NONE ctermfg=238 guifg=#444444 - hi MySQLQueryStat term=NONE cterm=NONE gui=NONE ctermfg=238 guifg=#444444 -elseif &background == 'light' - hi MySQLTableEnd term=NONE cterm=NONE gui=NONE ctermfg=247 guifg=#9e9e9e - hi MySQLTableDivide term=NONE cterm=NONE gui=NONE ctermfg=247 guifg=#9e9e9e - hi MySQLTableStart term=NONE cterm=NONE gui=NONE ctermfg=247 guifg=#9e9e9e - hi MySQLTableBar term=NONE cterm=NONE gui=NONE ctermfg=247 guifg=#9e9e9e - hi MySQLNull term=NONE cterm=NONE gui=NONE ctermfg=247 guifg=#9e9e9e - hi MySQLQueryStat term=NONE cterm=NONE gui=NONE ctermfg=247 guifg=#9e9e9e -endif - - -" ******************************************************************************************************************* -" Bash ************************************************************************************************************** -" ******************************************************************************************************************* - -" Typical Prompt -silent execute "syn match ConquePromptLine '" . g:ConqueTerm_PromptRegex . ".*$' contains=ConquePrompt,ConqueString oneline" -silent execute "syn match ConquePrompt '" . g:ConqueTerm_PromptRegex . "' contained oneline" -hi def link ConquePrompt Identifier - -" Strings -syn region ConqueString start=+'+ end=+'+ skip=+\\'+ contained oneline -syn region ConqueString start=+"+ end=+"+ skip=+\\"+ contained oneline -syn region ConqueString start=+`+ end=+`+ skip=+\\`+ contained oneline -hi def link ConqueString String - -" vim: foldmethod=marker diff --git a/vim/tmp/conque_1.1.tar.gz b/vim/tmp/conque_1.1.tar.gz deleted file mode 100644 index 96f95b4..0000000 Binary files a/vim/tmp/conque_1.1.tar.gz and /dev/null differ diff --git a/vim/tmp/cucumber b/vim/tmp/cucumber deleted file mode 160000 index 2ef3e5a..0000000 --- a/vim/tmp/cucumber +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2ef3e5a4876a4cd5ea83a0dcbf17f5c3edbf9de3 diff --git a/vim/tmp/endwise b/vim/tmp/endwise deleted file mode 160000 index 9a9d199..0000000 --- a/vim/tmp/endwise +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9a9d1994eaeae3f2f23da6bb71111782ab70276c diff --git a/vim/tmp/fugitive b/vim/tmp/fugitive deleted file mode 160000 index 201bdd0..0000000 --- a/vim/tmp/fugitive +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 201bdd0eff4cd79847cf006f143deb62f8f97342 diff --git a/vim/tmp/gist-vim b/vim/tmp/gist-vim deleted file mode 160000 index 37e98ed..0000000 --- a/vim/tmp/gist-vim +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 37e98ed00e1262ef80d232a9f0e0529afd4ed6ce diff --git a/vim/tmp/git b/vim/tmp/git deleted file mode 160000 index 291cbe9..0000000 --- a/vim/tmp/git +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 291cbe97f2c367f40360949f19b4fa8fb0740e9f diff --git a/vim/tmp/haml b/vim/tmp/haml deleted file mode 160000 index de3e72a..0000000 --- a/vim/tmp/haml +++ /dev/null @@ -1 +0,0 @@ -Subproject commit de3e72a384c9b1cc8707c9bc37cefc24d8484ebf diff --git a/vim/tmp/indent_object b/vim/tmp/indent_object deleted file mode 160000 index 78fffa6..0000000 --- a/vim/tmp/indent_object +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 78fffa609b3e6b84ef01ee4c9aba6d7435d7b18e diff --git a/vim/tmp/irblack b/vim/tmp/irblack deleted file mode 160000 index 59622ca..0000000 --- a/vim/tmp/irblack +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 59622caff32a7925181ab139701fad3eee54ae51 diff --git a/vim/tmp/javascript b/vim/tmp/javascript deleted file mode 160000 index 9990a76..0000000 --- a/vim/tmp/javascript +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9990a767695c78a44611ce33fb2dbc25c83d8827 diff --git a/vim/tmp/markdown b/vim/tmp/markdown deleted file mode 160000 index ae3a265..0000000 --- a/vim/tmp/markdown +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ae3a2653f824bb9e969f462c5d77e035a518ea61 diff --git a/vim/tmp/nerdcommenter b/vim/tmp/nerdcommenter deleted file mode 160000 index 093e6b3..0000000 --- a/vim/tmp/nerdcommenter +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 093e6b3f765b728c129a4271f1f34bb70e671f08 diff --git a/vim/tmp/nerdtree b/vim/tmp/nerdtree deleted file mode 160000 index 3bb112d..0000000 --- a/vim/tmp/nerdtree +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3bb112d916a3e78f2e6528b869cdad1f7d826114 diff --git a/vim/tmp/puppet b/vim/tmp/puppet deleted file mode 160000 index 1f3b151..0000000 --- a/vim/tmp/puppet +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1f3b151b2d4eefc2f1d59c0d381d01d32d56eb50 diff --git a/vim/tmp/rails b/vim/tmp/rails deleted file mode 160000 index d94405a..0000000 --- a/vim/tmp/rails +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d94405aae64ff10fc10a78807b5e9214c83c60df diff --git a/vim/tmp/rspec b/vim/tmp/rspec deleted file mode 160000 index 4e6e495..0000000 --- a/vim/tmp/rspec +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4e6e4956dd3f3ae58daf1087352951a2ba7137bf diff --git a/vim/tmp/scala b/vim/tmp/scala deleted file mode 160000 index e3746cd..0000000 --- a/vim/tmp/scala +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e3746cd5703bedf1009c869e555a3b847b361701 diff --git a/vim/tmp/searchfold b/vim/tmp/searchfold deleted file mode 160000 index f2b988c..0000000 --- a/vim/tmp/searchfold +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f2b988c592bc8989c2b9300f241ebb0aefde43e6 diff --git a/vim/tmp/snipmate b/vim/tmp/snipmate deleted file mode 160000 index f5a75d0..0000000 --- a/vim/tmp/snipmate +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f5a75d075d3c005ebe69e3f5e56cf99516e8aa3b diff --git a/vim/tmp/solarized b/vim/tmp/solarized deleted file mode 160000 index 528a59f..0000000 --- a/vim/tmp/solarized +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 528a59f26d12278698bb946f8fb82a63711eec21 diff --git a/vim/tmp/supertab b/vim/tmp/supertab deleted file mode 160000 index 80ec653..0000000 --- a/vim/tmp/supertab +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 80ec6539e4139a2e0281a0f1e36d5038d55ad980 diff --git a/vim/tmp/surround b/vim/tmp/surround deleted file mode 160000 index f6c9d3b..0000000 --- a/vim/tmp/surround +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f6c9d3beb2d11959d22b2555636aeb0c37e66aa1 diff --git a/vim/tmp/syntastic b/vim/tmp/syntastic deleted file mode 160000 index cf6aa9a..0000000 --- a/vim/tmp/syntastic +++ /dev/null @@ -1 +0,0 @@ -Subproject commit cf6aa9a4143704e0e3070302ffe593636d6e8cc9 diff --git a/vim/tmp/taglist b/vim/tmp/taglist deleted file mode 160000 index 53041fb..0000000 --- a/vim/tmp/taglist +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 53041fbc45398a9af631a20657e109707a455339 diff --git a/vim/tmp/textile b/vim/tmp/textile deleted file mode 160000 index 5d25629..0000000 --- a/vim/tmp/textile +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5d25629d066d01f3c9e0872ac18565afbb84a6dd diff --git a/vim/tmp/unimpaired b/vim/tmp/unimpaired deleted file mode 160000 index 1c9dcee..0000000 --- a/vim/tmp/unimpaired +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1c9dcee02bc23dc5757c2c8f3cc2e4964ed1e636 diff --git a/vim/tmp/vim-coffee-script b/vim/tmp/vim-coffee-script deleted file mode 160000 index dc16925..0000000 --- a/vim/tmp/vim-coffee-script +++ /dev/null @@ -1 +0,0 @@ -Subproject commit dc1692561461fd0b7642e05b03b7670974112eee diff --git a/vim/tmp/vividchalk b/vim/tmp/vividchalk deleted file mode 160000 index c824c2a..0000000 --- a/vim/tmp/vividchalk +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c824c2a5c1d96a7d2ec2df6baf7231dcee621130 diff --git a/vim/tmp/zoomwin b/vim/tmp/zoomwin deleted file mode 160000 index e7ee18e..0000000 --- a/vim/tmp/zoomwin +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e7ee18e2e7ed60509aa951cd34b57193fa14e5ab -- cgit From b3ed569dfb65cde7f84f2c3be3bda3a7edafff5a Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Wed, 5 Jun 2013 09:04:29 -0500 Subject: Move EasyMotion and LargeFile to pathogen bundle --- .gitmodules | 12 +- vim/autoload/EasyMotion.vim | 573 -------------------------------------------- vim/doc/easymotion.txt | 319 ------------------------ vim/plugin/EasyMotion.vim | 73 ------ vim/plugin/LargeFile.vim | 80 ------- 5 files changed, 10 insertions(+), 1047 deletions(-) delete mode 100755 vim/autoload/EasyMotion.vim delete mode 100755 vim/doc/easymotion.txt delete mode 100755 vim/plugin/EasyMotion.vim delete mode 100644 vim/plugin/LargeFile.vim diff --git a/.gitmodules b/.gitmodules index ab37167..c5abb8d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,8 +4,16 @@ [submodule "ctrlp"] path = vim/bundle/ctrlp.vim - url = https://github.com/kien/ctrlp.vim.git + url = git://github.com/kien/ctrlp.vim.git [submodule "vim-json"] path = vim/bundle/vim-json - url = https://github.com/elzr/vim-json.git + url = git://github.com/elzr/vim-json.git + +[submodule "vim-easymotion"] + path = vim/bundle/vim-easymotion + url = git://github.com/Lokaltog/vim-easymotion.git + +[submodule "LargeFile"] + path = vim/bundle/LargeFile + url = git://github.com/vim-scripts/LargeFile.git diff --git a/vim/autoload/EasyMotion.vim b/vim/autoload/EasyMotion.vim deleted file mode 100755 index 7c79dd8..0000000 --- a/vim/autoload/EasyMotion.vim +++ /dev/null @@ -1,573 +0,0 @@ -" EasyMotion - Vim motions on speed! -" -" Author: Kim Silkebækken -" Source repository: https://github.com/Lokaltog/vim-easymotion - -" Default configuration functions {{{ - function! EasyMotion#InitOptions(options) " {{{ - for [key, value] in items(a:options) - if ! exists('g:EasyMotion_' . key) - exec 'let g:EasyMotion_' . key . ' = ' . string(value) - endif - endfor - endfunction " }}} - function! EasyMotion#InitHL(group, colors) " {{{ - let group_default = a:group . 'Default' - - " Prepare highlighting variables - let guihl = printf('guibg=%s guifg=%s gui=%s', a:colors.gui[0], a:colors.gui[1], a:colors.gui[2]) - if !exists('g:CSApprox_loaded') - let ctermhl = &t_Co == 256 - \ ? printf('ctermbg=%s ctermfg=%s cterm=%s', a:colors.cterm256[0], a:colors.cterm256[1], a:colors.cterm256[2]) - \ : printf('ctermbg=%s ctermfg=%s cterm=%s', a:colors.cterm[0], a:colors.cterm[1], a:colors.cterm[2]) - else - let ctermhl = '' - endif - - " Create default highlighting group - execute printf('hi default %s %s %s', group_default, guihl, ctermhl) - - " Check if the hl group exists - if hlexists(a:group) - redir => hlstatus | exec 'silent hi ' . a:group | redir END - - " Return if the group isn't cleared - if hlstatus !~ 'cleared' - return - endif - endif - - " No colors are defined for this group, link to defaults - execute printf('hi default link %s %s', a:group, group_default) - endfunction " }}} - function! EasyMotion#InitMappings(motions) "{{{ - for motion in keys(a:motions) - call EasyMotion#InitOptions({ 'mapping_' . motion : g:EasyMotion_leader_key . motion }) - endfor - - if g:EasyMotion_do_mapping - for [motion, fn] in items(a:motions) - if empty(g:EasyMotion_mapping_{motion}) - continue - endif - - silent exec 'nnoremap ' . g:EasyMotion_mapping_{motion} . ' :call EasyMotion#' . fn.name . '(0, ' . fn.dir . ')' - silent exec 'onoremap ' . g:EasyMotion_mapping_{motion} . ' :call EasyMotion#' . fn.name . '(0, ' . fn.dir . ')' - silent exec 'vnoremap ' . g:EasyMotion_mapping_{motion} . ' :call EasyMotion#' . fn.name . '(1, ' . fn.dir . ')' - endfor - endif - endfunction "}}} -" }}} -" Motion functions {{{ - function! EasyMotion#F(visualmode, direction) " {{{ - let char = s:GetSearchChar(a:visualmode) - - if empty(char) - return - endif - - let re = '\C' . escape(char, '.$^~') - - call s:EasyMotion(re, a:direction, a:visualmode ? visualmode() : '', mode(1)) - endfunction " }}} - function! EasyMotion#T(visualmode, direction) " {{{ - let char = s:GetSearchChar(a:visualmode) - - if empty(char) - return - endif - - if a:direction == 1 - let re = '\C' . escape(char, '.$^~') . '\zs.' - else - let re = '\C.' . escape(char, '.$^~') - endif - - call s:EasyMotion(re, a:direction, a:visualmode ? visualmode() : '', mode(1)) - endfunction " }}} - function! EasyMotion#WB(visualmode, direction) " {{{ - call s:EasyMotion('\(\<.\|^$\)', a:direction, a:visualmode ? visualmode() : '', '') - endfunction " }}} - function! EasyMotion#WBW(visualmode, direction) " {{{ - call s:EasyMotion('\(\(^\|\s\)\@<=\S\|^$\)', a:direction, a:visualmode ? visualmode() : '', '') - endfunction " }}} - function! EasyMotion#E(visualmode, direction) " {{{ - call s:EasyMotion('\(.\>\|^$\)', a:direction, a:visualmode ? visualmode() : '', mode(1)) - endfunction " }}} - function! EasyMotion#EW(visualmode, direction) " {{{ - call s:EasyMotion('\(\S\(\s\|$\)\|^$\)', a:direction, a:visualmode ? visualmode() : '', mode(1)) - endfunction " }}} - function! EasyMotion#JK(visualmode, direction) " {{{ - call s:EasyMotion('^\(\w\|\s*\zs\|$\)', a:direction, a:visualmode ? visualmode() : '', '') - endfunction " }}} - function! EasyMotion#Search(visualmode, direction) " {{{ - call s:EasyMotion(@/, a:direction, a:visualmode ? visualmode() : '', '') - endfunction " }}} -" }}} -" Helper functions {{{ - function! s:Message(message) " {{{ - echo 'EasyMotion: ' . a:message - endfunction " }}} - function! s:Prompt(message) " {{{ - echohl Question - echo a:message . ': ' - echohl None - endfunction " }}} - function! s:VarReset(var, ...) " {{{ - if ! exists('s:var_reset') - let s:var_reset = {} - endif - - let buf = bufname("") - - if a:0 == 0 && has_key(s:var_reset, a:var) - " Reset var to original value - call setbufvar(buf, a:var, s:var_reset[a:var]) - elseif a:0 == 1 - let new_value = a:0 == 1 ? a:1 : '' - - " Store original value - let s:var_reset[a:var] = getbufvar(buf, a:var) - - " Set new var value - call setbufvar(buf, a:var, new_value) - endif - endfunction " }}} - function! s:SetLines(lines, key) " {{{ - try - " Try to join changes with previous undo block - undojoin - catch - endtry - - for [line_num, line] in a:lines - call setline(line_num, line[a:key]) - endfor - endfunction " }}} - function! s:GetChar() " {{{ - let char = getchar() - - if char == 27 - " Escape key pressed - redraw - - call s:Message('Cancelled') - - return '' - endif - - return nr2char(char) - endfunction " }}} - function! s:GetSearchChar(visualmode) " {{{ - call s:Prompt('Search for character') - - let char = s:GetChar() - - " Check that we have an input char - if empty(char) - " Restore selection - if ! empty(a:visualmode) - silent exec 'normal! gv' - endif - - return '' - endif - - return char - endfunction " }}} -" }}} -" Grouping algorithms {{{ - let s:grouping_algorithms = { - \ 1: 'SCTree' - \ , 2: 'Original' - \ } - " Single-key/closest target priority tree {{{ - " This algorithm tries to assign one-key jumps to all the targets closest to the cursor. - " It works recursively and will work correctly with as few keys as two. - function! s:GroupingAlgorithmSCTree(targets, keys) - " Prepare variables for working - let targets_len = len(a:targets) - let keys_len = len(a:keys) - - let groups = {} - - let keys = reverse(copy(a:keys)) - - " Semi-recursively count targets {{{ - " We need to know exactly how many child nodes (targets) this branch will have - " in order to pass the correct amount of targets to the recursive function. - - " Prepare sorted target count list {{{ - " This is horrible, I know. But dicts aren't sorted in vim, so we need to - " work around that. That is done by having one sorted list with key counts, - " and a dict which connects the key with the keys_count list. - - let keys_count = [] - let keys_count_keys = {} - - let i = 0 - for key in keys - call add(keys_count, 0) - - let keys_count_keys[key] = i - - let i += 1 - endfor - " }}} - - let targets_left = targets_len - let level = 0 - let i = 0 - - while targets_left > 0 - " Calculate the amount of child nodes based on the current level - let childs_len = (level == 0 ? 1 : (keys_len - 1) ) - - for key in keys - " Add child node count to the keys_count array - let keys_count[keys_count_keys[key]] += childs_len - - " Subtract the child node count - let targets_left -= childs_len - - if targets_left <= 0 - " Subtract the targets left if we added too many too - " many child nodes to the key count - let keys_count[keys_count_keys[key]] += targets_left - - break - endif - - let i += 1 - endfor - - let level += 1 - endwhile - " }}} - " Create group tree {{{ - let i = 0 - let key = 0 - - call reverse(keys_count) - - for key_count in keys_count - if key_count > 1 - " We need to create a subgroup - " Recurse one level deeper - let groups[a:keys[key]] = s:GroupingAlgorithmSCTree(a:targets[i : i + key_count - 1], a:keys) - elseif key_count == 1 - " Assign single target key - let groups[a:keys[key]] = a:targets[i] - else - " No target - continue - endif - - let key += 1 - let i += key_count - endfor - " }}} - - " Finally! - return groups - endfunction - " }}} - " Original {{{ - function! s:GroupingAlgorithmOriginal(targets, keys) - " Split targets into groups (1 level) - let targets_len = len(a:targets) - let keys_len = len(a:keys) - - let groups = {} - - let i = 0 - let root_group = 0 - try - while root_group < targets_len - let groups[a:keys[root_group]] = {} - - for key in a:keys - let groups[a:keys[root_group]][key] = a:targets[i] - - let i += 1 - endfor - - let root_group += 1 - endwhile - catch | endtry - - " Flatten the group array - if len(groups) == 1 - let groups = groups[a:keys[0]] - endif - - return groups - endfunction - " }}} - " Coord/key dictionary creation {{{ - function! s:CreateCoordKeyDict(groups, ...) - " Dict structure: - " 1,2 : a - " 2,3 : b - let sort_list = [] - let coord_keys = {} - let group_key = a:0 == 1 ? a:1 : '' - - for [key, item] in items(a:groups) - let key = ( ! empty(group_key) ? group_key : key) - - if type(item) == 3 - " Destination coords - - " The key needs to be zero-padded in order to - " sort correctly - let dict_key = printf('%05d,%05d', item[0], item[1]) - let coord_keys[dict_key] = key - - " We need a sorting list to loop correctly in - " PromptUser, dicts are unsorted - call add(sort_list, dict_key) - else - " Item is a dict (has children) - let coord_key_dict = s:CreateCoordKeyDict(item, key) - - " Make sure to extend both the sort list and the - " coord key dict - call extend(sort_list, coord_key_dict[0]) - call extend(coord_keys, coord_key_dict[1]) - endif - - unlet item - endfor - - return [sort_list, coord_keys] - endfunction - " }}} -" }}} -" Core functions {{{ - function! s:PromptUser(groups) "{{{ - " If only one possible match, jump directly to it {{{ - let group_values = values(a:groups) - - if len(group_values) == 1 - redraw - - return group_values[0] - endif - " }}} - " Prepare marker lines {{{ - let lines = {} - let hl_coords = [] - let coord_key_dict = s:CreateCoordKeyDict(a:groups) - - for dict_key in sort(coord_key_dict[0]) - let target_key = coord_key_dict[1][dict_key] - let [line_num, col_num] = split(dict_key, ',') - - let line_num = str2nr(line_num) - let col_num = str2nr(col_num) - - " Add original line and marker line - if ! has_key(lines, line_num) - let current_line = getline(line_num) - - let lines[line_num] = { 'orig': current_line, 'marker': current_line, 'mb_compensation': 0 } - endif - - " Compensate for byte difference between marker - " character and target character - " - " This has to be done in order to match the correct - " column; \%c matches the byte column and not display - " column. - let target_char_len = strlen(matchstr(lines[line_num]['marker'], '\%' . col_num . 'c.')) - let target_key_len = strlen(target_key) - - " Solve multibyte issues by matching the byte column - " number instead of the visual column - let col_num -= lines[line_num]['mb_compensation'] - - if strlen(lines[line_num]['marker']) > 0 - " Substitute marker character if line length > 0 - let lines[line_num]['marker'] = substitute(lines[line_num]['marker'], '\%' . col_num . 'c.', target_key, '') - else - " Set the line to the marker character if the line is empty - let lines[line_num]['marker'] = target_key - endif - - " Add highlighting coordinates - call add(hl_coords, '\%' . line_num . 'l\%' . col_num . 'c') - - " Add marker/target lenght difference for multibyte - " compensation - let lines[line_num]['mb_compensation'] += (target_char_len - target_key_len) - endfor - - let lines_items = items(lines) - " }}} - " Highlight targets {{{ - let target_hl_id = matchadd(g:EasyMotion_hl_group_target, join(hl_coords, '\|'), 1) - " }}} - - try - " Set lines with markers - call s:SetLines(lines_items, 'marker') - - redraw - - " Get target character {{{ - call s:Prompt('Target key') - - let char = s:GetChar() - " }}} - finally - " Restore original lines - call s:SetLines(lines_items, 'orig') - - " Un-highlight targets {{{ - if exists('target_hl_id') - call matchdelete(target_hl_id) - endif - " }}} - - redraw - endtry - - " Check if we have an input char {{{ - if empty(char) - throw 'Cancelled' - endif - " }}} - " Check if the input char is valid {{{ - if ! has_key(a:groups, char) - throw 'Invalid target' - endif - " }}} - - let target = a:groups[char] - - if type(target) == 3 - " Return target coordinates - return target - else - " Prompt for new target character - return s:PromptUser(target) - endif - endfunction "}}} - function! s:EasyMotion(regexp, direction, visualmode, mode) " {{{ - let orig_pos = [line('.'), col('.')] - let targets = [] - - try - " Reset properties {{{ - call s:VarReset('&scrolloff', 0) - call s:VarReset('&modified', 0) - call s:VarReset('&modifiable', 1) - call s:VarReset('&readonly', 0) - call s:VarReset('&spell', 0) - call s:VarReset('&virtualedit', '') - " }}} - " Find motion targets {{{ - let search_direction = (a:direction == 1 ? 'b' : '') - let search_stopline = line(a:direction == 1 ? 'w0' : 'w$') - - while 1 - let pos = searchpos(a:regexp, search_direction, search_stopline) - - " Reached end of search range - if pos == [0, 0] - break - endif - - " Skip folded lines - if foldclosed(pos[0]) != -1 - continue - endif - - call add(targets, pos) - endwhile - - let targets_len = len(targets) - if targets_len == 0 - throw 'No matches' - endif - " }}} - - let GroupingFn = function('s:GroupingAlgorithm' . s:grouping_algorithms[g:EasyMotion_grouping]) - let groups = GroupingFn(targets, split(g:EasyMotion_keys, '\zs')) - - " Shade inactive source {{{ - if g:EasyMotion_do_shade - let shade_hl_pos = '\%' . orig_pos[0] . 'l\%'. orig_pos[1] .'c' - - if a:direction == 1 - " Backward - let shade_hl_re = '\%'. line('w0') .'l\_.*' . shade_hl_pos - else - " Forward - let shade_hl_re = shade_hl_pos . '\_.*\%'. line('w$') .'l' - endif - - let shade_hl_id = matchadd(g:EasyMotion_hl_group_shade, shade_hl_re, 0) - endif - " }}} - - " Prompt user for target group/character - let coords = s:PromptUser(groups) - - " Update selection {{{ - if ! empty(a:visualmode) - keepjumps call cursor(orig_pos[0], orig_pos[1]) - - exec 'normal! ' . a:visualmode - endif - " }}} - " Handle operator-pending mode {{{ - if a:mode == 'no' - " This mode requires that we eat one more - " character to the right if we're using - " a forward motion - if a:direction != 1 - let coords[1] += 1 - endif - endif - " }}} - - " Update cursor position - call cursor(orig_pos[0], orig_pos[1]) - mark ' - call cursor(coords[0], coords[1]) - - call s:Message('Jumping to [' . coords[0] . ', ' . coords[1] . ']') - catch - redraw - - " Show exception message - call s:Message(v:exception) - - " Restore original cursor position/selection {{{ - if ! empty(a:visualmode) - silent exec 'normal! gv' - else - keepjumps call cursor(orig_pos[0], orig_pos[1]) - endif - " }}} - finally - " Restore properties {{{ - call s:VarReset('&scrolloff') - call s:VarReset('&modified') - call s:VarReset('&modifiable') - call s:VarReset('&readonly') - call s:VarReset('&spell') - call s:VarReset('&virtualedit') - " }}} - " Remove shading {{{ - if g:EasyMotion_do_shade && exists('shade_hl_id') - call matchdelete(shade_hl_id) - endif - " }}} - endtry - endfunction " }}} -" }}} - -" vim: fdm=marker:noet:ts=4:sw=4:sts=4 diff --git a/vim/doc/easymotion.txt b/vim/doc/easymotion.txt deleted file mode 100755 index c91a959..0000000 --- a/vim/doc/easymotion.txt +++ /dev/null @@ -1,319 +0,0 @@ -*easymotion.txt* Version 1.3. Last change: 2011 Nov 7 - - - ______ __ ___ __ _ - / ____/____ ________ __/ |/ /____ / /_(_)____ ____ - / __/ / __ `/ ___/ / / / /|_/ // __ \/ __/ // __ \/ __ \ - / /___ / /_/ (__ ) /_/ / / / // /_/ / /_/ // /_/ / / / / - /_____/ \__,_/____/\__, /_/ /_/ \____/\__/_/ \____/_/ /_/ - /____/ - - Vim motions on speed! - - -============================================================================== -CONTENTS *easymotion-contents* - - 1. Introduction ....................... |easymotion-introduction| - 2. Usage .............................. |easymotion-usage| - 2.1 Default mappings ............... |easymotion-default-mappings| - 3. Requirements ....................... |easymotion-requirements| - 4. Configuration ...................... |easymotion-configuration| - 4.1 EasyMotion_keys ................ |EasyMotion_keys| - 4.2 EasyMotion_do_shade ............ |EasyMotion_do_shade| - 4.3 EasyMotion_do_mapping .......... |EasyMotion_do_mapping| - 4.4 EasyMotion_grouping ............ |EasyMotion_grouping| - 4.5 Custom highlighting ............ |easymotion-custom-hl| - 4.6 Custom mappings ................ |easymotion-custom-mappings| - 4.6.1 Leader key ............... |easymotion-leader-key| - 4.6.2 Custom keys .............. |easymotion-custom-keys| - 5. License ............................ |easymotion-license| - 6. Known bugs ......................... |easymotion-known-bugs| - 7. Contributing ....................... |easymotion-contributing| - 8. Credits ............................ |easymotion-credits| - -============================================================================== -1. Introduction *easymotion* *easymotion-introduction* - -EasyMotion provides a much simpler way to use some motions in vim. It takes -the out of w or f{char} by highlighting all possible -choices and allowing you to press one key to jump directly to the target. - -When one of the available motions is triggered, all visible text preceding or -following the cursor is faded, and motion targets are highlighted. - -============================================================================== -2. Usage *easymotion-usage* - -EasyMotion is triggered by one of the provided mappings (see -|easymotion-default-mappings| for details). - -Example: > - - Lorem ipsum dolor sit amet. - -Type w to trigger the word motion |w|. See -|easymotion-leader-key| for details about the leader key. When the -motion is triggered, the text is updated (no braces are actually added, -the text is highlighted in red by default): > - - Lorem {a}psum {b}olor {c}it {d}met. - -Press "c" to jump to the beginning of the word "sit": > - - Lorem ipsum dolor sit amet. - -Similarly, if you're looking for an "o", you can use the |f| motion. -Type fo, and all "o" characters are highlighted: > - - L{a}rem ipsum d{b}l{c}r sit amet. - -Press "b" to jump to the second "o": > - - Lorem ipsum dolor sit amet. - -And that's it! - ------------------------------------------------------------------------------- -2.1 Default mappings *easymotion-default-mappings* - -The default configuration defines the following mappings in normal, -visual and operator-pending mode: - - Mapping | Details - ------------------|---------------------------------------------- - f{char} | Find {char} to the right. See |f|. - F{char} | Find {char} to the left. See |F|. - t{char} | Till before the {char} to the right. See |t|. - T{char} | Till after the {char} to the left. See |T|. - w | Beginning of word forward. See |w|. - W | Beginning of WORD forward. See |W|. - b | Beginning of word backward. See |b|. - B | Beginning of WORD backward. See |B|. - e | End of word forward. See |e|. - E | End of WORD forward. See |E|. - ge | End of word backward. See |ge|. - gE | End of WORD backward. See |gE|. - j | Line downward. See |j|. - k | Line upward. See |k|. - n | Jump to latest "/" or "?" forward. See |n|. - N | Jump to latest "/" or "?" backward. See |N|. - -See |easymotion-leader-key| and |mapleader| for details about the leader key. -See |easymotion-custom-mappings| for customizing the default mappings. - -============================================================================== -3. Requirements *easymotion-requirements* - -EasyMotion has been developed and tested in vim 7.3, but it should run without -any problems in vim 7.2. - -Vi-compatible mode must be disabled. - -============================================================================== -4. Configuration *easymotion-configuration* - -EasyMotion will work fine without any configuration, but you can override the -default behavior by setting configuration variables globally in your |vimrc| -file. - -Example (this will change the target keys and disable shading): > - - let g:EasyMotion_keys = '1234567890' - let g:EasyMotion_do_shade = 0 - ------------------------------------------------------------------------------- -4.1 EasyMotion_keys *EasyMotion_keys* - -Set the keys which will be used for motion targets. Add as many keys as you -want. There's a lower chance that the motion targets will be grouped if many -keys are available. - -Default: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' - ------------------------------------------------------------------------------- -4.2 EasyMotion_do_shade *EasyMotion_do_shade* - -The default behavior is to shade the text following the cursor (forward -motions) or preceding the cursor (backward motions) to make the motion targets -more visible. Set this option to 0 if you want to disable text shading. - -Default: 1 - ------------------------------------------------------------------------------- -4.3 EasyMotion_do_mapping *EasyMotion_do_mapping* - -Set this option to 0 if you want to disable the default mappings. See -|easymotion-default-mappings| for details about the default mappings. - -Note: If you disable this option, you'll have to map the motions yourself. See -the plugin source code for mapping details. You usually shouldn't need to do -this, see |easymotion-custom-mappings| for customizing the default mappings. - -Default: 1 - ------------------------------------------------------------------------------- -4.4 EasyMotion_grouping *EasyMotion_grouping* - -When there are too many possible targets on the screen, the results have to be -grouped. This configuration option lets you change which grouping algorithm -you want to use. There are two grouping algorithms available: - - * Single-key priority (value: 1) - ------------------- - - This algorithm prioritizes single-key jumps for the targets closest to - the cursor and only groups the last jump targets to maximize the amount - of single-key jumps. - - This algorithm works recursively and will work with as few keys as two. - - Example (with |EasyMotion_keys| = "abcdef"): > - - x x x x x x x x x -< - The |w| motion is triggered: > - - a b c d e f f f f - ^ ^ ^ ^ ^ Direct jump to target - ^ ^ ^ ^ Enter group "f" -< - * Original (value: 2) - -------- - - This is the original algorithm which always groups all targets if there - are too many possible motion targets. - - Example (with |EasyMotion_keys| = "abcdef"): > - - x x x x x x x x x -< - The |w| motion is triggered: > - - a a a a a a b b b - ^ ^ ^ ^ ^ ^ Enter group "a" - ^ ^ ^ Enter group "b" - -Default: 1 - ------------------------------------------------------------------------------- -4.5 Custom highlighting *easymotion-custom-hl* - -The default EasyMotion configuration uses two highlighting groups that link -to groups with default values. The highlighting groups are: - - * EasyMotionTarget - - Highlights motion targets, the default value is bold red - - * EasyMotionShade - - Highlights shaded text, the default value is dark gray - -There are two ways to override the default colors: - - 1) Set the highlighting in your color scheme - - This will only affect a single color scheme. The default red/gray colors - will be used if you change the color scheme to one that doesn't assign - any EasyMotion colors. - - Example: > - - hi EasyMotionTarget ctermbg=none ctermfg=green - hi EasyMotionShade ctermbg=none ctermfg=blue -< - 2) Set the highlighting in your vimrc - - This is ideal if you want to link the colors to highlighting groups that - are available in almost every color scheme, e.g. |ErrorMsg| (usually - bright red) and Comment (usually faded). You can be sure that the - color scheme's colors will be used instead of the default red/gray - if you choose this option. - - Example: > - - hi link EasyMotionTarget ErrorMsg - hi link EasyMotionShade Comment -< ------------------------------------------------------------------------------- -4.6 Custom mappings *easymotion-custom-mappings* - -EasyMotion allows you to customize all default mappings to avoid conflicts -with existing mappings. It is possible to change the default leader key -of all mappings to another key or sequence. It is also possible to fine -tune the plugin to your need by changing every single sequence. - -4.6.1 Leader key *EasyMotion_leader_key* *easymotion-leader-key* - -The default leader key can be changed with the configuration option -|EasyMotion_leader_key|. - -Set this option to the key sequence to use as the prefix of the mappings -described in |easymotion-default-mappings|. - -Note: The default leader key has been changed to '' to -avoid conflicts with other plugins. You can revert to the original -leader by setting this option in your vimrc: > - - let g:EasyMotion_leader_key = '' -< -Default: '' - -4.6.2 Custom Keys *easymotion-custom-keys* - -All custom mappings follow the same variable format: > - - EasyMotion_mapping_{motion} = {mapping} -< -Example: > - - let g:EasyMotion_mapping_f = '_f' - let g:EasyMotion_mapping_T = '' -< -See |easymotion-default-mappings| for a table of motions that can be mapped -and their default values. - -Note: The leader key defined by |EasyMotion_leader_key| is not prepended to -your customized mappings! You have to provide full key sequences when setting -these options. - -============================================================================== -5. License *easymotion-license* - -Creative Commons Attribution-ShareAlike 3.0 Unported - -http://creativecommons.org/licenses/by-sa/3.0/ - -============================================================================== -6. Known bugs *easymotion-known-bugs* - -None. - -============================================================================== -7. Contributing *easymotion-contributing* - -If you experience any bugs or have feature requests, please open an issue on -GitHub. Fork the source repository on GitHub and send a pull request if you -have any code improvements. - -Author: Kim Silkebækken -Source repository: https://github.com/Lokaltog/vim-easymotion - -============================================================================== -8. Credits *easymotion-credits* - -- Ben Boeckel: ge and WORD motions -- Drew Neil: operator-pending mappings -- Rob O'Dwyer: customizable mappings without giving up all defaults -- Michel D'Hooge: customizable leader -- Maxime Bourget: search motion, improved JK motion behavior -- Kearn Holliday: fix jumplist issues -- Shougo Matsushita: fix CSApprox issue - -EasyMotion is based on Bartlomiej Podolak's great PreciseJump script, which -can be downloaded here: - -http://www.vim.org/scripts/script.php?script_id=3437 - -============================================================================== -vim:tw=78:sw=4:ts=8:ft=help:norl: diff --git a/vim/plugin/EasyMotion.vim b/vim/plugin/EasyMotion.vim deleted file mode 100755 index fff29dc..0000000 --- a/vim/plugin/EasyMotion.vim +++ /dev/null @@ -1,73 +0,0 @@ -" EasyMotion - Vim motions on speed! -" -" Author: Kim Silkebækken -" Source repository: https://github.com/Lokaltog/vim-easymotion - -" Script initialization {{{ - if exists('g:EasyMotion_loaded') || &compatible || version < 702 - finish - endif - - let g:EasyMotion_loaded = 1 -" }}} -" Default configuration {{{ - " Default options {{{ - call EasyMotion#InitOptions({ - \ 'leader_key' : '' - \ , 'keys' : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' - \ , 'do_shade' : 1 - \ , 'do_mapping' : 1 - \ , 'grouping' : 1 - \ - \ , 'hl_group_target' : 'EasyMotionTarget' - \ , 'hl_group_shade' : 'EasyMotionShade' - \ }) - " }}} - " Default highlighting {{{ - let s:target_hl_defaults = { - \ 'gui' : ['NONE', '#ff0000' , 'bold'] - \ , 'cterm256': ['NONE', '196' , 'bold'] - \ , 'cterm' : ['NONE', 'red' , 'bold'] - \ } - - let s:shade_hl_defaults = { - \ 'gui' : ['NONE', '#777777' , 'NONE'] - \ , 'cterm256': ['NONE', '242' , 'NONE'] - \ , 'cterm' : ['NONE', 'grey' , 'NONE'] - \ } - - call EasyMotion#InitHL(g:EasyMotion_hl_group_target, s:target_hl_defaults) - call EasyMotion#InitHL(g:EasyMotion_hl_group_shade, s:shade_hl_defaults) - - " Reset highlighting after loading a new color scheme {{{ - augroup EasyMotionInitHL - autocmd! - - autocmd ColorScheme * call EasyMotion#InitHL(g:EasyMotion_hl_group_target, s:target_hl_defaults) - autocmd ColorScheme * call EasyMotion#InitHL(g:EasyMotion_hl_group_shade, s:shade_hl_defaults) - augroup end - " }}} - " }}} - " Default key mapping {{{ - call EasyMotion#InitMappings({ - \ 'f' : { 'name': 'F' , 'dir': 0 } - \ , 'F' : { 'name': 'F' , 'dir': 1 } - \ , 't' : { 'name': 'T' , 'dir': 0 } - \ , 'T' : { 'name': 'T' , 'dir': 1 } - \ , 'w' : { 'name': 'WB' , 'dir': 0 } - \ , 'W' : { 'name': 'WBW', 'dir': 0 } - \ , 'b' : { 'name': 'WB' , 'dir': 1 } - \ , 'B' : { 'name': 'WBW', 'dir': 1 } - \ , 'e' : { 'name': 'E' , 'dir': 0 } - \ , 'E' : { 'name': 'EW' , 'dir': 0 } - \ , 'ge': { 'name': 'E' , 'dir': 1 } - \ , 'gE': { 'name': 'EW' , 'dir': 1 } - \ , 'j' : { 'name': 'JK' , 'dir': 0 } - \ , 'k' : { 'name': 'JK' , 'dir': 1 } - \ , 'n' : { 'name': 'Search' , 'dir': 0 } - \ , 'N' : { 'name': 'Search' , 'dir': 1 } - \ }) - " }}} -" }}} - -" vim: fdm=marker:noet:ts=4:sw=4:sts=4 diff --git a/vim/plugin/LargeFile.vim b/vim/plugin/LargeFile.vim deleted file mode 100644 index 9f6551e..0000000 --- a/vim/plugin/LargeFile.vim +++ /dev/null @@ -1,80 +0,0 @@ -" LargeFile: Sets up an autocmd to make editing large files work with celerity -" Author: Charles E. Campbell, Jr. -" Date: Sep 23, 2008 -" Version: 4 -" GetLatestVimScripts: 1506 1 :AutoInstall: LargeFile.vim - -" --------------------------------------------------------------------- -" Load Once: {{{1 -if exists("g:loaded_LargeFile") || &cp - finish -endif -let g:loaded_LargeFile = "v4" -let s:keepcpo = &cpo -set cpo&vim - -" --------------------------------------------------------------------- -" Commands: {{{1 -com! Unlarge call s:Unlarge() -com! -bang Large call s:LargeFile(0,expand("%")) - -" --------------------------------------------------------------------- -" Options: {{{1 -if !exists("g:LargeFile") - let g:LargeFile= 20 " in megabytes -endif - -" --------------------------------------------------------------------- -" LargeFile Autocmd: {{{1 -" for large files: turns undo, syntax highlighting, undo off etc -" (based on vimtip#611) -augroup LargeFile - au! - au BufReadPre * call LargeFile(0,expand("")) - au BufReadPost * - \ if &ch < 2 && (getfsize(expand("")) >= g:LargeFile*1024*1024 || getfsize(expand("")) == -2) - \| echomsg "***note*** handling a large file" - \| endif -augroup END - -" --------------------------------------------------------------------- -" s:LargeFile: {{{2 -fun! s:LargeFile(force,fname) -" call Dfunc("LargeFile(force=".a:force." fname<".a:fname.">)") - if a:force || getfsize(a:fname) >= g:LargeFile*1024*1024 || getfsize(a:fname) <= -2 - syn clear - let b:eikeep = &ei - let b:ulkeep = &ul - let b:bhkeep = &bh - let b:fdmkeep= &fdm - let b:swfkeep= &swf - set ei=FileType - setlocal noswf bh=unload fdm=manual ul=-1 - let fname=escape(substitute(a:fname,'\','/','g'),' ') - exe "au LargeFile BufEnter ".fname." set ul=-1" - exe "au LargeFile BufLeave ".fname." let &ul=".b:ulkeep."|set ei=".b:eikeep - exe "au LargeFile BufUnload ".fname." au! LargeFile * ". fname - echomsg "***note*** handling a large file" - endif -" call Dret("s:LargeFile") -endfun - -" --------------------------------------------------------------------- -" s:Unlarge: this function will undo what the LargeFile autocmd does {{{2 -fun! s:Unlarge() -" call Dfunc("s:Unlarge()") - if exists("b:eikeep") |let &ei = b:eikeep |endif - if exists("b:ulkeep") |let &ul = b:ulkeep |endif - if exists("b:bhkeep") |let &bh = b:bhkeep |endif - if exists("b:fdmkeep")|let &fdm = b:fdmkeep|endif - if exists("b:swfkeep")|let &swf = b:swfkeep|endif - syn on - doau FileType -" call Dret("s:Unlarge") -endfun - -" --------------------------------------------------------------------- -" Restore: {{{1 -let &cpo= s:keepcpo -unlet s:keepcpo -" vim: ts=4 fdm=marker -- cgit From b61151bbd6d1b325d2d0d09cac7d06e2543346c7 Mon Sep 17 00:00:00 2001 From: Ben Beltran Date: Wed, 5 Jun 2013 09:34:53 -0500 Subject: A whole bunch of new additions to the submodules --- .gitmodules | 40 +- tmux-powerline | 1 + vim/autoload/Align.vim | 1029 --------- vim/autoload/AlignMaps.vim | 330 --- vim/autoload/ZoomWin.vim | 380 ---- vim/autoload/delimitMate.vim | 586 ----- vim/bundle/Align | 1 + vim/bundle/Colour-Sampler-Pack | 1 + vim/bundle/LargeFile | 1 + vim/bundle/SearchComplete | 1 + vim/bundle/ZoomWin | 1 + vim/bundle/ag.vim | 1 + vim/bundle/delimitMate | 1 + vim/bundle/nerdcommenter | 1 + vim/bundle/nerdtree | 1 + vim/bundle/vim-easymotion | 1 + vim/bundle/vim-endwise | 1 + vim/doc/Align.txt | 1469 ------------ vim/doc/NERD_commenter.txt | 988 -------- vim/doc/NERD_tree.txt | 1226 ---------- vim/doc/ZoomWin.txt | 121 - vim/doc/ack.txt | 51 - vim/doc/delimitMate.txt | 818 ------- vim/nerdtree_plugin/exec_menuitem.vim | 41 - vim/nerdtree_plugin/fs_menu.vim | 194 -- vim/plugin/AlignMapsPlugin.vim | 242 -- vim/plugin/AlignPlugin.vim | 41 - vim/plugin/NERD_commenter.vim | 2790 ----------------------- vim/plugin/NERD_tree.vim | 4049 --------------------------------- vim/plugin/SearchComplete.vim | 100 - vim/plugin/ZoomWinPlugin.vim | 49 - vim/plugin/ack.vim | 79 - vim/plugin/cecutil.vim | 510 ----- vim/plugin/color_sample_pack.vim | 164 -- vim/plugin/conque_term.vim | 93 - vim/plugin/delimitMate.vim | 434 ---- vim/plugin/endwise.vim | 134 -- 37 files changed, 45 insertions(+), 15925 deletions(-) create mode 160000 tmux-powerline delete mode 100644 vim/autoload/Align.vim delete mode 100644 vim/autoload/AlignMaps.vim delete mode 100644 vim/autoload/ZoomWin.vim delete mode 100644 vim/autoload/delimitMate.vim create mode 160000 vim/bundle/Align create mode 160000 vim/bundle/Colour-Sampler-Pack create mode 160000 vim/bundle/LargeFile create mode 160000 vim/bundle/SearchComplete create mode 160000 vim/bundle/ZoomWin create mode 160000 vim/bundle/ag.vim create mode 160000 vim/bundle/delimitMate create mode 160000 vim/bundle/nerdcommenter create mode 160000 vim/bundle/nerdtree create mode 160000 vim/bundle/vim-easymotion create mode 160000 vim/bundle/vim-endwise delete mode 100644 vim/doc/Align.txt delete mode 100644 vim/doc/NERD_commenter.txt delete mode 100644 vim/doc/NERD_tree.txt delete mode 100644 vim/doc/ZoomWin.txt delete mode 100644 vim/doc/ack.txt delete mode 100644 vim/doc/delimitMate.txt delete mode 100644 vim/nerdtree_plugin/exec_menuitem.vim delete mode 100644 vim/nerdtree_plugin/fs_menu.vim delete mode 100644 vim/plugin/AlignMapsPlugin.vim delete mode 100644 vim/plugin/AlignPlugin.vim delete mode 100644 vim/plugin/NERD_commenter.vim delete mode 100644 vim/plugin/NERD_tree.vim delete mode 100644 vim/plugin/SearchComplete.vim delete mode 100644 vim/plugin/ZoomWinPlugin.vim delete mode 100644 vim/plugin/ack.vim delete mode 100644 vim/plugin/cecutil.vim delete mode 100644 vim/plugin/color_sample_pack.vim delete mode 100644 vim/plugin/conque_term.vim delete mode 100644 vim/plugin/delimitMate.vim delete mode 100644 vim/plugin/endwise.vim diff --git a/.gitmodules b/.gitmodules index c5abb8d..b572e5b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,10 +10,36 @@ path = vim/bundle/vim-json url = git://github.com/elzr/vim-json.git -[submodule "vim-easymotion"] - path = vim/bundle/vim-easymotion - url = git://github.com/Lokaltog/vim-easymotion.git - -[submodule "LargeFile"] - path = vim/bundle/LargeFile - url = git://github.com/vim-scripts/LargeFile.git +[submodule "vim/bundle/vim-easymotion"] + path = vim/bundle/vim-easymotion + url = git://github.com/Lokaltog/vim-easymotion.git +[submodule "vim/bundle/LargeFile"] + path = vim/bundle/LargeFile + url = git://github.com/vim-scripts/LargeFile.git +[submodule "vim/bundle/Align"] + path = vim/bundle/Align + url = https://github.com/vim-scripts/Align +[submodule "vim/bundle/nerdcommenter"] + path = vim/bundle/nerdcommenter + url = git://github.com/scrooloose/nerdcommenter.git +[submodule "vim/bundle/nerdtree"] + path = vim/bundle/nerdtree + url = git://github.com/scrooloose/nerdtree.git +[submodule "vim/bundle/SearchComplete"] + path = vim/bundle/SearchComplete + url = git://github.com/vim-scripts/SearchComplete.git +[submodule "vim/bundle/ZoomWin"] + path = vim/bundle/ZoomWin + url = git://github.com/vim-scripts/ZoomWin.git +[submodule "vim/bundle/ag.vim"] + path = vim/bundle/ag.vim + url = git://github.com/rking/ag.vim.git +[submodule "vim/bundle/Colour-Sampler-Pack"] + path = vim/bundle/Colour-Sampler-Pack + url = git://github.com/vim-scripts/Colour-Sampler-Pack.git +[submodule "vim/bundle/delimitMate"] + path = vim/bundle/delimitMate + url = git://github.com/Raimondi/delimitMate.git +[submodule "vim/bundle/vim-endwise"] + path = vim/bundle/vim-endwise + url = git://github.com/tpope/vim-endwise.git diff --git a/tmux-powerline b/tmux-powerline new file mode 160000 index 0000000..9a1c6b1 --- /dev/null +++ b/tmux-powerline @@ -0,0 +1 @@ +Subproject commit 9a1c6b12748fa807fbbe0c032e57fe85712a6d47 diff --git a/vim/autoload/Align.vim b/vim/autoload/Align.vim deleted file mode 100644 index bce3542..0000000 --- a/vim/autoload/Align.vim +++ /dev/null @@ -1,1029 +0,0 @@ -" Align: tool to align multiple fields based on one or more separators -" Author: Charles E. Campbell, Jr. -" Date: Mar 03, 2009 -" Version: 35 -" GetLatestVimScripts: 294 1 :AutoInstall: Align.vim -" GetLatestVimScripts: 1066 1 :AutoInstall: cecutil.vim -" Copyright: Copyright (C) 1999-2007 Charles E. Campbell, Jr. {{{1 -" Permission is hereby granted to use and distribute this code, -" with or without modifications, provided that this copyright -" notice is copied with it. Like anything else that's free, -" Align.vim is provided *as is* and comes with no warranty -" of any kind, either expressed or implied. By using this -" plugin, you agree that in no event will the copyright -" holder be liable for any damages resulting from the use -" of this software. -" -" Romans 1:16,17a : For I am not ashamed of the gospel of Christ, for it is {{{1 -" the power of God for salvation for everyone who believes; for the Jew first, -" and also for the Greek. For in it is revealed God's righteousness from -" faith to faith. - -" --------------------------------------------------------------------- -" Load Once: {{{1 -if exists("g:loaded_Align") || &cp - finish -endif -let g:loaded_Align = "v35" -if v:version < 700 - echohl WarningMsg - echo "***warning*** this version of Align needs vim 7.0" - echohl Normal - finish -endif -let s:keepcpo= &cpo -set cpo&vim -"DechoTabOn - -" --------------------------------------------------------------------- -" Debugging Support: {{{1 -"if !exists("g:loaded_Decho") | runtime plugin/Decho.vim | endif - -" --------------------------------------------------------------------- -" Options: {{{1 -if !exists("g:Align_xstrlen") - if &enc == "latin1" || $LANG == "en_US.UTF-8" || !has("multi_byte") - let g:Align_xstrlen= 0 - else - let g:Align_xstrlen= 1 - endif -endif - -" --------------------------------------------------------------------- -" Align#AlignCtrl: enter alignment patterns here {{{1 -" -" Styles = all alignment-break patterns are equivalent -" C cycle through alignment-break pattern(s) -" l left-justified alignment -" r right-justified alignment -" c center alignment -" - skip separator, treat as part of field -" : treat rest of line as field -" + repeat previous [lrc] style -" < left justify separators -" > right justify separators -" | center separators -" -" Builds = s:AlignPat s:AlignCtrl s:AlignPatQty -" C s:AlignPat s:AlignCtrl s:AlignPatQty -" p s:AlignPrePad -" P s:AlignPostPad -" w s:AlignLeadKeep -" W s:AlignLeadKeep -" I s:AlignLeadKeep -" l s:AlignStyle -" r s:AlignStyle -" - s:AlignStyle -" + s:AlignStyle -" : s:AlignStyle -" c s:AlignStyle -" g s:AlignGPat -" v s:AlignVPat -" < s:AlignSep -" > s:AlignSep -" | s:AlignSep -fun! Align#AlignCtrl(...) - -" call Dfunc("AlignCtrl(...) a:0=".a:0) - - " save options that will be changed - let keep_search = @/ - let keep_ic = &ic - - " turn ignorecase off - set noic - - " clear visual mode so that old visual-mode selections don't - " get applied to new invocations of Align(). - if v:version < 602 - if !exists("s:Align_gavemsg") - let s:Align_gavemsg= 1 - echomsg "Align needs at least Vim version 6.2 to clear visual-mode selection" - endif - elseif exists("s:dovisclear") -" call Decho("clearing visual mode a:0=".a:0." a:1<".a:1.">") - let clearvmode= visualmode(1) - endif - - " set up a list akin to an argument list - if a:0 > 0 - let A= s:QArgSplitter(a:1) - else - let A=[0] - endif - - if A[0] > 0 - let style = A[1] - - " Check for bad separator patterns (zero-length matches) - " (but zero-length patterns for g/v is ok) - if style !~# '[gv]' - let ipat= 2 - while ipat <= A[0] - if "" =~ A[ipat] - echoerr "AlignCtrl: separator<".A[ipat]."> matches zero-length string" - let &ic= keep_ic -" call Dret("AlignCtrl") - return - endif - let ipat= ipat + 1 - endwhile - endif - endif - -" call Decho("AlignCtrl() A[0]=".A[0]) - if !exists("s:AlignStyle") - let s:AlignStyle= "l" - endif - if !exists("s:AlignPrePad") - let s:AlignPrePad= 0 - endif - if !exists("s:AlignPostPad") - let s:AlignPostPad= 0 - endif - if !exists("s:AlignLeadKeep") - let s:AlignLeadKeep= 'w' - endif - - if A[0] == 0 - " ---------------------- - " List current selection - " ---------------------- - if !exists("s:AlignPatQty") - let s:AlignPatQty= 0 - endif - echo "AlignCtrl<".s:AlignCtrl."> qty=".s:AlignPatQty." AlignStyle<".s:AlignStyle."> Padding<".s:AlignPrePad."|".s:AlignPostPad."> LeadingWS=".s:AlignLeadKeep." AlignSep=".s:AlignSep -" call Decho("AlignCtrl<".s:AlignCtrl."> qty=".s:AlignPatQty." AlignStyle<".s:AlignStyle."> Padding<".s:AlignPrePad."|".s:AlignPostPad."> LeadingWS=".s:AlignLeadKeep." AlignSep=".s:AlignSep) - if exists("s:AlignGPat") && !exists("s:AlignVPat") - echo "AlignGPat<".s:AlignGPat.">" - elseif !exists("s:AlignGPat") && exists("s:AlignVPat") - echo "AlignVPat<".s:AlignVPat.">" - elseif exists("s:AlignGPat") && exists("s:AlignVPat") - echo "AlignGPat<".s:AlignGPat."> AlignVPat<".s:AlignVPat.">" - endif - let ipat= 1 - while ipat <= s:AlignPatQty - echo "Pat".ipat."<".s:AlignPat_{ipat}.">" -" call Decho("Pat".ipat."<".s:AlignPat_{ipat}.">") - let ipat= ipat + 1 - endwhile - - else - " ---------------------------------- - " Process alignment control settings - " ---------------------------------- -" call Decho("process the alignctrl settings") -" call Decho("style<".style.">") - - if style ==? "default" - " Default: preserve initial leading whitespace, left-justified, - " alignment on '=', one space padding on both sides - if exists("s:AlignCtrlStackQty") - " clear AlignCtrl stack - while s:AlignCtrlStackQty > 0 - call Align#AlignPop() - endwhile - unlet s:AlignCtrlStackQty - endif - " Set AlignCtrl to its default value - call Align#AlignCtrl("Ilp1P1=<",'=') - call Align#AlignCtrl("g") - call Align#AlignCtrl("v") - let s:dovisclear = 1 - let &ic = keep_ic - let @/ = keep_search -" call Dret("AlignCtrl") - return - endif - - if style =~# 'm' - " map support: Do an AlignPush now and the next call to Align() - " will do an AlignPop at exit -" call Decho("style case m: do AlignPush") - call Align#AlignPush() - let s:DoAlignPop= 1 - endif - - " = : record a list of alignment patterns that are equivalent - if style =~# "=" -" call Decho("style case =: record list of equiv alignment patterns") - let s:AlignCtrl = '=' - if A[0] >= 2 - let s:AlignPatQty= 1 - let s:AlignPat_1 = A[2] - let ipat = 3 - while ipat <= A[0] - let s:AlignPat_1 = s:AlignPat_1.'\|'.A[ipat] - let ipat = ipat + 1 - endwhile - let s:AlignPat_1= '\('.s:AlignPat_1.'\)' -" call Decho("AlignCtrl<".s:AlignCtrl."> AlignPat<".s:AlignPat_1.">") - endif - - "c : cycle through alignment pattern(s) - elseif style =~# 'C' -" call Decho("style case C: cycle through alignment pattern(s)") - let s:AlignCtrl = 'C' - if A[0] >= 2 - let s:AlignPatQty= A[0] - 1 - let ipat = 1 - while ipat < A[0] - let s:AlignPat_{ipat}= A[ipat+1] -" call Decho("AlignCtrl<".s:AlignCtrl."> AlignQty=".s:AlignPatQty." AlignPat_".ipat."<".s:AlignPat_{ipat}.">") - let ipat= ipat + 1 - endwhile - endif - endif - - if style =~# 'p' - let s:AlignPrePad= substitute(style,'^.*p\(\d\+\).*$','\1','') -" call Decho("style case p".s:AlignPrePad.": pre-separator padding") - if s:AlignPrePad == "" - echoerr "AlignCtrl: 'p' needs to be followed by a numeric argument' - let @/ = keep_search - let &ic= keep_ic -" call Dret("AlignCtrl") - return - endif - endif - - if style =~# 'P' - let s:AlignPostPad= substitute(style,'^.*P\(\d\+\).*$','\1','') -" call Decho("style case P".s:AlignPostPad.": post-separator padding") - if s:AlignPostPad == "" - echoerr "AlignCtrl: 'P' needs to be followed by a numeric argument' - let @/ = keep_search - let &ic= keep_ic -" call Dret("AlignCtrl") - return - endif - endif - - if style =~# 'w' -" call Decho("style case w: ignore leading whitespace") - let s:AlignLeadKeep= 'w' - elseif style =~# 'W' -" call Decho("style case w: keep leading whitespace") - let s:AlignLeadKeep= 'W' - elseif style =~# 'I' -" call Decho("style case w: retain initial leading whitespace") - let s:AlignLeadKeep= 'I' - endif - - if style =~# 'g' - " first list item is a "g" selector pattern -" call Decho("style case g: global selector pattern") - if A[0] < 2 - if exists("s:AlignGPat") - unlet s:AlignGPat -" call Decho("unlet s:AlignGPat") - endif - else - let s:AlignGPat= A[2] -" call Decho("s:AlignGPat<".s:AlignGPat.">") - endif - elseif style =~# 'v' - " first list item is a "v" selector pattern -" call Decho("style case v: global selector anti-pattern") - if A[0] < 2 - if exists("s:AlignVPat") - unlet s:AlignVPat -" call Decho("unlet s:AlignVPat") - endif - else - let s:AlignVPat= A[2] -" call Decho("s:AlignVPat<".s:AlignVPat.">") - endif - endif - - "[-lrc+:] : set up s:AlignStyle - if style =~# '[-lrc+:]' -" call Decho("style case [-lrc+:]: field justification") - let s:AlignStyle= substitute(style,'[^-lrc:+]','','g') -" call Decho("AlignStyle<".s:AlignStyle.">") - endif - - "[<>|] : set up s:AlignSep - if style =~# '[<>|]' -" call Decho("style case [-lrc+:]: separator justification") - let s:AlignSep= substitute(style,'[^<>|]','','g') -" call Decho("AlignSep ".s:AlignSep) - endif - endif - - " sanity - if !exists("s:AlignCtrl") - let s:AlignCtrl= '=' - endif - - " restore search and options - let @/ = keep_search - let &ic= keep_ic - -" call Dret("AlignCtrl ".s:AlignCtrl.'p'.s:AlignPrePad.'P'.s:AlignPostPad.s:AlignLeadKeep.s:AlignStyle) - return s:AlignCtrl.'p'.s:AlignPrePad.'P'.s:AlignPostPad.s:AlignLeadKeep.s:AlignStyle -endfun - -" --------------------------------------------------------------------- -" s:MakeSpace: returns a string with spacecnt blanks {{{1 -fun! s:MakeSpace(spacecnt) -" call Dfunc("MakeSpace(spacecnt=".a:spacecnt.")") - let str = "" - let spacecnt = a:spacecnt - while spacecnt > 0 - let str = str . " " - let spacecnt = spacecnt - 1 - endwhile -" call Dret("MakeSpace <".str.">") - return str -endfun - -" --------------------------------------------------------------------- -" Align#Align: align selected text based on alignment pattern(s) {{{1 -fun! Align#Align(hasctrl,...) range -" call Dfunc("Align#Align(hasctrl=".a:hasctrl.",...) a:0=".a:0) - - " sanity checks - if string(a:hasctrl) != "0" && string(a:hasctrl) != "1" - echohl Error|echo 'usage: Align#Align(hasctrl<'.a:hasctrl.'> (should be 0 or 1),"separator(s)" (you have '.a:0.') )'|echohl None -" call Dret("Align#Align") - return - endif - if exists("s:AlignStyle") && s:AlignStyle == ":" - echohl Error |echo '(Align#Align) your AlignStyle is ":", which implies "do-no-alignment"!'|echohl None -" call Dret("Align#Align") - return - endif - - " set up a list akin to an argument list - if a:0 > 0 - let A= s:QArgSplitter(a:1) - else - let A=[0] - endif - - " if :Align! was used, then the first argument is (should be!) an AlignCtrl string - " Note that any alignment control set this way will be temporary. - let hasctrl= a:hasctrl -" call Decho("hasctrl=".hasctrl) - if a:hasctrl && A[0] >= 1 -" call Decho("Align! : using A[1]<".A[1]."> for AlignCtrl") - if A[1] =~ '[gv]' - let hasctrl= hasctrl + 1 - call Align#AlignCtrl('m') - call Align#AlignCtrl(A[1],A[2]) -" call Decho("Align! : also using A[2]<".A[2]."> for AlignCtrl") - elseif A[1] !~ 'm' - call Align#AlignCtrl(A[1]."m") - else - call Align#AlignCtrl(A[1]) - endif - endif - - " Check for bad separator patterns (zero-length matches) - let ipat= 1 + hasctrl - while ipat <= A[0] - if "" =~ A[ipat] - echoerr "Align: separator<".A[ipat]."> matches zero-length string" -" call Dret("Align#Align") - return - endif - let ipat= ipat + 1 - endwhile - - " record current search pattern for subsequent restoration - let keep_search= @/ - let keep_ic = &ic - let keep_report= &report - set noic report=10000 - - if A[0] > hasctrl - " Align will accept a list of separator regexps -" call Decho("A[0]=".A[0].": accepting list of separator regexp") - - if s:AlignCtrl =~# "=" - "= : consider all separators to be equivalent -" call Decho("AlignCtrl: record list of equivalent alignment patterns") - let s:AlignCtrl = '=' - let s:AlignPat_1 = A[1 + hasctrl] - let s:AlignPatQty= 1 - let ipat = 2 + hasctrl - while ipat <= A[0] - let s:AlignPat_1 = s:AlignPat_1.'\|'.A[ipat] - let ipat = ipat + 1 - endwhile - let s:AlignPat_1= '\('.s:AlignPat_1.'\)' -" call Decho("AlignCtrl<".s:AlignCtrl."> AlignPat<".s:AlignPat_1.">") - - elseif s:AlignCtrl =~# 'C' - "c : cycle through alignment pattern(s) -" call Decho("AlignCtrl: cycle through alignment pattern(s)") - let s:AlignCtrl = 'C' - let s:AlignPatQty= A[0] - hasctrl - let ipat = 1 - while ipat <= s:AlignPatQty - let s:AlignPat_{ipat}= A[(ipat + hasctrl)] -" call Decho("AlignCtrl<".s:AlignCtrl."> AlignQty=".s:AlignPatQty." AlignPat_".ipat."<".s:AlignPat_{ipat}.">") - let ipat= ipat + 1 - endwhile - endif - endif - - " Initialize so that begline - " is greater than the line's string length -> ragged right. - " Have to be careful about visualmode() -- it returns the last visual - " mode used whether or not it was used currently. - let begcol = virtcol("'<")-1 - let endcol = virtcol("'>")-1 - if begcol > endcol - let begcol = virtcol("'>")-1 - let endcol = virtcol("'<")-1 - endif -" call Decho("begcol=".begcol." endcol=".endcol) - let begline = a:firstline - let endline = a:lastline - if begline > endline - let begline = a:lastline - let endline = a:firstline - endif -" call Decho("begline=".begline." endline=".endline) - let fieldcnt = 0 - if (begline == line("'>") && endline == line("'<")) || (begline == line("'<") && endline == line("'>")) - let vmode= visualmode() -" call Decho("vmode=".vmode) - if vmode == "\" - if exists("g:Align_xstrlen") && g:Align_xstrlen - let ragged = ( col("'>") > s:Strlen(getline("'>")) || col("'<") > s:Strlen(getline("'<")) ) - else - let ragged = ( col("'>") > strlen(getline("'>")) || col("'<") > strlen(getline("'<")) ) - endif - else - let ragged= 1 - endif - else - let ragged= 1 - endif - if ragged - let begcol= 0 - endif -" call Decho("lines[".begline.",".endline."] col[".begcol.",".endcol."] ragged=".ragged." AlignCtrl<".s:AlignCtrl.">") - - " Keep user options - let etkeep = &l:et - let pastekeep= &l:paste - setlocal et paste - - " convert selected range of lines to use spaces instead of tabs - " but if first line's initial white spaces are to be retained - " then use 'em - if begcol <= 0 && s:AlignLeadKeep == 'I' - " retain first leading whitespace for all subsequent lines - let bgntxt= substitute(getline(begline),'^\(\s*\).\{-}$','\1','') -" call Decho("retaining 1st leading whitespace: bgntxt<".bgntxt.">") - set noet - endif - exe begline.",".endline."ret" - - " Execute two passes - " First pass: collect alignment data (max field sizes) - " Second pass: perform alignment - let pass= 1 - while pass <= 2 -" call Decho(" ") -" call Decho("---- Pass ".pass.": ----") - - let line= begline - while line <= endline - " Process each line - let txt = getline(line) -" call Decho(" ") -" call Decho("Pass".pass.": Line ".line." <".txt.">") - - " AlignGPat support: allows a selector pattern (akin to g/selector/cmd ) - if exists("s:AlignGPat") -" call Decho("Pass".pass.": AlignGPat<".s:AlignGPat.">") - if match(txt,s:AlignGPat) == -1 -" call Decho("Pass".pass.": skipping") - let line= line + 1 - continue - endif - endif - - " AlignVPat support: allows a selector pattern (akin to v/selector/cmd ) - if exists("s:AlignVPat") -" call Decho("Pass".pass.": AlignVPat<".s:AlignVPat.">") - if match(txt,s:AlignVPat) != -1 -" call Decho("Pass".pass.": skipping") - let line= line + 1 - continue - endif - endif - - " Always skip blank lines - if match(txt,'^\s*$') != -1 -" call Decho("Pass".pass.": skipping") - let line= line + 1 - continue - endif - - " Extract visual-block selected text (init bgntxt, endtxt) - if exists("g:Align_xstrlen") && g:Align_xstrlen - let txtlen= s:Strlen(txt) - else - let txtlen= strlen(txt) - endif - if begcol > 0 - " Record text to left of selected area - let bgntxt= strpart(txt,0,begcol) -" call Decho("Pass".pass.": record text to left: bgntxt<".bgntxt.">") - elseif s:AlignLeadKeep == 'W' - let bgntxt= substitute(txt,'^\(\s*\).\{-}$','\1','') -" call Decho("Pass".pass.": retaining all leading ws: bgntxt<".bgntxt.">") - elseif s:AlignLeadKeep == 'w' || !exists("bgntxt") - " No beginning text - let bgntxt= "" -" call Decho("Pass".pass.": no beginning text") - endif - if ragged - let endtxt= "" - else - " Elide any text lying outside selected columnar region - let endtxt= strpart(txt,endcol+1,txtlen-endcol) - let txt = strpart(txt,begcol,endcol-begcol+1) - endif -" call Decho(" ") -" call Decho("Pass".pass.": bgntxt<".bgntxt.">") -" call Decho("Pass".pass.": txt<". txt .">") -" call Decho("Pass".pass.": endtxt<".endtxt.">") - if !exists("s:AlignPat_{1}") - echohl Error|echo "no separators specified!"|echohl None -" call Dret("Align#Align") - return - endif - - " Initialize for both passes - let seppat = s:AlignPat_{1} - let ifield = 1 - let ipat = 1 - let bgnfield = 0 - let endfield = 0 - let alignstyle = s:AlignStyle - let doend = 1 - let newtxt = "" - let alignprepad = s:AlignPrePad - let alignpostpad= s:AlignPostPad - let alignsep = s:AlignSep - let alignophold = " " - let alignop = "l" -" call Decho("Pass".pass.": initial alignstyle<".alignstyle."> seppat<".seppat.">") - - " Process each field on the line - while doend > 0 - - " C-style: cycle through pattern(s) - if s:AlignCtrl == 'C' && doend == 1 - let seppat = s:AlignPat_{ipat} -" call Decho("Pass".pass.": processing field: AlignCtrl=".s:AlignCtrl." ipat=".ipat." seppat<".seppat.">") - let ipat = ipat + 1 - if ipat > s:AlignPatQty - let ipat = 1 - endif - endif - - " cyclic alignment/justification operator handling - let alignophold = alignop - let alignop = strpart(alignstyle,0,1) - if alignop == '+' || doend == 2 - let alignop= alignophold - else - let alignstyle = strpart(alignstyle,1).strpart(alignstyle,0,1) - let alignopnxt = strpart(alignstyle,0,1) - if alignop == ':' - let seppat = '$' - let doend = 2 -" call Decho("Pass".pass.": alignop<:> case: setting seppat<$> doend==2") - endif - endif - - " cylic separator alignment specification handling - let alignsepop= strpart(alignsep,0,1) - let alignsep = strpart(alignsep,1).alignsepop - - " mark end-of-field and the subsequent end-of-separator. - " Extend field if alignop is '-' - let endfield = match(txt,seppat,bgnfield) - let sepfield = matchend(txt,seppat,bgnfield) - let skipfield= sepfield -" call Decho("Pass".pass.": endfield=match(txt<".txt.">,seppat<".seppat.">,bgnfield=".bgnfield.")=".endfield) - while alignop == '-' && endfield != -1 - let endfield = match(txt,seppat,skipfield) - let sepfield = matchend(txt,seppat,skipfield) - let skipfield = sepfield - let alignop = strpart(alignstyle,0,1) - let alignstyle= strpart(alignstyle,1).strpart(alignstyle,0,1) -" call Decho("Pass".pass.": extend field: endfield<".strpart(txt,bgnfield,endfield-bgnfield)."> alignop<".alignop."> alignstyle<".alignstyle.">") - endwhile - let seplen= sepfield - endfield -" call Decho("Pass".pass.": seplen=[sepfield=".sepfield."] - [endfield=".endfield."]=".seplen) - - if endfield != -1 - if pass == 1 - " --------------------------------------------------------------------- - " Pass 1: Update FieldSize to max -" call Decho("Pass".pass.": before lead/trail remove: field<".strpart(txt,bgnfield,endfield-bgnfield).">") - let field = substitute(strpart(txt,bgnfield,endfield-bgnfield),'^\s*\(.\{-}\)\s*$','\1','') - if s:AlignLeadKeep == 'W' - let field = bgntxt.field - let bgntxt= "" - endif - if exists("g:Align_xstrlen") && g:Align_xstrlen - let fieldlen = s:Strlen(field) - else - let fieldlen = strlen(field) - endif - let sFieldSize = "FieldSize_".ifield - if !exists(sFieldSize) - let FieldSize_{ifield}= fieldlen -" call Decho("Pass".pass.": set FieldSize_{".ifield."}=".FieldSize_{ifield}." <".field.">") - elseif fieldlen > FieldSize_{ifield} - let FieldSize_{ifield}= fieldlen -" call Decho("Pass".pass.": oset FieldSize_{".ifield."}=".FieldSize_{ifield}." <".field.">") - endif - let sSepSize= "SepSize_".ifield - if !exists(sSepSize) - let SepSize_{ifield}= seplen -" call Decho(" set SepSize_{".ifield."}=".SepSize_{ifield}." <".field.">") - elseif seplen > SepSize_{ifield} - let SepSize_{ifield}= seplen -" call Decho("Pass".pass.": oset SepSize_{".ifield."}=".SepSize_{ifield}." <".field.">") - endif - - else - " --------------------------------------------------------------------- - " Pass 2: Perform Alignment - let prepad = strpart(alignprepad,0,1) - let postpad = strpart(alignpostpad,0,1) - let alignprepad = strpart(alignprepad,1).strpart(alignprepad,0,1) - let alignpostpad = strpart(alignpostpad,1).strpart(alignpostpad,0,1) - let field = substitute(strpart(txt,bgnfield,endfield-bgnfield),'^\s*\(.\{-}\)\s*$','\1','') - if s:AlignLeadKeep == 'W' - let field = bgntxt.field - let bgntxt= "" - endif - if doend == 2 - let prepad = 0 - let postpad= 0 - endif - if exists("g:Align_xstrlen") && g:Align_xstrlen - let fieldlen = s:Strlen(field) - else - let fieldlen = strlen(field) - endif - let sep = s:MakeSpace(prepad).strpart(txt,endfield,sepfield-endfield).s:MakeSpace(postpad) - if seplen < SepSize_{ifield} - if alignsepop == "<" - " left-justify separators - let sep = sep.s:MakeSpace(SepSize_{ifield}-seplen) - elseif alignsepop == ">" - " right-justify separators - let sep = s:MakeSpace(SepSize_{ifield}-seplen).sep - else - " center-justify separators - let sepleft = (SepSize_{ifield} - seplen)/2 - let sepright = SepSize_{ifield} - seplen - sepleft - let sep = s:MakeSpace(sepleft).sep.s:MakeSpace(sepright) - endif - endif - let spaces = FieldSize_{ifield} - fieldlen -" call Decho("Pass".pass.": Field #".ifield."<".field."> spaces=".spaces." be[".bgnfield.",".endfield."] pad=".prepad.','.postpad." FS_".ifield."<".FieldSize_{ifield}."> sep<".sep."> ragged=".ragged." doend=".doend." alignop<".alignop.">") - - " Perform alignment according to alignment style justification - if spaces > 0 - if alignop == 'c' - " center the field - let spaceleft = spaces/2 - let spaceright= FieldSize_{ifield} - spaceleft - fieldlen - let newtxt = newtxt.s:MakeSpace(spaceleft).field.s:MakeSpace(spaceright).sep - elseif alignop == 'r' - " right justify the field - let newtxt= newtxt.s:MakeSpace(spaces).field.sep - elseif ragged && doend == 2 - " left justify rightmost field (no trailing blanks needed) - let newtxt= newtxt.field - else - " left justfiy the field - let newtxt= newtxt.field.s:MakeSpace(spaces).sep - endif - elseif ragged && doend == 2 - " field at maximum field size and no trailing blanks needed - let newtxt= newtxt.field - else - " field is at maximum field size already - let newtxt= newtxt.field.sep - endif -" call Decho("Pass".pass.": newtxt<".newtxt.">") - endif " pass 1/2 - - " bgnfield indexes to end of separator at right of current field - " Update field counter - let bgnfield= sepfield - let ifield = ifield + 1 - if doend == 2 - let doend= 0 - endif - " handle end-of-text as end-of-field - elseif doend == 1 - let seppat = '$' - let doend = 2 - else - let doend = 0 - endif " endfield != -1 - endwhile " doend loop (as well as regularly separated fields) - - if pass == 2 - " Write altered line to buffer -" call Decho("Pass".pass.": bgntxt<".bgntxt."> line=".line) -" call Decho("Pass".pass.": newtxt<".newtxt.">") -" call Decho("Pass".pass.": endtxt<".endtxt.">") - call setline(line,bgntxt.newtxt.endtxt) - endif - - let line = line + 1 - endwhile " line loop - - let pass= pass + 1 - endwhile " pass loop -" call Decho("end of two pass loop") - - " Restore user options - let &l:et = etkeep - let &l:paste = pastekeep - - if exists("s:DoAlignPop") - " AlignCtrl Map support - call Align#AlignPop() - unlet s:DoAlignPop - endif - - " restore current search pattern - let @/ = keep_search - let &ic = keep_ic - let &report = keep_report - -" call Dret("Align#Align") - return -endfun - -" --------------------------------------------------------------------- -" Align#AlignPush: this command/function pushes an alignment control string onto a stack {{{1 -fun! Align#AlignPush() -" call Dfunc("AlignPush()") - - " initialize the stack - if !exists("s:AlignCtrlStackQty") - let s:AlignCtrlStackQty= 1 - else - let s:AlignCtrlStackQty= s:AlignCtrlStackQty + 1 - endif - - " construct an AlignCtrlStack entry - if !exists("s:AlignSep") - let s:AlignSep= '' - endif - let s:AlignCtrlStack_{s:AlignCtrlStackQty}= s:AlignCtrl.'p'.s:AlignPrePad.'P'.s:AlignPostPad.s:AlignLeadKeep.s:AlignStyle.s:AlignSep -" call Decho("AlignPush: AlignCtrlStack_".s:AlignCtrlStackQty."<".s:AlignCtrlStack_{s:AlignCtrlStackQty}.">") - - " push [GV] patterns onto their own stack - if exists("s:AlignGPat") - let s:AlignGPat_{s:AlignCtrlStackQty}= s:AlignGPat - else - let s:AlignGPat_{s:AlignCtrlStackQty}= "" - endif - if exists("s:AlignVPat") - let s:AlignVPat_{s:AlignCtrlStackQty}= s:AlignVPat - else - let s:AlignVPat_{s:AlignCtrlStackQty}= "" - endif - -" call Dret("AlignPush") -endfun - -" --------------------------------------------------------------------- -" Align#AlignPop: this command/function pops an alignment pattern from a stack {{{1 -" and into the AlignCtrl variables. -fun! Align#AlignPop() -" call Dfunc("Align#AlignPop()") - - " sanity checks - if !exists("s:AlignCtrlStackQty") - echoerr "AlignPush needs to be used prior to AlignPop" -" call Dret("Align#AlignPop <> : AlignPush needs to have been called first") - return "" - endif - if s:AlignCtrlStackQty <= 0 - unlet s:AlignCtrlStackQty - echoerr "AlignPush needs to be used prior to AlignPop" -" call Dret("Align#AlignPop <> : AlignPop needs to have been called first") - return "" - endif - - " pop top of AlignCtrlStack and pass value to AlignCtrl - let retval=s:AlignCtrlStack_{s:AlignCtrlStackQty} - unlet s:AlignCtrlStack_{s:AlignCtrlStackQty} - call Align#AlignCtrl(retval) - - " pop G pattern stack - if s:AlignGPat_{s:AlignCtrlStackQty} != "" - call Align#AlignCtrl('g',s:AlignGPat_{s:AlignCtrlStackQty}) - else - call Align#AlignCtrl('g') - endif - unlet s:AlignGPat_{s:AlignCtrlStackQty} - - " pop V pattern stack - if s:AlignVPat_{s:AlignCtrlStackQty} != "" - call Align#AlignCtrl('v',s:AlignVPat_{s:AlignCtrlStackQty}) - else - call Align#AlignCtrl('v') - endif - - unlet s:AlignVPat_{s:AlignCtrlStackQty} - let s:AlignCtrlStackQty= s:AlignCtrlStackQty - 1 - -" call Dret("Align#AlignPop <".retval."> : AlignCtrlStackQty=".s:AlignCtrlStackQty) - return retval -endfun - -" --------------------------------------------------------------------- -" Align#AlignReplaceQuotedSpaces: {{{1 -fun! Align#AlignReplaceQuotedSpaces() -" call Dfunc("AlignReplaceQuotedSpaces()") - - let l:line = getline(line(".")) - if exists("g:Align_xstrlen") && g:Align_xstrlen - let l:linelen = s:Strlen(l:line) - else - let l:linelen = strlen(l:line) - endif - let l:startingPos = 0 - let l:startQuotePos = 0 - let l:endQuotePos = 0 - let l:spacePos = 0 - let l:quoteRe = '\\\@, is needed. {{{1 -" However, doesn't split at all, so this function returns a list -" of arguments which has been: -" * split at whitespace -" * unless inside "..."s. One may escape characters with a backslash inside double quotes. -" along with a leading length-of-list. -" -" Examples: %Align "\"" will align on "s -" %Align " " will align on spaces -" -" The resulting list: qarglist[0] corresponds to a:0 -" qarglist[i] corresponds to a:{i} -fun! s:QArgSplitter(qarg) -" call Dfunc("s:QArgSplitter(qarg<".a:qarg.">)") - - if a:qarg =~ '".*"' - " handle "..." args, which may include whitespace - let qarglist = [] - let args = a:qarg -" call Decho("handle quoted arguments: args<".args.">") - while args != "" - let iarg = 0 - let arglen = strlen(args) -" call Decho("args[".iarg."]<".args[iarg]."> arglen=".arglen) - " find index to first not-escaped '"' - while args[iarg] != '"' && iarg < arglen - if args[iarg] == '\' - let args= strpart(args,1) - endif - let iarg= iarg + 1 - endwhile -" call Decho("args<".args."> iarg=".iarg." arglen=".arglen) - - if iarg > 0 - " handle left of quote or remaining section -" call Decho("handle left of quote or remaining section") - if args[iarg] == '"' - let qarglist= qarglist + split(strpart(args,0,iarg-1)) - else - let qarglist= qarglist + split(strpart(args,0,iarg)) - endif - let args = strpart(args,iarg) - let arglen = strlen(args) - - elseif iarg < arglen && args[0] == '"' - " handle "quoted" section -" call Decho("handle quoted section") - let iarg= 1 - while args[iarg] != '"' && iarg < arglen - if args[iarg] == '\' - let args= strpart(args,1) - endif - let iarg= iarg + 1 - endwhile -" call Decho("args<".args."> iarg=".iarg." arglen=".arglen) - if args[iarg] == '"' - call add(qarglist,strpart(args,1,iarg-1)) - let args= strpart(args,iarg+1) - else - let qarglist = qarglist + split(args) - let args = "" - endif - endif -" call Decho("qarglist".string(qarglist)." iarg=".iarg." args<".args.">") - endwhile - - else - " split at all whitespace - let qarglist= split(a:qarg) - endif - - let qarglistlen= len(qarglist) - let qarglist = insert(qarglist,qarglistlen) -" call Dret("s:QArgSplitter ".string(qarglist)) - return qarglist -endfun - -" --------------------------------------------------------------------- -" s:Strlen: this function returns the length of a string, even if its {{{1 -" using two-byte etc characters. -" Currently, its only used if g:Align_xstrlen is set to a -" nonzero value. Solution from Nicolai Weibull, vim docs -" (:help strlen()), Tony Mechelynck, and my own invention. -fun! s:Strlen(x) -" call Dfunc("s:Strlen(x<".a:x.">") - if g:Align_xstrlen == 1 - " number of codepoints (Latin a + combining circumflex is two codepoints) - " (comment from TM, solution from NW) - let ret= strlen(substitute(a:x,'.','c','g')) - - elseif g:Align_xstrlen == 2 - " number of spacing codepoints (Latin a + combining circumflex is one spacing - " codepoint; a hard tab is one; wide and narrow CJK are one each; etc.) - " (comment from TM, solution from TM) - let ret=strlen(substitute(a:x, '.\Z', 'x', 'g')) - - elseif g:Align_xstrlen == 3 - " virtual length (counting, for instance, tabs as anything between 1 and - " 'tabstop', wide CJK as 2 rather than 1, Arabic alif as zero when immediately - " preceded by lam, one otherwise, etc.) - " (comment from TM, solution from me) - let modkeep= &l:mod - exe "norm! o\" - call setline(line("."),a:x) - let ret= virtcol("$") - 1 - d - let &l:mod= modkeep - - else - " at least give a decent default - ret= strlen(a:x) - endif -" call Dret("s:Strlen ".ret) - return ret -endfun - -" --------------------------------------------------------------------- -" Set up default values: {{{1 -"call Decho("-- Begin AlignCtrl Initialization --") -call Align#AlignCtrl("default") -"call Decho("-- End AlignCtrl Initialization --") - -" --------------------------------------------------------------------- -" Restore: {{{1 -let &cpo= s:keepcpo -unlet s:keepcpo -" vim: ts=4 fdm=marker diff --git a/vim/autoload/AlignMaps.vim b/vim/autoload/AlignMaps.vim deleted file mode 100644 index ace2de8..0000000 --- a/vim/autoload/AlignMaps.vim +++ /dev/null @@ -1,330 +0,0 @@ -" AlignMaps.vim : support functions for AlignMaps -" Author: Charles E. Campbell, Jr. -" Date: Mar 03, 2009 -" Version: 41 -" --------------------------------------------------------------------- -" Load Once: {{{1 -if &cp || exists("g:loaded_AlignMaps") - finish -endif -let g:loaded_AlignMaps= "v41" -let s:keepcpo = &cpo -set cpo&vim - -" ===================================================================== -" Functions: {{{1 - -" --------------------------------------------------------------------- -" AlignMaps#WrapperStart: {{{2 -fun! AlignMaps#WrapperStart(vis) range -" call Dfunc("AlignMaps#WrapperStart(vis=".a:vis.")") - - if a:vis - norm! ' - endif - - if line("'y") == 0 || line("'z") == 0 || !exists("s:alignmaps_wrapcnt") || s:alignmaps_wrapcnt <= 0 -" call Decho("wrapper initialization") - let s:alignmaps_wrapcnt = 1 - let s:alignmaps_keepgd = &gdefault - let s:alignmaps_keepsearch = @/ - let s:alignmaps_keepch = &ch - let s:alignmaps_keepmy = SaveMark("'y") - let s:alignmaps_keepmz = SaveMark("'z") - let s:alignmaps_posn = SaveWinPosn(0) - " set up fencepost blank lines - put ='' - norm! mz'a - put! ='' - ky - let s:alignmaps_zline = line("'z") - exe "'y,'zs/@/\177/ge" - else -" call Decho("embedded wrapper") - let s:alignmaps_wrapcnt = s:alignmaps_wrapcnt + 1 - norm! 'yjma'zk - endif - - " change some settings to align-standard values - set nogd - set ch=2 - AlignPush - norm! 'zk -" call Dret("AlignMaps#WrapperStart : alignmaps_wrapcnt=".s:alignmaps_wrapcnt." my=".line("'y")." mz=".line("'z")) -endfun - -" --------------------------------------------------------------------- -" AlignMaps#WrapperEnd: {{{2 -fun! AlignMaps#WrapperEnd() range -" call Dfunc("AlignMaps#WrapperEnd() alignmaps_wrapcnt=".s:alignmaps_wrapcnt." my=".line("'y")." mz=".line("'z")) - - " remove trailing white space introduced by whatever in the modification zone - 'y,'zs/ \+$//e - - " restore AlignCtrl settings - AlignPop - - let s:alignmaps_wrapcnt= s:alignmaps_wrapcnt - 1 - if s:alignmaps_wrapcnt <= 0 - " initial wrapper ending - exe "'y,'zs/\177/@/ge" - - " if the 'z line hasn't moved, then go ahead and restore window position - let zstationary= s:alignmaps_zline == line("'z") - - " remove fencepost blank lines. - " restore 'a - norm! 'yjmakdd'zdd - - " restore original 'y, 'z, and window positioning - call RestoreMark(s:alignmaps_keepmy) - call RestoreMark(s:alignmaps_keepmz) - if zstationary > 0 - call RestoreWinPosn(s:alignmaps_posn) -" call Decho("restored window positioning") - endif - - " restoration of options - let &gd= s:alignmaps_keepgd - let &ch= s:alignmaps_keepch - let @/ = s:alignmaps_keepsearch - - " remove script variables - unlet s:alignmaps_keepch - unlet s:alignmaps_keepsearch - unlet s:alignmaps_keepmy - unlet s:alignmaps_keepmz - unlet s:alignmaps_keepgd - unlet s:alignmaps_posn - endif - -" call Dret("AlignMaps#WrapperEnd : alignmaps_wrapcnt=".s:alignmaps_wrapcnt." my=".line("'y")." mz=".line("'z")) -endfun - -" --------------------------------------------------------------------- -" AlignMaps#StdAlign: some semi-standard align calls {{{2 -fun! AlignMaps#StdAlign(mode) range -" call Dfunc("AlignMaps#StdAlign(mode=".a:mode.")") - if a:mode == 1 - " align on @ -" call Decho("align on @") - AlignCtrl mIp1P1=l @ - 'a,.Align - elseif a:mode == 2 - " align on @, retaining all initial white space on each line -" call Decho("align on @, retaining all initial white space on each line") - AlignCtrl mWp1P1=l @ - 'a,.Align - elseif a:mode == 3 - " like mode 2, but ignore /* */-style comments -" call Decho("like mode 2, but ignore /* */-style comments") - AlignCtrl v ^\s*/[/*] - AlignCtrl mWp1P1=l @ - 'a,.Align - else - echoerr "(AlignMaps) AlignMaps#StdAlign doesn't support mode#".a:mode - endif -" call Dret("AlignMaps#StdAlign") -endfun - -" --------------------------------------------------------------------- -" AlignMaps#CharJoiner: joins lines which end in the given character (spaces {{{2 -" at end are ignored) -fun! AlignMaps#CharJoiner(chr) -" call Dfunc("AlignMaps#CharJoiner(chr=".a:chr.")") - let aline = line("'a") - let rep = line(".") - aline - while rep > 0 - norm! 'a - while match(getline(aline),a:chr . "\s*$") != -1 && rep >= 0 - " while = at end-of-line, delete it and join with next - norm! 'a$ - j! - let rep = rep - 1 - endwhile - " update rep(eat) count - let rep = rep - 1 - if rep <= 0 - " terminate loop if at end-of-block - break - endif - " prepare for next line - norm! jma - let aline = line("'a") - endwhile -" call Dret("AlignMaps#CharJoiner") -endfun - -" --------------------------------------------------------------------- -" AlignMaps#Equals: supports \t= and \T= {{{2 -fun! AlignMaps#Equals() range -" call Dfunc("AlignMaps#Equals()") - 'a,'zs/\s\+\([*/+\-%|&\~^]\==\)/ \1/e - 'a,'zs@ \+\([*/+\-%|&\~^]\)=@\1=@ge - 'a,'zs/==/\="\\"/ge - 'a,'zs/\([!<>:]\)=/\=submatch(1)."\"/ge - norm g'zk - AlignCtrl mIp1P1=l = - AlignCtrl g = - 'a,'z-1Align - 'a,'z-1s@\([*/+\-%|&\~^!=]\)\( \+\)=@\2\1=@ge - 'a,'z-1s/\( \+\);/;\1/ge - if &ft == "c" || &ft == "cpp" -" call Decho("exception for ".&ft) - 'a,'z-1v/^\s*\/[*/]/s/\/[*/]/@&@/e - 'a,'z-1v/^\s*\/[*/]/s/\*\//@&/e - if exists("g:mapleader") - exe "norm 'zk" - call AlignMaps#StdAlign(1) - else - exe "norm 'zk" - call AlignMaps#StdAlign(1) - endif - 'y,'zs/^\(\s*\) @/\1/e - endif - 'a,'z-1s/\%x0f/=/ge - 'y,'zs/ @//eg -" call Dret("AlignMaps#Equals") -endfun - -" --------------------------------------------------------------------- -" AlignMaps#Afnc: useful for splitting one-line function beginnings {{{2 -" into one line per argument format -fun! AlignMaps#Afnc() -" call Dfunc("AlignMaps#Afnc()") - - " keep display quiet - let chkeep = &ch - let gdkeep = &gd - let vekeep = &ve - set ch=2 nogd ve= - - " will use marks y,z ; save current values - let mykeep = SaveMark("'y") - let mzkeep = SaveMark("'z") - - " Find beginning of function -- be careful to skip over comments - let cmmntid = synIDtrans(hlID("Comment")) - let stringid = synIDtrans(hlID("String")) - exe "norm! ]]" - while search(")","bW") != 0 -" call Decho("line=".line(".")." col=".col(".")) - let parenid= synIDtrans(synID(line("."),col("."),1)) - if parenid != cmmntid && parenid != stringid - break - endif - endwhile - norm! %my - s/(\s*\(\S\)/(\r \1/e - exe "norm! `y%" - s/)\s*\(\/[*/]\)/)\r\1/e - exe "norm! `y%mz" - 'y,'zs/\s\+$//e - 'y,'zs/^\s\+//e - 'y+1,'zs/^/ / - - " insert newline after every comma only one parenthesis deep - sil! exe "norm! `y\h" - let parens = 1 - let cmmnt = 0 - let cmmntline= -1 - while parens >= 1 -" call Decho("parens=".parens." @a=".@a) - exe 'norm! ma "ay`a ' - if @a == "(" - let parens= parens + 1 - elseif @a == ")" - let parens= parens - 1 - - " comment bypass: /* ... */ or //... - elseif cmmnt == 0 && @a == '/' - let cmmnt= 1 - elseif cmmnt == 1 - if @a == '/' - let cmmnt = 2 " //... - let cmmntline= line(".") - elseif @a == '*' - let cmmnt= 3 " /*... - else - let cmmnt= 0 - endif - elseif cmmnt == 2 && line(".") != cmmntline - let cmmnt = 0 - let cmmntline= -1 - elseif cmmnt == 3 && @a == '*' - let cmmnt= 4 - elseif cmmnt == 4 - if @a == '/' - let cmmnt= 0 " ...*/ - elseif @a != '*' - let cmmnt= 3 - endif - - elseif @a == "," && parens == 1 && cmmnt == 0 - exe "norm! i\\" - endif - endwhile - norm! `y%mz% - sil! 'y,'zg/^\s*$/d - - " perform substitutes to mark fields for Align - sil! 'y+1,'zv/^\//s/^\s\+\(\S\)/ \1/e - sil! 'y+1,'zv/^\//s/\(\S\)\s\+/\1 /eg - sil! 'y+1,'zv/^\//s/\* \+/*/ge - sil! 'y+1,'zv/^\//s/\w\zs\s*\*/ */ge - " func - " ws <- declaration -> <-ptr -> <-var-> <-[array][] -> <-glop-> <-end-> - sil! 'y+1,'zv/^\//s/^\s*\(\(\K\k*\s*\)\+\)\s\+\([(*]*\)\s*\(\K\k*\)\s*\(\(\[.\{-}]\)*\)\s*\(.\{-}\)\=\s*\([,)]\)\s*$/ \1@#\3@\4\5@\7\8/e - sil! 'y+1,'z+1g/^\s*\/[*/]/norm! kJ - sil! 'y+1,'z+1s%/[*/]%@&@%ge - sil! 'y+1,'z+1s%*/%@&%ge - AlignCtrl mIp0P0=l @ - sil! 'y+1,'zAlign - sil! 'y,'zs%@\(/[*/]\)@%\t\1 %e - sil! 'y,'zs%@\*/% */%e - sil! 'y,'zs/@\([,)]\)/\1/ - sil! 'y,'zs/@/ / - AlignCtrl mIlrp0P0= # @ - sil! 'y+1,'zAlign - sil! 'y+1,'zs/#/ / - sil! 'y+1,'zs/@// - sil! 'y+1,'zs/\(\s\+\)\([,)]\)/\2\1/e - - " Restore - call RestoreMark(mykeep) - call RestoreMark(mzkeep) - let &ch= chkeep - let &gd= gdkeep - let &ve= vekeep - -" call Dret("AlignMaps#Afnc") -endfun - -" --------------------------------------------------------------------- -" AlignMaps#FixMultiDec: converts a type arg,arg,arg; line to multiple lines {{{2 -fun! AlignMaps#FixMultiDec() -" call Dfunc("AlignMaps#FixMultiDec()") - - " save register x - let xkeep = @x - let curline = getline(".") -" call Decho("curline<".curline.">") - - " Get the type. I'm assuming one type per line (ie. int x; double y; on one line will not be handled properly) - let @x=substitute(curline,'^\(\s*[a-zA-Z_ \t][a-zA-Z0-9_ \t]*\)\s\+[(*]*\h.*$','\1','') -" call Decho("@x<".@x.">") - - " transform line - exe 's/,/;\r'.@x.' /ge' - - "restore register x - let @x= xkeep - -" call Dret("AlignMaps#FixMultiDec : my=".line("'y")." mz=".line("'z")) -endfun - -" --------------------------------------------------------------------- -" Restore: {{{1 -let &cpo= s:keepcpo -unlet s:keepcpo -" vim: ts=4 fdm=marker diff --git a/vim/autoload/ZoomWin.vim b/vim/autoload/ZoomWin.vim deleted file mode 100644 index d2d993f..0000000 --- a/vim/autoload/ZoomWin.vim +++ /dev/null @@ -1,380 +0,0 @@ -" ZoomWin: Brief-like ability to zoom into/out-of a window -" Author: Charles Campbell -" original version by Ron Aaron -" Date: Jan 26, 2009 -" Version: 23 -" History: see :help zoomwin-history {{{1 -" GetLatestVimScripts: 508 1 :AutoInstall: ZoomWin.vim - -" --------------------------------------------------------------------- -" Load Once: {{{1 -if &cp || exists("g:loaded_ZoomWin") - finish -endif -if v:version < 702 - echohl WarningMsg - echo "***warning*** this version of ZoomWin needs vim 7.2" - echohl Normal - finish -endif -let s:keepcpo = &cpo -let g:loaded_ZoomWin = "v23" -set cpo&vim -"DechoTabOn - -" ===================================================================== -" Functions: {{{1 - -" --------------------------------------------------------------------- -" ZoomWin#ZoomWin: toggles between a single-window and a multi-window layout {{{2 -" The original version was by Ron Aaron. -fun! ZoomWin#ZoomWin() -" let g:decho_hide= 1 "Decho -" call Dfunc("ZoomWin#ZoomWin() winbufnr(2)=".winbufnr(2)) - - " if the vim doesn't have +mksession, only a partial zoom is available {{{3 - if !has("mksession") - if !exists("s:partialzoom") - echomsg "missing the +mksession feature; only a partial zoom is available" - let s:partialzoom= 0 - endif - if v:version < 630 - echoerr "***sorry*** you need an updated vim, preferably with +mksession" - elseif s:partialzoom - " partial zoom out - let s:partialzoom= 0 - exe s:winrestore - else - " partial zoom in - let s:partialzoom= 1 - let s:winrestore = winrestcmd() - res - endif -" call Dret("ZoomWin#ZoomWin : partialzoom=".s:partialzoom) - return - endif - - " Close certain windows {{{3 - call s:ZoomWinPreserve(0) - - " save options. Force window minimum height/width to be >= 1 {{{3 - let keep_hidden = &hidden - let keep_write = &write - - if v:version < 603 - if &wmh == 0 || &wmw == 0 - let keep_wmh = &wmh - let keep_wmw = &wmw - silent! set wmh=1 wmw=1 - endif - endif - set hidden write - - if winbufnr(2) == -1 - " there's only one window - restore to multiple-windows mode {{{3 -" call Decho("there's only one window - restore to multiple windows") - - if exists("s:sessionfile") && filereadable(s:sessionfile) - " save position in current one-window-only -" call Decho("save position in current one-window-only in sponly") - let sponly = s:SavePosn(0) - let s:origline = line(".") - let s:origcol = virtcol(".") - - " source session file to restore window layout - let ei_keep= &ei - set ei=all - exe 'silent! so '.fnameescape(s:sessionfile) -" Decho("@@<".@@.">") - let v:this_session= s:sesskeep - - if exists("s:savedposn1") - " restore windows' positioning and buffers -" call Decho("restore windows, positions, buffers") - windo call s:RestorePosn(s:savedposn{winnr()})|unlet s:savedposn{winnr()} - call s:GotoWinNum(s:winkeep) - unlet s:winkeep - endif - - if line(".") != s:origline || virtcol(".") != s:origcol - " If the cursor hasn't moved from the original position, - " then let the position remain what it was in the original - " multi-window layout. -" call Decho("restore position using sponly") - call s:RestorePosn(sponly) - endif - - " delete session file and variable holding its name -" call Decho("delete session file") - call delete(s:sessionfile) - unlet s:sessionfile - let &ei=ei_keep - endif - - else " there's more than one window - go to only-one-window mode {{{3 -" call Decho("there's multiple windows - goto one-window-only") - - let s:winkeep = winnr() - let s:sesskeep = v:this_session - - " doesn't work with the command line window (normal mode q:) - if &bt == "nofile" && expand("%") == (v:version < 702 ? 'command-line' : '[Command Line]') - echoerr "***error*** ZoomWin#ZoomWin doesn't work with the ".expand("%")." window" -" call Dret("ZoomWin#ZoomWin : ".expand('%')." window error") - return - endif -" call Decho("1: @@<".@@.">") - - " disable all events (autocmds) -" call Decho("disable events") - let ei_keep= &ei - set ei=all -" call Decho("2: @@<".@@.">") - - " save window positioning commands -" call Decho("save window positioning commands") - windo let s:savedposn{winnr()}= s:SavePosn(1) - call s:GotoWinNum(s:winkeep) - - " set up name of session file -" call Decho("3: @@<".@@.">") - let s:sessionfile= tempname() -" call Decho("4: @@<".@@.">") - - " save session -" call Decho("save session") - let ssop_keep = &ssop - let &ssop = 'blank,help,winsize,folds,globals,localoptions,options' -" call Decho("5: @@<".@@.">") - exe 'mksession! '.fnameescape(s:sessionfile) -" call Decho("6: @@<".@@.">") - let keepyy= @@ - let keepy0= @0 - let keepy1= @1 - let keepy2= @2 - let keepy3= @3 - let keepy4= @4 - let keepy5= @5 - let keepy6= @6 - let keepy7= @7 - let keepy8= @8 - let keepy9= @9 - set lz ei=all bh= - if v:version >= 700 - try - exe "keepalt keepmarks new! ".fnameescape(s:sessionfile) - catch /^Vim\%((\a\+)\)\=:E/ - echoerr "Too many windows" - silent! call delete(s:sessionfile) - unlet s:sessionfile -" call Dret("ZoomWin#ZoomWin : too many windows") - return - endtry - silent! keepjumps keepmarks v/wincmd\|split\|resize/d - keepalt w! - keepalt bw! - else - exe "new! ".fnameescape(s:sessionfile) - v/wincmd\|split\|resize/d - w! - bw! - endif - let @@= keepyy - let @0= keepy0 - let @1= keepy1 - let @2= keepy2 - let @3= keepy3 - let @4= keepy4 - let @5= keepy5 - let @6= keepy6 - let @7= keepy7 - let @8= keepy8 - let @9= keepy9 - call histdel('search', -1) - let @/ = histget('search', -1) -" call Decho("7: @@<".@@.">") - - " restore user's session options and restore event handling -" call Decho("restore user session options and event handling") - set nolz - let &ssop = ssop_keep - silent! only! -" call Decho("8: @@<".@@.">") - let &ei = ei_keep - echomsg expand("%") -" call Decho("9: @@<".@@.">") - endif - - " restore user option settings {{{3 -" call Decho("restore user option settings") - let &hidden= keep_hidden - let &write = keep_write - if v:version < 603 - if exists("keep_wmw") - let &wmh= keep_wmh - let &wmw= keep_wmw - endif - endif - - " Re-open certain windows {{{3 - call s:ZoomWinPreserve(1) - -" call Dret("ZoomWin#ZoomWin") -endfun - -" --------------------------------------------------------------------- -" SavePosn: this function sets up a savedposn variable that {{{2 -" has the commands necessary to restore the view -" of the current window. -fun! s:SavePosn(savewinhoriz) -" call Dfunc("SavePosn(savewinhoriz=".a:savewinhoriz.") file<".expand("%").">") - let swline = line(".") - if swline == 1 && getline(1) == "" - " empty buffer - let savedposn= "silent b ".winbufnr(0) -" call Dret("SavePosn savedposn<".savedposn.">") - return savedposn - endif - let swcol = col(".") - let swwline = winline()-1 - let swwcol = virtcol(".") - wincol() - let savedposn = "silent b ".winbufnr(0)."|".swline."|silent norm! z\" - if swwline > 0 - let savedposn= savedposn.":silent norm! ".swwline."\\:silent norm! zs\" - endif - let savedposn= savedposn.":silent call cursor(".swline.",".swcol.")\" - - if a:savewinhoriz - if swwcol > 0 - let savedposn= savedposn.":silent norm! ".swwcol."zl\" - endif - - " handle certain special settings for the multi-window savedposn call - " bufhidden buftype buflisted - let settings= "" - if &bh != "" - let settings="bh=".&bh - setlocal bh=hide - endif - if !&bl - let settings= settings." nobl" - setlocal bl - endif - if &bt != "" - let settings= settings." bt=".&bt - setlocal bt= - endif - if settings != "" - let savedposn= savedposn.":setlocal ".settings."\" - endif - - endif -" call Dret("SavePosn savedposn<".savedposn.">") - return savedposn -endfun - -" --------------------------------------------------------------------- -" s:RestorePosn: this function restores noname and scratch windows {{{2 -fun! s:RestorePosn(savedposn) -" call Dfunc("RestorePosn(savedposn<".a:savedposn.">) file<".expand("%").">") - if &scb - setlocal noscb - exe a:savedposn - setlocal scb - else - exe a:savedposn - endif -" call Dret("RestorePosn") -endfun - -" --------------------------------------------------------------------- -" CleanupSessionFile: if you exit Vim before cleaning up the {{{2 -" supposed-to-be temporary session file -fun! ZoomWin#CleanupSessionFile() -" call Dfunc("ZoomWin#CleanupSessionFile()") - if exists("s:sessionfile") && filereadable(s:sessionfile) -" call Decho("sessionfile exists and is readable; deleting it") - silent! call delete(s:sessionfile) - unlet s:sessionfile - endif -" call Dret("ZoomWin#CleanupSessionFile") -endfun - -" --------------------------------------------------------------------- -" GotoWinNum: this function puts cursor into specified window {{{2 -fun! s:GotoWinNum(winnum) -" call Dfunc("GotoWinNum(winnum=".a:winnum.") winnr=".winnr()) - if a:winnum != winnr() - exe a:winnum."wincmd w" - endif -" call Dret("GotoWinNum") -endfun - - -" --------------------------------------------------------------------- -" ZoomWinPreserve: This function, largely written by David Fishburn, {{{2 -" allows ZoomWin to "preserve" certain windows: -" -" TagList, by Yegappan Lakshmanan -" http://vim.sourceforge.net/scripts/script.php?script_id=273 -" -" WinManager, by Srinath Avadhanula -" http://vim.sourceforge.net/scripts/script.php?script_id=95 -" -" It does so by closing the associated window upon entry to ZoomWin -" and re-opening it upon exit by using commands provided by the -" utilities themselves. -fun! s:ZoomWinPreserve(open) -" call Dfunc("ZoomWinPreserve(open=".a:open.")") - - if a:open == 0 - - " Close Taglist - if exists('g:zoomwin_preserve_taglist') && exists('g:loaded_taglist') - " If taglist window is open then close it. - let s:taglist_winnum = bufwinnr(g:TagList_title) - if s:taglist_winnum != -1 - " Close the window - exec "silent! Tlist" - endif - endif - - " Close Winmanager - if exists('g:zoomwin_preserve_winmanager') && exists('g:loaded_winmanager') - " If the winmanager window is open then close it. - let s:is_winmgr_vis = IsWinManagerVisible() - if s:is_winmgr_vis == 1 - exec "WMClose" - endif - endif - - else - - " Re-open Taglist - if exists('g:zoomwin_preserve_taglist') && exists('g:loaded_taglist') - " If taglist window was open, open it again - if s:taglist_winnum != -1 - exec "silent! Tlist" - endif - endif - - " Re-Open Winmanager - if exists('g:zoomwin_preserve_winmanager') && exists('g:loaded_winmanager') - " If the winmanager window is open then close it. - if s:is_winmgr_vis == 1 - exec "WManager" - endif - endif - endif - -" call Dret("ZoomWinPreserve") -endfun - -" ===================================================================== -" Restore: {{{1 -let &cpo= s:keepcpo -unlet s:keepcpo - -" --------------------------------------------------------------------- -" Modelines: {{{1 -" vim: ts=4 fdm=marker diff --git a/vim/autoload/delimitMate.vim b/vim/autoload/delimitMate.vim deleted file mode 100644 index bd10975..0000000 --- a/vim/autoload/delimitMate.vim +++ /dev/null @@ -1,586 +0,0 @@ -" File: autoload/delimitMate.vim -" Version: 2.6 -" Modified: 2011-01-14 -" Description: This plugin provides auto-completion for quotes, parens, etc. -" Maintainer: Israel Chauca F. -" Manual: Read ":help delimitMate". -" ============================================================================ - -" Utilities {{{ - -let delimitMate_loaded = 1 - -function! delimitMate#ShouldJump() "{{{ - " Returns 1 if the next character is a closing delimiter. - let col = col('.') - let lcol = col('$') - let char = getline('.')[col - 1] - - " Closing delimiter on the right. - for cdel in b:_l_delimitMate_right_delims + b:_l_delimitMate_quotes_list - if char == cdel - return 1 - endif - endfor - - " Closing delimiter with space expansion. - let nchar = getline('.')[col] - if b:_l_delimitMate_expand_space && char == " " - for cdel in b:_l_delimitMate_right_delims + b:_l_delimitMate_quotes_list - if nchar == cdel - return 1 - endif - endfor - endif - - " Closing delimiter with CR expansion. - let uchar = getline(line('.') + 1)[0] - if b:_l_delimitMate_expand_cr && char == "" - for cdel in b:_l_delimitMate_right_delims + b:_l_delimitMate_quotes_list - if uchar == cdel - return 1 - endif - endfor - endif - - return 0 -endfunction "}}} - -function! delimitMate#IsEmptyPair(str) "{{{ - for pair in b:_l_delimitMate_matchpairs_list - if a:str == join( split( pair, ':' ),'' ) - return 1 - endif - endfor - for quote in b:_l_delimitMate_quotes_list - if a:str == quote . quote - return 1 - endif - endfor - return 0 -endfunction "}}} - -function! delimitMate#IsCRExpansion() " {{{ - let nchar = getline(line('.')-1)[-1:] - let schar = getline(line('.')+1)[:0] - let isEmpty = getline('.') == "" - if index(b:_l_delimitMate_left_delims, nchar) > -1 && - \ index(b:_l_delimitMate_left_delims, nchar) == index(b:_l_delimitMate_right_delims, schar) && - \ isEmpty - return 1 - elseif index(b:_l_delimitMate_quotes_list, nchar) > -1 && - \ index(b:_l_delimitMate_quotes_list, nchar) == index(b:_l_delimitMate_quotes_list, schar) && - \ isEmpty - return 1 - else - return 0 - endif -endfunction " }}} delimitMate#IsCRExpansion() - -function! delimitMate#IsSpaceExpansion() " {{{ - let line = getline('.') - let col = col('.')-2 - if col > 0 - let pchar = line[col - 1] - let nchar = line[col + 2] - let isSpaces = (line[col] == line[col+1] && line[col] == " ") - - if index(b:_l_delimitMate_left_delims, pchar) > -1 && - \ index(b:_l_delimitMate_left_delims, pchar) == index(b:_l_delimitMate_right_delims, nchar) && - \ isSpaces - return 1 - elseif index(b:_l_delimitMate_quotes_list, pchar) > -1 && - \ index(b:_l_delimitMate_quotes_list, pchar) == index(b:_l_delimitMate_quotes_list, nchar) && - \ isSpaces - return 1 - endif - endif - return 0 -endfunction " }}} IsSpaceExpansion() - -function! delimitMate#WithinEmptyPair() "{{{ - let cur = strpart( getline('.'), col('.')-2, 2 ) - return delimitMate#IsEmptyPair( cur ) -endfunction "}}} - -function! delimitMate#WriteBefore(str) "{{{ - let len = len(a:str) - let line = getline('.') - let col = col('.')-2 - if col < 0 - call setline('.',line[(col+len+1):]) - else - call setline('.',line[:(col)].line[(col+len+1):]) - endif - return a:str -endfunction " }}} - -function! delimitMate#WriteAfter(str) "{{{ - let len = len(a:str) - let line = getline('.') - let col = col('.')-2 - if (col) < 0 - call setline('.',a:str.line) - else - call setline('.',line[:(col)].a:str.line[(col+len):]) - endif - return '' -endfunction " }}} - -function! delimitMate#GetSyntaxRegion(line, col) "{{{ - return synIDattr(synIDtrans(synID(a:line, a:col, 1)), 'name') -endfunction " }}} - -function! delimitMate#GetCurrentSyntaxRegion() "{{{ - let col = col('.') - if col == col('$') - let col = col - 1 - endif - return delimitMate#GetSyntaxRegion(line('.'), col) -endfunction " }}} - -function! delimitMate#GetCurrentSyntaxRegionIf(char) "{{{ - let col = col('.') - let origin_line = getline('.') - let changed_line = strpart(origin_line, 0, col - 1) . a:char . strpart(origin_line, col - 1) - call setline('.', changed_line) - let region = delimitMate#GetSyntaxRegion(line('.'), col) - call setline('.', origin_line) - return region -endfunction "}}} - -function! delimitMate#IsForbidden(char) "{{{ - if b:_l_delimitMate_excluded_regions_enabled == 0 - return 0 - endif - "let result = index(b:_l_delimitMate_excluded_regions_list, delimitMate#GetCurrentSyntaxRegion()) >= 0 - if index(b:_l_delimitMate_excluded_regions_list, delimitMate#GetCurrentSyntaxRegion()) >= 0 - "echom "Forbidden 1!" - return 1 - endif - let region = delimitMate#GetCurrentSyntaxRegionIf(a:char) - "let result = index(b:_l_delimitMate_excluded_regions_list, region) >= 0 - "return result || region == 'Comment' - "echom "Forbidden 2!" - return index(b:_l_delimitMate_excluded_regions_list, region) >= 0 -endfunction "}}} - -function! delimitMate#FlushBuffer() " {{{ - let b:_l_delimitMate_buffer = [] - return '' -endfunction " }}} - -function! delimitMate#BalancedParens(char) "{{{ - " Returns: - " = 0 => Parens balanced. - " > 0 => More opening parens. - " < 0 => More closing parens. - - let line = getline('.') - let col = col('.') - 2 - let col = col >= 0 ? col : 0 - let list = split(line, '\zs') - let left = b:_l_delimitMate_left_delims[index(b:_l_delimitMate_right_delims, a:char)] - let right = a:char - let opening = 0 - let closing = 0 - - " If the cursor is not at the beginning, count what's behind it. - if col > 0 - " Find the first opening paren: - let start = index(list, left) - " Must be before cursor: - let start = start < col ? start : col - 1 - " Now count from the first opening until the cursor, this will prevent - " extra closing parens from being counted. - let opening = count(list[start : col - 1], left) - let closing = count(list[start : col - 1], right) - " I don't care if there are more closing parens than opening parens. - let closing = closing > opening ? opening : closing - endif - - " Evaluate parens from the cursor to the end: - let opening += count(list[col :], left) - let closing += count(list[col :], right) - - "echom "–––––––––" - "echom line - "echom col - ""echom left.":".a:char - "echom string(list) - "echom string(list[start : col - 1]) . " : " . string(list[col :]) - "echom opening . " - " . closing . " = " . (opening - closing) - - " Return the found balance: - return opening - closing -endfunction "}}} - -function! delimitMate#RmBuffer(num) " {{{ - if len(b:_l_delimitMate_buffer) > 0 - call remove(b:_l_delimitMate_buffer, 0, (a:num-1)) - endif - return "" -endfunction " }}} - -" }}} - -" Doers {{{ -function! delimitMate#SkipDelim(char) "{{{ - if delimitMate#IsForbidden(a:char) - return a:char - endif - let col = col('.') - 1 - let line = getline('.') - if col > 0 - let cur = line[col] - let pre = line[col-1] - else - let cur = line[col] - let pre = "" - endif - if pre == "\\" - " Escaped character - return a:char - elseif cur == a:char - " Exit pair - "return delimitMate#WriteBefore(a:char) - return a:char . delimitMate#Del() - elseif delimitMate#IsEmptyPair( pre . a:char ) - " Add closing delimiter and jump back to the middle. - call insert(b:_l_delimitMate_buffer, a:char) - return delimitMate#WriteAfter(a:char) - else - " Nothing special here, return the same character. - return a:char - endif -endfunction "}}} - -function! delimitMate#ParenDelim(char) " {{{ - if delimitMate#IsForbidden(a:char) - return '' - endif - " Try to balance matchpairs - if b:_l_delimitMate_balance_matchpairs && - \ delimitMate#BalancedParens(a:char) <= 0 - return '' - endif - let line = getline('.') - let col = col('.')-2 - let left = b:_l_delimitMate_left_delims[index(b:_l_delimitMate_right_delims,a:char)] - let smart_matchpairs = substitute(b:_l_delimitMate_smart_matchpairs, '\\!', left, 'g') - let smart_matchpairs = substitute(smart_matchpairs, '\\#', a:char, 'g') - "echom left.':'.smart_matchpairs . ':' . matchstr(line[col+1], smart_matchpairs) - if b:_l_delimitMate_smart_matchpairs != '' && - \ line[col+1:] =~ smart_matchpairs - return '' - elseif (col) < 0 - call setline('.',a:char.line) - call insert(b:_l_delimitMate_buffer, a:char) - else - "echom string(col).':'.line[:(col)].'|'.line[(col+1):] - call setline('.',line[:(col)].a:char.line[(col+1):]) - call insert(b:_l_delimitMate_buffer, a:char) - endif - return '' -endfunction " }}} - -function! delimitMate#QuoteDelim(char) "{{{ - if delimitMate#IsForbidden(a:char) - return a:char - endif - let line = getline('.') - let col = col('.') - 2 - if line[col] == "\\" - " Seems like a escaped character, insert one quotation mark. - return a:char - elseif line[col + 1] == a:char && - \ index(b:_l_delimitMate_nesting_quotes, a:char) < 0 - " Get out of the string. - return a:char . delimitMate#Del() - elseif (line[col] =~ '\w' && a:char == "'") || - \ (b:_l_delimitMate_smart_quotes && - \ (line[col] =~ '\w' || - \ line[col + 1] =~ '\w')) - " Seems like an apostrophe or a smart quote case, insert a single quote. - return a:char - elseif (line[col] == a:char && line[col + 1 ] != a:char) && b:_l_delimitMate_smart_quotes - " Seems like we have an unbalanced quote, insert one quotation mark and jump to the middle. - call insert(b:_l_delimitMate_buffer, a:char) - return delimitMate#WriteAfter(a:char) - else - " Insert a pair and jump to the middle. - call insert(b:_l_delimitMate_buffer, a:char) - call delimitMate#WriteAfter(a:char) - return a:char - endif -endfunction "}}} - -function! delimitMate#JumpOut(char) "{{{ - if delimitMate#IsForbidden(a:char) - return a:char - endif - let line = getline('.') - let col = col('.')-2 - if line[col+1] == a:char - return a:char . delimitMate#Del() - else - return a:char - endif -endfunction " }}} - -function! delimitMate#JumpAny(key) " {{{ - if delimitMate#IsForbidden('') - return a:key - endif - if !delimitMate#ShouldJump() - return a:key - endif - " Let's get the character on the right. - let char = getline('.')[col('.')-1] - if char == " " - " Space expansion. - "let char = char . getline('.')[col('.')] . delimitMate#Del() - return char . getline('.')[col('.')] . delimitMate#Del() . delimitMate#Del() - "call delimitMate#RmBuffer(1) - elseif char == "" - " CR expansion. - "let char = "\" . getline(line('.') + 1)[0] . "\" - let b:_l_delimitMate_buffer = [] - return "\" . getline(line('.') + 1)[0] . "\" - else - "call delimitMate#RmBuffer(1) - return char . delimitMate#Del() - endif -endfunction " delimitMate#JumpAny() }}} - -function! delimitMate#JumpMany() " {{{ - let line = getline('.')[col('.') - 1 : ] - let len = len(line) - let rights = "" - let found = 0 - let i = 0 - while i < len - let char = line[i] - if index(b:_l_delimitMate_quotes_list, char) >= 0 || - \ index(b:_l_delimitMate_right_delims, char) >= 0 - let rights .= "\" - let found = 1 - elseif found == 0 - let rights .= "\" - else - break - endif - let i += 1 - endwhile - if found == 1 - return rights - else - return '' - endif -endfunction " delimitMate#JumpMany() }}} - -function! delimitMate#ExpandReturn() "{{{ - if delimitMate#IsForbidden("") - return "\" - endif - if delimitMate#WithinEmptyPair() - " Expand: - call delimitMate#FlushBuffer() - "return "\a\x\\k$\"_xa" - return "\\\o" - else - return "\" - endif -endfunction "}}} - -function! delimitMate#ExpandSpace() "{{{ - if delimitMate#IsForbidden("\") - return "\" - endif - if delimitMate#WithinEmptyPair() - " Expand: - call insert(b:_l_delimitMate_buffer, 's') - return delimitMate#WriteAfter(' ') . "\" - else - return "\" - endif -endfunction "}}} - -function! delimitMate#BS() " {{{ - if delimitMate#IsForbidden("") - return "\" - endif - if delimitMate#WithinEmptyPair() - "call delimitMate#RmBuffer(1) - return "\" . delimitMate#Del() -" return "\\\" - elseif delimitMate#IsSpaceExpansion() - "call delimitMate#RmBuffer(1) - return "\" . delimitMate#Del() - elseif delimitMate#IsCRExpansion() - return "\\" - else - return "\" - endif -endfunction " }}} delimitMate#BS() - -function! delimitMate#Del() " {{{ - if len(b:_l_delimitMate_buffer) > 0 - let line = getline('.') - let col = col('.') - 2 - call delimitMate#RmBuffer(1) - call setline('.', line[:col] . line[col+2:]) - return '' - else - return "\" - endif -endfunction " }}} - -function! delimitMate#Finish(move_back) " {{{ - let len = len(b:_l_delimitMate_buffer) - if len > 0 - let buffer = join(b:_l_delimitMate_buffer, '') - let len2 = len(buffer) - " Reset buffer: - let b:_l_delimitMate_buffer = [] - let line = getline('.') - let col = col('.') -2 - "echom 'col: ' . col . '-' . line[:col] . "|" . line[col+len+1:] . '%' . buffer - if col < 0 - call setline('.', line[col+len2+1:]) - else - call setline('.', line[:col] . line[col+len2+1:]) - endif - let i = 1 - let lefts = "" - while i <= len && a:move_back - let lefts = lefts . "\" - let i += 1 - endwhile - return substitute(buffer, "s", "\", 'g') . lefts - endif - return '' -endfunction " }}} - -" }}} - -" Tools: {{{ -function! delimitMate#TestMappings() "{{{ - let options = sort(keys(delimitMate#OptionsList())) - let optoutput = ['delimitMate Report', '==================', '', '* Options: ( ) default, (g) global, (b) buffer',''] - for option in options - exec 'call add(optoutput, ''('.(exists('b:delimitMate_'.option) ? 'b' : exists('g:delimitMate_'.option) ? 'g' : ' ').') delimitMate_''.option.'' = ''.string(b:_l_delimitMate_'.option.'))' - endfor - call append(line('$'), optoutput + ['--------------------','']) - - " Check if mappings were set. {{{ - let imaps = b:_l_delimitMate_right_delims - let imaps = imaps + ( b:_l_delimitMate_autoclose ? b:_l_delimitMate_left_delims : [] ) - let imaps = imaps + - \ b:_l_delimitMate_quotes_list + - \ b:_l_delimitMate_apostrophes_list + - \ ['', '', '', '', ''] + - \ ['', '', '', '', '', ''] + - \ ['', '', '', '', '', '', 'g'] - let imaps = imaps + ( b:_l_delimitMate_expand_cr ? [''] : [] ) - let imaps = imaps + ( b:_l_delimitMate_expand_space ? [''] : [] ) - - let vmaps = - \ b:_l_delimitMate_right_delims + - \ b:_l_delimitMate_left_delims + - \ b:_l_delimitMate_quotes_list - - let ibroken = [] - for map in imaps - if maparg(map, "i") !~? 'delimitMate' - let output = '' - if map == '|' - let map = '' - endif - redir => output | execute "verbose imap ".map | redir END - let ibroken = ibroken + [map.": is not set:"] + split(output, '\n') - endif - endfor - - unlet! output - if ibroken == [] - let output = ['* Mappings:', '', 'All mappings were set-up.', '--------------------', '', ''] - else - let output = ['* Mappings:', ''] + ibroken + ['--------------------', ''] - endif - call append('$', output+['* Showcase:', '']) - " }}} - if b:_l_delimitMate_autoclose - " {{{ - for i in range(len(b:_l_delimitMate_left_delims)) - exec "normal Go0\Open: " . b:_l_delimitMate_left_delims[i]. "|" - exec "normal o0\Delete: " . b:_l_delimitMate_left_delims[i] . "\|" - exec "normal o0\Exit: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . "|" - if b:_l_delimitMate_expand_space == 1 - exec "normal o0\Space: " . b:_l_delimitMate_left_delims[i] . " |" - exec "normal o0\Delete space: " . b:_l_delimitMate_left_delims[i] . " \|" - endif - if b:_l_delimitMate_expand_cr == 1 - exec "normal o0\Car return: " . b:_l_delimitMate_left_delims[i] . "\|" - exec "normal Go0\Delete car return: " . b:_l_delimitMate_left_delims[i] . "\0\\|" - endif - call append(line('$'), '') - endfor - for i in range(len(b:_l_delimitMate_quotes_list)) - exec "normal Go0\Open: " . b:_l_delimitMate_quotes_list[i] . "|" - exec "normal o0\Delete: " . b:_l_delimitMate_quotes_list[i] . "\|" - exec "normal o0\Exit: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . "|" - if b:_l_delimitMate_expand_space == 1 - exec "normal o0\Space: " . b:_l_delimitMate_quotes_list[i] . " |" - exec "normal o0\Delete space: " . b:_l_delimitMate_quotes_list[i] . " \|" - endif - if b:_l_delimitMate_expand_cr == 1 - exec "normal o0\Car return: " . b:_l_delimitMate_quotes_list[i] . "\|" - exec "normal Go0\Delete car return: " . b:_l_delimitMate_quotes_list[i] . "\\|" - endif - call append(line('$'), '') - endfor - "}}} - else - "{{{ - for i in range(len(b:_l_delimitMate_left_delims)) - exec "normal GoOpen & close: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . "|" - exec "normal oDelete: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . "\|" - exec "normal oExit: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . b:_l_delimitMate_right_delims[i] . "|" - if b:_l_delimitMate_expand_space == 1 - exec "normal oSpace: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . " |" - exec "normal oDelete space: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . " \|" - endif - if b:_l_delimitMate_expand_cr == 1 - exec "normal oCar return: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . "\|" - exec "normal GoDelete car return: " . b:_l_delimitMate_left_delims[i] . b:_l_delimitMate_right_delims[i] . "\\|" - endif - call append(line('$'), '') - endfor - for i in range(len(b:_l_delimitMate_quotes_list)) - exec "normal GoOpen & close: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . "|" - exec "normal oDelete: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . "\|" - exec "normal oExit: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . "|" - if b:_l_delimitMate_expand_space == 1 - exec "normal oSpace: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . " |" - exec "normal oDelete space: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . " \|" - endif - if b:_l_delimitMate_expand_cr == 1 - exec "normal oCar return: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . "\|" - exec "normal GoDelete car return: " . b:_l_delimitMate_quotes_list[i] . b:_l_delimitMate_quotes_list[i] . "\\|" - endif - call append(line('$'), '') - endfor - endif "}}} - redir => setoptions | set | filetype | redir END - call append(line('$'), split(setoptions,"\n") - \ + ['--------------------']) - setlocal nowrap -endfunction "}}} - -function! delimitMate#OptionsList() "{{{ - return {'autoclose' : 1,'matchpairs': &matchpairs, 'quotes' : '" '' `', 'nesting_quotes' : [], 'expand_cr' : 0, 'expand_space' : 0, 'smart_quotes' : 1, 'smart_matchpairs' : '\w', 'balance_matchpairs' : 0, 'excluded_regions' : 'Comment', 'excluded_ft' : '', 'apostrophes' : ''} -endfunction " delimitMate#OptionsList }}} -"}}} - -" vim:foldmethod=marker:foldcolumn=4 diff --git a/vim/bundle/Align b/vim/bundle/Align new file mode 160000 index 0000000..787662f --- /dev/null +++ b/vim/bundle/Align @@ -0,0 +1 @@ +Subproject commit 787662fe90cd057942bc5b682fd70c87e1a9dd77 diff --git a/vim/bundle/Colour-Sampler-Pack b/vim/bundle/Colour-Sampler-Pack new file mode 160000 index 0000000..05cded8 --- /dev/null +++ b/vim/bundle/Colour-Sampler-Pack @@ -0,0 +1 @@ +Subproject commit 05cded87b2ef29aaa9e930230bb88e23abff4441 diff --git a/vim/bundle/LargeFile b/vim/bundle/LargeFile new file mode 160000 index 0000000..2b654ca --- /dev/null +++ b/vim/bundle/LargeFile @@ -0,0 +1 @@ +Subproject commit 2b654cad2c8e253f844b87e4b768db3a205da280 diff --git a/vim/bundle/SearchComplete b/vim/bundle/SearchComplete new file mode 160000 index 0000000..d85ccf8 --- /dev/null +++ b/vim/bundle/SearchComplete @@ -0,0 +1 @@ +Subproject commit d85ccf8c6c1fa88feff0c56b8fe271b7d91bd292 diff --git a/vim/bundle/ZoomWin b/vim/bundle/ZoomWin new file mode 160000 index 0000000..cf21ce1 --- /dev/null +++ b/vim/bundle/ZoomWin @@ -0,0 +1 @@ +Subproject commit cf21ce1f4bfec10fe7e446c08e9e647a2a234e03 diff --git a/vim/bundle/ag.vim b/vim/bundle/ag.vim new file mode 160000 index 0000000..b0d5073 --- /dev/null +++ b/vim/bundle/ag.vim @@ -0,0 +1 @@ +Subproject commit b0d50730dbf692168307adef625f1378553730df diff --git a/vim/bundle/delimitMate b/vim/bundle/delimitMate new file mode 160000 index 0000000..f2efe43 --- /dev/null +++ b/vim/bundle/delimitMate @@ -0,0 +1 @@ +Subproject commit f2efe4331b74a4e1157729106cd7950ed6bbf4a8 diff --git a/vim/bundle/nerdcommenter b/vim/bundle/nerdcommenter new file mode 160000 index 0000000..0b3d928 --- /dev/null +++ b/vim/bundle/nerdcommenter @@ -0,0 +1 @@ +Subproject commit 0b3d928dce8262dedfc2f83b9aeb59a94e4f0ae4 diff --git a/vim/bundle/nerdtree b/vim/bundle/nerdtree new file mode 160000 index 0000000..b0bb781 --- /dev/null +++ b/vim/bundle/nerdtree @@ -0,0 +1 @@ +Subproject commit b0bb781fc73ef40365e4c996a16f04368d64fc9d diff --git a/vim/bundle/vim-easymotion b/vim/bundle/vim-easymotion new file mode 160000 index 0000000..667a668 --- /dev/null +++ b/vim/bundle/vim-easymotion @@ -0,0 +1 @@ +Subproject commit 667a668e114e9ec0e5d4cbcb0962d835b23614c4 diff --git a/vim/bundle/vim-endwise b/vim/bundle/vim-endwise new file mode 160000 index 0000000..9f05e4c --- /dev/null +++ b/vim/bundle/vim-endwise @@ -0,0 +1 @@ +Subproject commit 9f05e4c0c6163ec52010b0e1e6f66605ae42302d diff --git a/vim/doc/Align.txt b/vim/doc/Align.txt deleted file mode 100644 index c447372..0000000 --- a/vim/doc/Align.txt +++ /dev/null @@ -1,1469 +0,0 @@ -*align.txt* The Alignment Tool Mar 04, 2009 - -Author: Charles E. Campbell, Jr. - (remove NOSPAM from Campbell's email first) -Copyright: (c) 2004-2008 by Charles E. Campbell, Jr. *Align-copyright* - The VIM LICENSE applies to Align.vim, AlignMaps.vim, and Align.txt - (see |copyright|) except use "Align and AlignMaps" instead of "Vim" - NO WARRANTY, EXPRESS OR IMPLIED. USE AT-YOUR-OWN-RISK. - -============================================================================== -1. Contents *align* *align-contents* {{{1 - - 1. Contents.................: |align-contents| - 2. Alignment Manual.........: |align-manual| - 3. Alignment Usage..........: |align-usage| - Alignment Concepts.......: |align-concepts| - Alignment Commands.......: |align-commands| - Alignment Control........: |align-control| - Separators.............: |alignctrl-separators| - Initial Whitespace.....: |alignctrl-w| |alignctrl-W| |alignctrl-I| - Justification..........: |alignctrl-l| |alignctrl-r| |alignctrl-c| - Justification Control..: |alignctrl--| |alignctrl-+| |alignctrl-:| - Cyclic/Sequential......: |alignctrl-=| |alignctrl-C| - Separator Justification: |alignctrl-<| |alignctrl->| |alignctrl-|| - Line (de)Selection.....: |alignctrl-g| |alignctrl-v| - Temporary Settings.....: |alignctrl-m| - Padding................: |alignctrl-p| |alignctrl-P| - Current Options........: |alignctrl-settings| |alignctrl-| - Alignment................: |align-align| - 4. Alignment Maps...........: |align-maps| - \a,....................: |alignmap-a,| - \a?....................: |alignmap-a?| - \a<....................: |alignmap-a<| - \abox..................: |alignmap-abox| - \acom..................: |alignmap-acom| - \anum..................: |alignmap-anum| - \ascom.................: |alignmap-ascom| - \adec..................: |alignmap-adec| - \adef..................: |alignmap-adef| - \afnc..................: |alignmap-afnc| - \adcom.................: |alignmap-adcom| - \aocom.................: |alignmap-aocom| - \tsp...................: |alignmap-tsp| - \tsq...................: |alignmap-tsq| - \tt....................: |alignmap-tt| - \t=....................: |alignmap-t=| - \T=....................: |alignmap-T=| - \Htd...................: |alignmap-Htd| - 5. Alignment Tool History...: |align-history| - -============================================================================== -2. Align Manual *alignman* *alignmanual* *align-manual* {{{1 - - Align comes as a vimball; simply typing > - vim Align.vba.gz - :so % -< should put its components where they belong. The components are: > - .vim/plugin/AlignPlugin.vim - .vim/plugin/AlignMapsPlugin.vim - .vim/plugin/cecutil.vim - .vim/autoload/Align.vim - .vim/autoload/AlignMaps.vim - .vim/doc/Align.txt -< To see a user's guide, see |align-userguide| - To see examples, see |alignctrl| and |alignmaps| -> -/=============+=========+=====================================================\ -|| \ Default/ || -|| Commands \ Value/ Explanation || -|| | | || -++==============+====+=======================================================++ -|| AlignCtrl | | =Clrc-+:pPIWw [..list-of-separator-patterns..] || -|| | +-------------------------------------------------------+| -|| | | may be called as a command or as a function: || -|| | | :AlignCtrl =lp0P0W & \\ || -|| | | :call Align#AlignCtrl('=lp0P0W','&','\\') || -|| | | || -|| | +-------------------------------------------------------++ -|| 1st arg | = | = all separator patterns are equivalent and are || -|| | | simultaneously active. Patterns are |regexp|. || -|| | | C cycle through separator patterns. Patterns are || -|| | | |regexp| and are active sequentially. || -|| | | || -|| | < | < left justify separator Separators are justified, || -|| | | > right justify separator too. Separator styles || -|| | | | center separator are cyclic. || -|| | | || -|| | l | l left justify Justification styles are always || -|| | | r right justify cyclic (ie. lrc would mean left j., || -|| | | c center then right j., then center, repeat. || -|| | | - skip this separator || -|| | | + re-use last justification method || -|| | | : treat rest of text as a field || -|| | | || -|| | p1 | p### pad separator on left by # blanks || -|| | P1 | P### pad separator on right by # blanks || -|| | | || -|| | I | I preserve and apply first line's leading white || -|| | | space to all lines || -|| | | W preserve leading white space on every line, even || -|| | | if it varies from line to line || -|| | | w don't preserve leading white space || -|| | | || -|| | | g second argument is a selection pattern -- only || -|| | | align on lines that have a match (inspired by || -|| | | :g/selection pattern/command) || -|| | | v second argument is a selection pattern -- only || -|| | | align on lines that _don't_ have a match (inspired || -|| | | by :v/selection pattern/command) || -|| | | || -|| | | m Map support: AlignCtrl will immediately do an || -|| | | AlignPush() and the next call to Align() will do || -|| | | an AlignPop at the end. This feature allows maps || -|| | | to preserve user settings. || -|| | | || -|| | | default || -|| | | AlignCtrl default || -|| | | will clear the AlignCtrl || -|| | | stack & set the default: AlignCtrl "Ilp1P1=" '=' || -|| | | || -|| +----+-------------------------------------------------------+| -|| More args | More arguments are interpreted as describing separators || -|| +------------------------------------------------------------+| -|| No args | AlignCtrl will display its current settings || -||==============+============================================================+| -||[range]Align | [..list-of-separators..] || -||[range]Align! | [AlignCtrl settings] [..list-of-separators..] || -|| +------------------------------------------------------------+| -|| | Aligns text over the given range. The range may be || -|| | selected via visual mode (v, V, or ctrl-v) or via || -|| | the command line. The Align operation may be invoked || -|| | as a command or as a function; as a function, the first || -|| | argument is 0=separators only, 1=AlignCtrl option string || -|| | followed by a list of separators. || -|| | :[range]Align || -|| | :[range]Align [list of separators] || -|| | :[range]call Align#Align(0) || -|| | :[range]call Align#Align(0,"list","of","separators",...) || -\=============================================================================/ - -============================================================================== -3. Alignment Usage *alignusage* *align-usage* *align-userguide* {{{1 - - -ALIGNMENT CONCEPTS *align-concept* *align-concepts* {{{2 - - The typical text to be aligned is considered to be: - - * composed of two or more fields - * separated by one or more separator pattern(s): - * two or more lines -> - ws field ws separator ws field ws separator ... - ws field ws separator ws field ws separator ... -< - where "ws" stands for "white space" such as blanks and/or tabs, - and "fields" are arbitrary text. For example, consider > - - x= y= z= 3; - xx= yy= zz= 4; - zzz= yyy= zzz= 5; - a= b= c= 3; -< - Assume that it is desired to line up all the "=" signs; these, - then, are the separators. The fields are composed of all the - alphameric text. Assuming they lie on lines 1-4, one may align - those "=" signs with: > - :AlignCtrl l - :1,4Align = -< The result is: > - x = y = z = 3; - xx = yy = zz = 4; - zzz = yyy = zzz = 5; - a = b = c = 3; - -< Note how each "=" sign is surrounded by a single space; the - default padding is p1P1 (p1 means one space before the separator, - and P1 means one space after it). If you wish to change the - padding, say to no padding, use (see |alignctrl-p|) > - :AlignCtrl lp0P0 - -< Next, note how each field is left justified; that's what the "l" - (a small letter "ell") does. If right-justification of the fields - had been desired, an "r" could've been used: > - :AlignCtrl r -< yielding > - x = y = z = 3; - xx = yy = zz = 4; - zzz = yyy = zzz = 5; - a = b = c = 3; -< There are many more options available for field justification: see - |alignctrl-c| and |alignctrl--|. - - Separators, although commonly only one character long, are actually - specified by regular expressions (see |regexp|), and one may left - justify, right justify, or center them, too (see |alignctrl-<|). - - Assume that for some reason a left-right-left-right-... justification - sequence was wished. This wish is simply achieved with > - :AlignCtrl lr - :1,4Align = -< because the justification commands are considered to be "cylic"; ie. - lr is the same as lrlrlrlrlrlrlr... - - There's a lot more discussed under |alignctrl|; hopefully the examples - there will help, too. - - -ALIGNMENT COMMANDS *align-command* *align-commands* {{{2 - - The script includes two primary commands and two - minor commands: - - AlignCtrl : this command/function sets up alignment options - which persist until changed for later Align calls. - It controls such things as: how to specify field - separators, initial white space, padding about - separators, left/right/center justification, etc. > - ex. AlignCtrl wp0P1 - Interpretation: during subsequent alignment - operations, preserve each line's initial - whitespace. Use no padding before separators - but provide one padding space after separators. -< - Align : this command/function operates on the range given it to - align text based on one or more separator patterns. The - patterns may be provided via AlignCtrl or via Align - itself. > - - ex. :%Align , - Interpretation: align all commas over the entire - file. -< The :Align! format permits alignment control commands - to precede the alignment patterns. > - ex. :%Align! p2P2 = -< This will align all "=" in the file with two padding - spaces on both sides of each "=" sign. - - NOTE ON USING PATTERNS WITH ALIGN:~ - Align and AlignCtrl use || to obtain their - input patterns and they use an internal function to - split arguments at whitespace unless inside "..."s. - One may escape characters inside a double-quote string - by preceding such characters with a backslash. - - AlignPush : this command/function pushes the current AlignCtrl - state onto an internal stack. > - ex. :AlignPush - Interpretation: save the current AlignCtrl - settings, whatever they may be. They'll - also remain as the current settings until - AlignCtrl is used to change them. -< - AlignPop : this command/function pops the current AlignCtrl - state from an internal stack. > - ex. :AlignPop - Interpretation: presumably AlignPush was - used (at least once) previously; this command - restores the AlignCtrl settings when AlignPush - was last used. -< Also see |alignctrl-m| for a way to automatically do - an AlignPop after an Align (primarily this is for maps). - -ALIGNMENT OPTIONS *align-option* *align-options* {{{2 - *align-utf8* *align-utf* *align-codepoint* *align-strlen* *align-multibyte* - - For those of you who are using 2-byte (or more) characters such as are - available with utf-8, Align now provides a special option which you - may choose based upon your needs: - - Use Built-in strlen() ~ -> - let g:Align_xstrlen= 0 - -< This is the fastest method, but it doesn't handle multibyte characters - well. It is the default for: - - enc=latin1 - vim compiled without multi-byte support - $LANG is en_US.UTF-8 (assuming USA english) - - Number of codepoints (Latin a + combining circumflex is two codepoints)~ -> - let g:Align_xstrlen= 1 (default) -< - Number of spacing codepoints (Latin a + combining circumflex is one~ - spacing codepoint; a hard tab is one; wide and narrow CJK are one~ - each; etc.)~ -> - let g:Align_xstrlen= 2 -< - Virtual length (counting, for instance, tabs as anything between 1 and~ - 'tabstop', wide CJK as 2 rather than 1, Arabic alif as zero when~ - immediately preceded by lam, one otherwise, etc.)~ -> - let g:Align_xstrlen= 3 -< - By putting one of these settings into your <.vimrc>, Align will use an - internal (interpreted) function to determine a string's length instead - of the Vim's built-in |strlen()| function. Since the function is - interpreted, Align will run a bit slower but will handle such strings - correctly. The last setting (g:Align_xstrlen= 3) probably will run - the slowest but be the most accurate. (thanks to Tony Mechelynck for - these) - - -ALIGNMENT CONTROL *alignctrl* *align-control* {{{2 - - This command doesn't do the alignment operation itself; instead, it - controls subsequent alignment operation(s). - - The first argument to AlignCtrl is a string which may contain one or - more alignment control settings. Most of the settings are specified - by single letters; the exceptions are the p# and P# commands which - interpret a digit following the p or P as specifying padding about the - separator. - - The typical text line is considered to be composed of two or more - fields separated by one or more separator pattern(s): > - - ws field ws separator ws field ws separator ... -< - where "ws" stands for "white space" such as blanks and/or tabs. - - - SEPARATORS *alignctrl-separators* {{{3 - - As a result, separators may not have white space (tabs or blanks) on - their outsides (ie. ": :" is fine as a separator, but " :: " is - not). Usually such separators are not needed, although a map has been - provided which works around this limitation and aligns on whitespace - (see |alignmap-tsp|). - - However, if you really need to have separators with leading or - trailing whitespace, consider handling them by performing a substitute - first (ie. s/ :: /@/g), do the alignment on the temporary pattern - (ie. @), and then perform a substitute to revert the separators back - to their desired condition (ie. s/@/ :: /g). - - The Align#Align() function will first convert tabs over the region into - spaces and then apply alignment control. Except for initial white - space, white space surrounding the fields is ignored. One has three - options just for handling initial white space: - - - --- *alignctrl-w* - wWI INITIAL WHITE SPACE *alignctrl-W* {{{3 - --- *alignctrl-I* - w : ignore all selected lines' initial white space - W : retain all selected lines' initial white space - I : retain only the first line's initial white space and - re-use it for subsequent lines - - Example: Leading white space options: > - +---------------+-------------------+-----------------+ - |AlignCtrl w= :=| AlignCtrl W= := | AlignCtrl I= := | - +------------------+---------------+-------------------+-----------------+ - | Original | w option | W option | I option | - +------------------+---------------+-------------------+-----------------+ - | a := baaa |a := baaa | a : = baaa | a := baaa | - | caaaa := deeee |caaaa := deeee | caaaa : = deeee| caaaa := deeee| - | ee := f |ee := f | ee : = f | ee := f | - +------------------+---------------+-------------------+-----------------+ -< - The original has at least one leading white space on every line. - Using Align with w eliminated each line's leading white space. - Using Align with W preserved each line's leading white space. - Using Align with I applied the first line's leading white space - (three spaces) to each line. - - - ------ *alignctrl-l* - lrc-+: FIELD JUSTIFICATION *alignctrl-r* {{{3 - ------ *alignctrl-c* - - With "lrc", the fields will be left-justified, right-justified, or - centered as indicated by the justification specifiers (lrc). The - "lrc" options are re-used by cycling through them as needed: - - l means llllll.... - r means rrrrrr.... - lr means lrlrlr.... - llr means llrllr.... - - Example: Justification options: Align = > - +------------+-------------------+-------------------+-------------------+ - | Original | AlignCtrl l | AlignCtrl r | AlignCtrl lr | - +------------+-------------------+-------------------+-------------------+ - | a=bb=ccc=1 |a = bb = ccc = 1| a = bb = ccc = 1|a = bb = ccc = 1| - | ccc=a=bb=2 |ccc = a = bb = 2|ccc = a = bb = 2|ccc = a = bb = 2| - | dd=eee=f=3 |dd = eee = f = 3| dd = eee = f = 3|dd = eee = f = 3| - +------------+-------------------+-------------------+-------------------+ - | Alignment |l l l l| r r r r|l r l r| - +------------+-------------------+-------------------+-------------------+ -< - AlignCtrl l : The = separator is repeatedly re-used, as the - cycle only consists of one character (the "l"). - Every time left-justification is used for fields. - AlignCtrl r : The = separator is repeatedly re-used, as the - cycle only consists of one character (the "l"). - Every time right-justification is used for fields - AlignCtrl lr: Again, the "=" separator is repeatedly re-used, - but the fields are justified alternately between - left and right. - - Even more separator control is available. With "-+:": - - - : skip treating the separator as a separator. *alignctrl--* - + : repeat use of the last "lrc" justification *alignctrl-+* - : : treat the rest of the line as a single field *alignctrl-:* - - Example: More justification options: Align = > - +------------+---------------+--------------------+---------------+ - | Original | AlignCtrl -l | AlignCtrl rl+ | AlignCtrl l: | - +------------+---------------+--------------------+---------------+ - | a=bb=ccc=1 |a=bb = ccc=1 | a = bb = ccc = 1 |a = bb=ccc=1 | - | ccc=a=bb=2 |ccc=a = bb=2 |ccc = a = bb = 2 |ccc = a=bb=2 | - | dd=eee=f=3 |dd=eee = f=3 | dd = eee = f = 3 |dd = eee=f=3 | - +------------+---------------+--------------------+---------------+ - | Alignment |l l | r l l l |l l | - +------------+---------------+--------------------+---------------+ -< - In the first example in "More justification options": - - The first "=" separator is skipped by the "-" specification, - and so "a=bb", "ccc=a", and "dd=eee" are considered as single fields. - - The next "=" separator has its (left side) field left-justified. - Due to the cyclic nature of separator patterns, the "-l" - specification is equivalent to "-l-l-l ...". - - Hence the next specification is a "skip", so "ccc=1", etc are fields. - - In the second example in "More justification options": - - The first field is right-justified, the second field is left - justified, and all remaining fields repeat the last justification - command (ie. they are left justified, too). - - Hence rl+ is equivalent to rlllllllll ... - (whereas plain rl is equivalent to rlrlrlrlrl ... ). - - In the third example in "More justification options": - - The text following the first separator is treated as a single field. - - Thus using the - and : operators one can apply justification to a - single separator. - - ex. 1st separator only: AlignCtrl l: - 2nd separator only: AlignCtrl -l: - 3rd separator only: AlignCtrl --l: - etc. - - - --- *alignctrl-=* - =C CYCLIC VS ALL-ACTIVE SEPARATORS *alignctrl-C* {{{3 - --- - - The separators themselves may be considered as equivalent and - simultaneously active ("=") or sequentially cycled through ("C"). - Separators are regular expressions (|regexp|) and are specified as the - second, third, etc arguments. When the separator patterns are - equivalent and simultaneously active, there will be one pattern - constructed: > - - AlignCtrl ... pat1 pat2 pat3 - \(pat1\|pat2\|pat3\) -< - Each separator pattern is thus equivalent and simultaneously active. - The cyclic separator AlignCtrl option stores a list of patterns, only - one of which is active for each field at a time. - - Example: Equivalent/Simultaneously-Active vs Cyclic Separators > - +-------------+------------------+---------------------+----------------------+ - | Original | AlignCtrl = = + -| AlignCtrl = = | AlignCtrl C = + - | - +-------------+------------------+---------------------+----------------------+ - |a = b + c - d|a = b + c - d |a = b + c - d |a = b + c - d | - |x = y = z + 2|x = y = z + 2 |x = y = z + 2|x = y = z + 2 | - |w = s - t = 0|w = s - t = 0 |w = s - t = 0 |w = s - t = 0 | - +-------------+------------------+---------------------+----------------------+ -< - The original is initially aligned with all operators (=+-) being - considered as equivalent and simultaneously active field separators. - Thus the "AlignCtrl = = + -" example shows no change. - - The second example only accepts the '=' as a field separator; - consequently "b + c - d" is now a single field. - - The third example illustrates cyclic field separators and is analyzed - in the following illustration: > - - field1 separator field2 separator field3 separator field4 - a = b + c - d - x = y = z + 2 - w = s - t = 0 -< - The word "cyclic" is used because the patterns form a cycle of use; in - the above case, its = + - = + - = + - = + -... - - Example: Cyclic separators > - Label : this is some text discussing ":"s | ex. abc:def:ghi - Label : this is some text with a ":" in it | ex. abc:def -< - apply AlignCtrl lWC : | | - (select lines)Align > - Label : this is some text discussing ":"s | ex. abc:def:ghi - Label : this is some text with a ":" in it | ex. abcd:efg -< - In the current example, - : is the first separator So the first ":"s are aligned - | is the second separator but subsequent ":"s are not. - | is the third separator The "|"s are aligned, too. - : is the fourth separator Since there aren't two bars, - | is the fifth separator the subsequent potential cycles - | is the sixth separator don't appear. - ... - - In this case it would probably have been a better idea to have used > - AlignCtrl WCl: : | -< as that alignment control would guarantee that no more cycling - would be used after the vertical bar. - - Example: Cyclic separators - - Original: > - a| b&c | (d|e) & f-g-h - aa| bb&cc | (dd|ee) & ff-gg-hh - aaa| bbb&ccc | (ddd|eee) & fff-ggg-hhh -< - AlignCtrl C | | & - > - a | b&c | (d|e) & f - g-h - aa | bb&cc | (dd|ee) & ff - gg-hh - aaa | bbb&ccc | (ddd|eee) & fff - ggg-hhh -< - In this example, - the first and second separators are "|", - the third separator is "&", and - the fourth separator is "-", - - (cycling) - the fifth and sixth separators are "|", - the seventh separator is "&", and - the eighth separator is "-", etc. - - Thus the first "&"s are (not yet) separators, and hence are treated as - part of the field. Ignoring white space for the moment, the AlignCtrl - shown here means that Align will work with > - - field | field | field & field - field | field | field & field - ... -< - - --- *alignctrl-<* - <>| SEPARATOR JUSTIFICATION *alignctrl->* {{{3 - --- *alignctrl-|* - - Separators may be of differing lengths as shown in the example below. - Hence they too may be justified left, right, or centered. - Furthermore, separator justification specifications are cyclic: - - < means <<<<<... justify separator(s) to the left - > means >>>>>... justify separator(s) to the right - | means |||||... center separator(s) - - Example: Separator Justification: Align -\+ > - +-----------------+ - | Original | - +-----------------+ - | a - bbb - c | - | aa -- bb -- ccc | - | aaa --- b --- cc| - +---------------------+-+-----------------+-+---------------------+ - | AlignCtrl < | AlignCtrl > | AlignCtrl | | - +---------------------+---------------------+---------------------+ - | a - bbb - c | a - bbb - c | a - bbb - c | - | aa -- bb -- ccc | aa -- bb -- ccc | aa -- bb -- ccc | - | aaa --- b --- cc | aaa --- b --- cc | aaa --- b --- cc | - +---------------------+---------------------+---------------------+ -< - - --- *alignctrl-g* - gv SELECTIVE APPLICATION *alignctrl-v* {{{3 - --- - - - These two options provide a way to select (g) or to deselect (v) lines - based on a pattern. Ideally :g/pat/Align would work; unfortunately - it results in Align#Align() being called on each line satisfying the - pattern separately. > - - AlignCtrl g pattern -< - Align will only consider those lines which have the given pattern. > - - AlignCtrl v pattern -< - Align will only consider those lines without the given pattern. As an - example of use, consider the following example: > - - :AlignCtrl v ^\s*/\* - Original :Align = :Align = - +----------------+------------------+----------------+ - |one= 2; |one = 2; |one = 2; | - |three= 4; |three = 4; |three = 4; | - |/* skip=this */ |/* skip = this */ |/* skip=this */ | - |five= 6; |five = 6; |five = 6; | - +----------------+------------------+----------------+ -< - The first "Align =" aligned with all "="s, including that one in the - "skip=this" comment. - - The second "Align =" had a AlignCtrl v-pattern which caused it to skip - (ignore) the "skip=this" line when aligning. - - To remove AlignCtrl's g and v patterns, use (as appropriate) > - - AlignCtrl g - AlignCtrl v -< - To see what g/v patterns are currently active, just use the reporting - capability of an unadorned call to AlignCtrl: > - - AlignCtrl -< - - --- - m MAP SUPPORT *alignctrl-m* {{{3 - --- - - This option primarily supports the development of maps. The - Align#AlignCtrl() call will first do an Align#AlignPush() (ie. retain - current alignment control settings). The next Align#Align() will, in - addition to its alignment job, finish up with an Align#AlignPop(). - Thus the Align#AlignCtrl settings that follow the "m" are only - temporarily in effect for just the next Align#Align(). - - - --- - p### *alignctrl-p* - P### PADDING *alignctrl-P* {{{3 - --- - - These two options control pre-padding and post-padding with blanks - about the separator. One may pad separators with zero to nine spaces; - the padding number(s) is/are treated as a cyclic parameter. Thus one - may specify padding separately for each field or re-use a padding - pattern. > - - Example: AlignCtrl p102P0 - +---------+----------------------------------+ - | Original| a=b=c=d=e=f=g=h=1 | - | Align = | a =b=c =d =e=f =g =h=1 | - +---------+----------------------------------+ - | prepad | 1 0 2 1 0 2 1 0 | - +---------+----------------------------------+ -< - This example will cause Align to: - - pre-pad the first "=" with a single blank, - pre-pad the second "=" with no blanks, - pre-pad the third "=" with two blanks, - pre-pad the fourth "=" with a single blank, - pre-pad the fifth "=" with no blanks, - pre-pad the sixth "=" with two blanks, - etc. - - --------------- *alignctrl-settings* - No option given DISPLAY STATUS *alignctrl-* {{{3 - --------------- *alignctrl-no-option* - - AlignCtrl, when called with no arguments, will display the current - alignment control settings. A typical display is shown below: > - - AlignCtrl<=> qty=1 AlignStyle Padding<1|1> - Pat1<\(=\)> -< - Interpreting, this means that the separator patterns are all - equivalent; in this case, there's only one (qty=1). Fields will be - padded on the right with spaces (left justification), and separators - will be padded on each side with a single space. - - To change one of these items, see: - - AlignCtrl......|alignctrl| - qty............|align-concept| - AlignStyle.....|alignctrl--| |alignctrl-+| |alignctrl-:||alignctrl-c| - Padding........|alignctrl-p| |alignctrl-P| - - One may get a string which can be fed back into AlignCtrl: > - - :let alignctrl= Align#AlignCtrl() -< - This form will put a string describing the current AlignCtrl options, - except for the "g" and "v" patterns, into a variable. The - Align#AlignCtrl() function will still echo its settings, however. One - can feed any non-supported "option" to AlignCtrl() to prevent this, - however: > - - :let alignctrl= Align#AlignCtrl("d") -< - -ALIGNMENT *align-align* {{{2 - - Once the alignment control has been determined, the user specifies a - range of lines for the Align command/function to do its thing. - Alignment is often done on a line-range basis, but one may also - restrict alignment to a visual block using ctrl-v. For any visual - mode, one types the colon (:) and then "Align". One may, of course, - specify a range of lines: > - - :[range]Align [list-of-separators] -< - where the |:range| is the usual Vim-powered set of possibilities; the - list of separators is the same as the AlignCtrl capability. There is - only one list of separators, but either AlignCtrl or Align can be used - to specify that list. - - An alternative form of the Align command can handle both alignment - control and the separator list: > - - :[range]Align! [alignment-control-string] [list-of-separators] -< - The alignment control string will be applied only for this particular - application of Align (it uses |alignctrl-m|). The "g pattern" and - "v pattern" alignment controls (see |alignctrl-g| and |alignctrl-v|) - are also available via this form of the Align command. - - Align makes two passes over the text to be aligned. The first pass - determines how many fields there are and determines the maximum sizes - of each field; these sizes are then stored in a vector. The second - pass pads the field (left/right/centered as specified) to bring its - length up to the maximum size of the field. Then the separator and - its AlignCtrl-specified padding is appended. - - Pseudo-Code:~ - During pass 1 - | For all fields in the current line - || Determine current separator - || Examine field specified by current separator - || Determine length of field and save if largest thus far - Initialize newline based on initial whitespace option (wWI) - During pass 2 - | For all fields in current line - || Determine current separator - || Extract field specified by current separator - || Prepend/append padding as specified by AlignCtrl - || (right/left/center)-justify to fit field into max-size field - || Append separator with AlignCtrl-specified separator padding - || Delete current line, install newly aligned line - - The g and v AlignCtrl patterns cause the passes not to consider lines - for alignment, either by requiring that the g-pattern be present or - that the v-pattern not be present. - - The whitespace on either side of a separator is ignored. - - -============================================================================== -4. Alignment Maps *alignmaps* *align-maps* {{{1 - - There are a number of maps using Align#AlignCtrl() and Align#Align() - in the file. This file may also be put into the - plugins subdirectory. Since AlignCtrl and Align supercede textab and - its file, the maps either have a leading "t" (for - "textab") or the more complicated ones an "a" (for "alignment") for - backwards compatibility. - - The maps are shown below with a leading backslash (\). Actually, the - construct is used (see |mapleader|), so the maps' leading - kick-off character is easily customized. - - Furthermore, all AlignMapsPlugin.vim maps use the construct (see - ||and |usr_41.txt|). Hence, if one wishes to override the - mapping entirely, one may do that, too. As an example: > - map ACOM AM_acom -< would have \ACOM do what \acom previously did (assuming that the - mapleader has been left at its default value of a backslash). - - \a, : useful for breaking up comma-separated - declarations prior to \adec |alignmap-a,| - \a( : aligns ( and , (useful for prototypes) *alignmap-a(* - \a? : aligns (...)? ...:... expressions on ? and : |alignmap-a?| - \a< : aligns << and >> for c++ |alignmap-a<| - \a= : aligns := assignments |alignmap-a=| - \abox : draw a C-style comment box around text lines |alignmap-abox| - \acom : useful for aligning comments |alignmap-acom| - \adcom: useful for aligning comments in declarations |alignmap-adcom| - \anum : useful for aligning numbers |alignmap-anum| - NOTE: For the visual-mode use of \anum, is needed! - See http://mysite.verizon.net/astronaut/vim/index.html#VIS - \aenum: align a European-style number |alignmap-anum| - \aunum: align a USA-style number |alignmap-anum| - \adec : useful for aligning declarations |alignmap-adec| - \adef : useful for aligning definitions |alignmap-adef| - \afnc : useful for aligning ansi-c style functions' - argument lists |alignmap-afnc| - \adcom: a variant of \acom, restricted to comment |alignmap-adcom| - containing lines only, but also only for - those which don't begin with a comment. - Good for certain declaration styles. - \aocom: a variant of \acom, restricted to comment |alignmap-aocom| - containing lines only - \tab : align a table based on tabs *alignmap-tab* - (converts to spaces) - \tml : useful for aligning the trailing backslashes |alignmap-tml| - used to continue lines (shell programming, etc) - \tsp : use Align to make a table separated by blanks |alignmap-tsp| - (left justified) - \ts, : like \t, but swaps whitespace on the right of *alignmap-ts,* - the commas to their left - \ts: : like \t: but swaps whitespace on the right of *alignmap-ts:* - the colons to their left - \ts< : like \t< but swaps whitespace on the right of *alignmap-ts<* - the less-than signs to their left - \ts= : like \t= but swaps whitespace on the right of *alignmap-ts=* - the equals signs to their left - \Tsp : use Align to make a table separated by blanks |alignmap-Tsp| - (right justified) - \tsq : use Align to make a table separated by blanks |alignmap-tsq| - (left justified) -- "strings" are not split up - \tt : useful for aligning LaTeX tabular tables |alignmap-tt| - \Htd : tabularizes html tables: |alignmap-Htd| - ...field... ...field... - - *alignmap-t|* *alignmap-t#* *alignmap-t,* *alignmap-t:* - *alignmap-t;* *alignmap-t<* *alignmap-t?* *alignmap-t~* - *alignmap-m=* - \tx : make a left-justified alignment on - character "x" where "x" is: ,:<=@|# |alignmap-t=| - \Tx : make a right-justified alignment on - character "x" where "x" is: ,:<=@# |alignmap-T=| - \m= : like \t= but aligns with %... style comments - - The leading backslash is actually (see |mapleader| for how to - customize the leader to be whatever you like). These maps use the - package and are defined in the file. - Although the maps use AlignCtrl options, they typically use the "m" - option which pushes the options (AlignPush). The associated Align - call which follows will then AlignPop the user's original options - back. - - ALIGNMENT MAP USE WITH MARK AND MOVE~ - In the examples below, one may select the text with a "ma" at the - first line, move to the last line, then execute the map. - - ALIGNMENT MAP USE WITH VISUAL MODE~ - Alternatively, one may select the text with the "V" visual mode - command. - - ALIGNMENT MAP USE WITH MENUS~ - One may use the mark-and-move style (ma, move, use the menu) or - the visual mode style (use the V visual mode, move, then select - the alignment map with menu selection). The alignment map menu - items are under DrChip.AlignMaps . - - One may even change the top level menu name to whatever is wished; by - default, its > - let g:DrChipTopLvlMenu= "DrChip." -< If you set the variable to the empty string (""), then no menu items - will be produced. Of course, one must have a vim with +menu, the gui - must be running, and |'go'| must have the menu bar suboption (ie. m - must be included). - - COMPLEX ALIGNMENT MAP METHOD~ - - For those complex alignment maps which do alignment on constructs - (e.g. \acom, \adec, etc), a series of substitutes is used to insert - "@" symbols in appropriate locations. Align#Align() is then used to - do alignment directly on "@"s; then it is followed by further - substitutes to do clean-up. However, the maps \WS and \WE, used by - every map supported by AlignMaps, protect any original embedded "@" - symbols by first converting them to characters, doing the - requested job, and then converting them back. > - - \WS calls AlignMaps#WrapperStart() - \WE calls AlignMaps#WrapperEnd() -< - - --------------------------- - Alignment Map Examples: \a, *alignmap-a,* {{{3 - --------------------------- - - Original: illustrates comma-separated declaration splitting: > - int a,b,c; - struct ABC_str abc,def; -< - Becomes: > - int a; - int b; - int c; - struct ABC_str abc; - struct ABC_str def; -< - - --------------------------- - Alignment Map Examples: \a? *alignmap-a?* {{{3 - --------------------------- - - Original: illustrates ()?: aligning > - printf("<%s>\n", - (x == ABC)? "abc" : - (x == DEFG)? "defg" : - (x == HIJKL)? "hijkl" : "???"); -< - Becomes: select "(x == ..." lines, then \a? > - printf("<%s>\n", - (x == ABC)? "abc" : - (x == DEFG)? "defg" : - (x == HIJKL)? "hijkl" : "???"); -< - - --------------------------- - Alignment Map Examples: \a< *alignmap-a<* {{{3 - --------------------------- - - Original: illustrating aligning of << and >> > - cin << x; - cin << y; - cout << "this is x=" << x; - cout << "but y=" << y << "is not"; -< - Becomes: select "(x == ..." lines, then \a< > - cin << x; - cin << y; - cout << "this is x=" << x; - cout << "but y=" << y << "is not"; -< - - --------------------------- - Alignment Map Examples: \a= *alignmap-a=* {{{3 - --------------------------- - - Original: illustrates how to align := assignments > - aa:=bb:=cc:=1; - a:=b:=c:=1; - aaa:=bbb:=ccc:=1; -< - Bcomes: select the three assignment lines, then \a:= > - aa := bb := cc := 1; - a := b := c := 1; - aaa := bbb := ccc := 1; -< - - --------------------------- - Alignment Map Examples: \abox *alignmap-abox* {{{3 - --------------------------- - - Original: illustrates how to comment-box some text > - This is some plain text - which will - soon be surrounded by a - comment box. -< - Becomes: Select "This..box." with ctrl-v, press \abox > - /*************************** - * This is some plain text * - * which will * - * soon be surrounded by a * - * comment box. * - ***************************/ -< - - --------------------------- - Alignment Map Examples: \acom *alignmap-acom* {{{3 - --------------------------- - - Original: illustrates aligning C-style comments (works for //, too) > - if(itworks) { /* this */ - then= dothis; /* is a */ - } /* set of three comments */ -< - Becomes: Select the three lines, press \acom > - if(itworks) { /* this */ - then= dothis; /* is a */ - } /* set of three comments */ -< - Also see |alignmap-aocom| - - - --------------------------- - Alignment Map Examples: \anum *alignmap-anum* {{{3 - --------------------------- - - Original: illustrates how to get numbers lined up > - -1.234 .5678 -.901e-4 - 1.234 5.678 9.01e-4 - 12.34 56.78 90.1e-4 - 123.4 567.8 901.e-4 -< - Becomes: Go to first line, ma. Go to last line, press \anum > - -1.234 .5678 -.901e-4 - 1.234 5.678 9.01e-4 - 12.34 56.78 90.1e-4 - 123.4 567.8 901.e-4 -< - Original: > - | -1.234 .5678 -.901e-4 | - | 1.234 5.678 9.01e-4 | - | 12.34 56.78 90.1e-4 | - | 123.4 567.8 901.e-4 | -< - Becomes: Select the numbers with ctrl-v (visual-block mode), > - press \anum - | -1.234 .5678 -.901e-4 | - | 1.234 5.678 9.01e-4 | - | 12.34 56.78 90.1e-4 | - | 123.4 567.8 901.e-4 | -< - Original: > - -1,234 ,5678 -,901e-4 - 1,234 5,678 9,01e-4 - 12,34 56,78 90,1e-4 - 123,4 567,8 901,e-4 -< - Becomes: Go to first line, ma. Go to last line, press \anum > - -1,234 ,5678 -,901e-4 - 1,234 5,678 9,01e-4 - 12,34 56,78 90,1e-4 - 123,4 567,8 901,e-4 -< - In addition: - \aenum is provided to support European-style numbers - \aunum is provided to support USA-style numbers - - One may get \aenum behavior for \anum > - let g:alignmaps_euronumber= 1 -< or \aunum behavior for \anum if one puts > - let g:alignmaps_usanumber= 1 -< in one's <.vimrc>. - - - --------------------------- - Alignment Map Examples: \ascom *alignmap-ascom* {{{3 - --------------------------- - - Original: > - /* A Title */ - int x; /* this is a comment */ - int yzw; /* this is another comment*/ -< - Becomes: Select the three lines, press \ascom > - /* A Title */ - int x; /* this is a comment */ - int yzw; /* this is another comment */ -< - - --------------------------- - Alignment Map Examples: \adec *alignmap-adec* {{{3 - --------------------------- - - Original: illustrates how to clean up C/C++ declarations > - int a; - float b; - double *c=NULL; - char x[5]; - struct abc_str abc; - struct abc_str *pabc; - int a; /* a */ - float b; /* b */ - double *c=NULL; /* b */ - char x[5]; /* x[5] */ - struct abc_str abc; /* abc */ - struct abc_str *pabc; /* pabc */ - static int a; /* a */ - static float b; /* b */ - static double *c=NULL; /* b */ - static char x[5]; /* x[5] */ - static struct abc_str abc; /* abc */ - static struct abc_str *pabc; /* pabc */ -< - Becomes: Select the declarations text, then \adec > - int a; - float b; - double *c = NULL; - char x[5]; - struct abc_str abc; - struct abc_str *pabc; - int a; /* a */ - float b; /* b */ - double *c = NULL; /* b */ - char x[5]; /* x[5] */ - struct abc_str abc; /* abc */ - struct abc_str *pabc; /* pabc */ - static int a; /* a */ - static float b; /* b */ - static double *c = NULL; /* b */ - static char x[5]; /* x[5] */ - static struct abc_str abc; /* abc */ - static struct abc_str *pabc; /* pabc */ -< - - --------------------------- - Alignment Map Examples: \adef *alignmap-adef* {{{3 - --------------------------- - - Original: illustrates how to line up #def'initions > - #define ONE 1 - #define TWO 22 - #define THREE 333 - #define FOUR 4444 -< - Becomes: Select four definition lines, apply \adef > - # define ONE 1 - # define TWO 22 - # define THREE 333 - # define FOUR 4444 -< - - --------------------------- - Alignment Map Examples: \afnc *alignmap-afnc* {{{3 - --------------------------- - - This map is an exception to the usual selection rules. - It uses "]]" to find the function body's leading "{". - Just put the cursor anywhere in the function arguments and - the entire function declaration should be processed. - - Because "]]" looks for that "{" in the first column, the - "original" and "becomes" examples are in the first column, - too. - - Original: illustrates lining up ansi-c style function definitions > - int f( - struct abc_str ***a, /* one */ - long *b, /* two */ - int c) /* three */ - { - } -< - Becomes: put cursor anywhere before the '{', press \afnc > - int f( - struct abc_str ***a, /* one */ - long *b, /* two */ - int c) /* three */ - { - } -< - - --------------------------- - Alignment Map Examples: \adcom *alignmap-adcom* {{{3 - --------------------------- - - Original: illustrates aligning comments that don't begin - lines (optionally after some whitespace). > - struct { - /* this is a test */ - int x; /* of how */ - double y; /* to use adcom */ - }; -< - Becomes: Select the inside lines of the structure, - then press \adcom. The comment-only - line is ignored but the other two comments - get aligned. > - struct { - /* this is a test */ - int x; /* of how */ - double y; /* to use adcom */ - }; -< - - --------------------------- - Alignment Map Examples: \aocom *alignmap-aocom* {{{3 - --------------------------- - - Original: illustrates how to align C-style comments (works for //, too) - but restricted only to aligning with those lines containing - comments. See the difference from \acom (|alignmap-acom|). > - if(itworks) { /* this comment */ - then= dothis; - } /* only appears on two lines */ -< - Becomes: Select the three lines, press \aocom > - if(itworks) { /* this comment */ - then= dothis; - } /* only appears on two lines */ -< - Also see |alignmap-acom| - - - --------------------------- *alignmap-Tsp* - Alignment Map Examples: \tsp *alignmap-tsp* {{{3 - --------------------------- - - Normally Align can't use white spaces for field separators as such - characters are ignored surrounding field separators. The \tsp and - \Tsp maps get around this limitation. - - Original: > - one two three four five - six seven eight nine ten - eleven twelve thirteen fourteen fifteen -< - Becomes: Select the lines, \tsp > - one two three four five - six seven eight nine ten - eleven twelve thirteen fourteen fifteen -< - Becomes: Select the lines, \Tsp > - one two three four five - six seven eight nine ten - eleven twelve thirteen fourteen fifteen -< - - --------------------------- - Alignment Map Examples: \tsq *alignmap-tsq* {{{3 - --------------------------- - - The \tsp map is useful for aligning tables based on white space, - but sometimes one wants double-quoted strings to act as a single - object in spite of embedded spaces. The \tsq map was invented - to support this. (thanks to Leif Wickland) - - Original: > - "one two" three - four "five six" -< - Becomes: Select the lines, \tsq > - "one two" three - four "five six" -< - - --------------------------- - Alignment Map Examples: \tt *alignmap-tt* {{{3 - --------------------------- - - Original: illustrates aligning a LaTex Table > - \begin{tabular}{||c|l|r||} - \hline\hline - one&two&three\\ \hline - four&five&six\\ - seven&eight&nine\\ - \hline\hline - \end{tabular} -< - Becomes: Select the three lines inside the table > - (ie. one..,four..,seven..) and press \tt - \begin{tabular}{||c|l|r||} - \hline\hline - one & two & three \\ \hline - four & five & six \\ - seven & eight & nine \\ - \hline\hline - \end{tabular} -< - - ---------------------------- - Alignment Map Examples: \tml *alignmap-tml* {{{3 - ---------------------------- - - Original: illustrates aligning multi-line continuation marks > - one \ - two three \ - four five six \ - seven \\ \ - eight \nine \ - ten \ -< - Becomes: > - one \ - two three \ - four five six \ - seven \\ \ - eight \nine \ - ten \ -< - - --------------------------- - Alignment Map Examples: \t= *alignmap-t=* {{{3 - --------------------------- - - Original: illustrates left-justified aligning of = > - aa=bb=cc=1;/*one*/ - a=b=c=1;/*two*/ - aaa=bbb=ccc=1;/*three*/ -< - Becomes: Select the three equations, press \t= > - aa = bb = cc = 1; /* one */ - a = b = c = 1; /* two */ - aaa = bbb = ccc = 1; /* three */ -< - - --------------------------- - Alignment Map Examples: \T= *alignmap-T=* {{{3 - --------------------------- - - Original: illustrates right-justified aligning of = > - aa=bb=cc=1; /* one */ - a=b=c=1; /* two */ - aaa=bbb=ccc=1; /* three */ -< - Becomes: Select the three equations, press \T= > - aa = bb = cc = 1; /* one */ - a = b = c = 1; /* two */ - aaa = bbb = ccc = 1; /* three */ -< - - --------------------------- - Alignment Map Examples: \Htd *alignmap-Htd* {{{3 - --------------------------- - - Original: for aligning tables with html > - ...field one......field two... - ...field three......field four... -< - Becomes: Select ... lines, press \Htd > - ...field one... ...field two... - ...field three... ...field four... -< -============================================================================== -4. Alignment Tools' History *align-history* {{{1 - -ALIGN HISTORY {{{2 - 35 : Nov 02, 2008 * g:loaded_AlignPlugin testing to prevent re-loading - installed - Nov 19, 2008 * new sanity check for an AlignStyle of just ":" - Jan 08, 2009 * save&restore of |'mod'| now done with local - variant - 34 : Jul 08, 2008 * using :AlignCtrl before entering any alignment - control commands was causing an error. - 33 : Sep 20, 2007 * s:Strlen() introduced to support various ways - used to represent characters and their effects - on string lengths. See |align-strlen|. - * Align now accepts "..." -- so it can accept - whitespace as separators. - 32 : Aug 18, 2007 * uses || instead of || plus a - custom argument splitter to allow patterns with - backslashes to slide in unaltered. - 31 : Aug 06, 2007 * :[range]Align! [AlignCtrl settings] pattern(s) - implemented. - 30 : Feb 12, 2007 * now uses |setline()| - 29 : Jan 18, 2006 * cecutil updated to use keepjumps - Feb 23, 2006 * Align now converted to vim 7.0 style using - auto-loading functions. - 28 : Aug 17, 2005 * report option workaround - Oct 24, 2005 * AlignCtrl l: wasn't behaving as expected; fixed - 27 : Apr 15, 2005 : cpo workaround - ignorecase workaround - 26 : Aug 20, 2004 : loaded_align now also indicates version number - GetLatestVimScripts :AutoInstall: now supported - 25 : Jul 27, 2004 : For debugging, uses Dfunc(), Dret(), and Decho() - 24 : Mar 03, 2004 : (should've done this earlier!) visualmode(1) - not supported until v6.2, now Align will avoid - calling it for earlier versions. Visualmode - clearing won't take place then, of course. - 23 : Oct 07, 2003 : Included Leif Wickland's ReplaceQuotedSpaces() - function which supports \tsq - 22 : Jan 29, 2003 : Now requires 6.1.308 or later to clear visualmode() - 21 : Jan 10, 2003 : BugFix: similar problem to #19; new code - bypasses "norm! v\" until initialization - is over. - 20 : Dec 30, 2002 : BugFix: more on "unable to highlight" fixed - 19 : Nov 21, 2002 : BugFix: some terminals gave an "unable to highlight" - message at startup; Hari Krishna Dara tracked it - down; a silent! now included to prevent noise. - 18 : Nov 04, 2002 : BugFix: re-enabled anti-repeated-loading - 17 : Nov 04, 2002 : BugFix: forgot to have AlignPush() push s:AlignSep - AlignCtrl now clears visual-block mode when used so - that Align won't try to use old visual-block - selection marks '< '> - 16 : Sep 18, 2002 : AlignCtrl <>| options implemented (separator - justification) - 15 : Aug 22, 2002 : bug fix: AlignCtrl's ":" now acts as a modifier of - the preceding alignment operator (lrc) - 14 : Aug 20, 2002 : bug fix: AlignCtrl default now keeps &ic unchanged - bug fix: Align, on end-field, wasn't using correct - alignop bug fix: Align, on end-field, was appending - padding - 13 : Aug 19, 2002 : bug fix: zero-length g/v patterns are accepted - bug fix: always skip blank lines - bug fix: AlignCtrl default now also clears g and v - patterns - 12 : Aug 16, 2002 : moved keep_ic above zero-length pattern checks - added "AlignCtrl default" - fixed bug with last field getting separator spaces - at end line - 11 : Jul 08, 2002 : prevent separator patterns which match zero length - -+: included as additional alignment/justification - styles - 10 : Jun 26, 2002 : =~# used instead of =~ (for matching case) - ignorecase option handled - 9 : Jun 25, 2002 : implemented cyclic padding - -ALIGNMENT MAP HISTORY *alignmap-history* {{{2 - v41 Nov 02, 2008 * g:loaded_AlignMapsPlugin testing to prevent - re-loading installed - * AlignMaps now use 0x0f (ctrl-p) for special - character substitutions (instead of 0xff). - Seems to avoid some problems with having to - use Strlen(). - * bug fixed with \ts, - * new maps: \ts; \ts, \ts: \ts< \ts= \a( - v40 Oct 21, 2008 * Modified AlignMaps so that its maps use s - and