tmux 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 225f31971e201d9baeeec68e3f920d8a72f727012a15e0617bb09d551a0af4a9
4
- data.tar.gz: 103f4cbd898b274d9901e825c3eecb95fdd534d2178fe6a59428066e58448f59
3
+ metadata.gz: 23df323bead080f14d354e022382c975a8abfd8a1e9bf2e1cc97e48a4a58adfe
4
+ data.tar.gz: 19f81109a746188a54ab245f7f072823bc776b47480c22ae9bbe5d56bb96cd06
5
5
  SHA512:
6
- metadata.gz: 3006eeaaca5dbf9449c9c2f8081096cc4c172c1f2cb3b1933348409b4a9f231522749213e025f0a187e0ceccbb2eaf63a6905fca3f772d8f58682f6ab5034bbf
7
- data.tar.gz: 316d61e9d40ae7c52f4352f350d38cb4f78c9b42c5bc047b2cab32d04ab66c4f1a646eeea52de19bee5b6f7111e29db325167381d5203410b5b617ef00228f8f
6
+ metadata.gz: 128d863c330c583c0dde063c580703be9acb1b09beaa65cbacc0f94ed1468b5ea46a26d50ae7908a8803abdf7ed8cbb84dcbf9225b619a17acf2edefc899313c
7
+ data.tar.gz: 3779b8111d62b90df1f6f6112245e46aba9086a3ad52c498797b41930e4eefa0729819f686730a48fca3093b2d07c08a8a3032aa283706d0c9d37237f6dddd33
data/CHANGELOG.md CHANGED
@@ -1,6 +1,61 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.0 (unreleased)
3
+ ## 0.3.0 (2026-11-02)
4
+
5
+ ### Library
6
+
7
+ - Configuration files can `require` the Ruby module of an installed tmux
8
+ plugin by name, such as `require "tmux-ai-attn"`. tmux.rb looks in each
9
+ `--plugin-path`, then `TMUX_RB_PLUGIN_PATH`, then TPM's plugin directory,
10
+ and adds the `lib` directory of each plugin that ships
11
+ `lib/<its directory name>.rb` to the end of the load path. The first copy
12
+ of a plugin found wins.
13
+ - `use` writes a `# --- Name (file) ---` comment above each component it
14
+ splices in, naming the component and the file that defines its
15
+ `to_config`, so the generated config shows where each part begins.
16
+ `append` still splices without one.
17
+ This changes the output of configurations that use `use`: regenerate
18
+ any compiled config you compare against a checked-in copy.
19
+ - `Tmux.segments` holds named format blocks that compile, in order, to one
20
+ format. `insert` (`before:`/`after:`), `replace`, and `remove` adjust them
21
+ by name, so one part of a configuration can change a status line another
22
+ part defines. Options accept them, and anything else with `to_format`, as
23
+ values.
24
+
25
+ ### Development
26
+
27
+ - Merging a version bump to main tags it and creates a GitHub release once
28
+ CI passes on that commit, with the version's CHANGELOG section as the
29
+ notes (`script/release-notes VERSION` prints it). A test fails if the
30
+ current version has no CHANGELOG section.
31
+
32
+ ## 0.2.0 (2026-10-23)
33
+
34
+ ### Library
35
+
36
+ - `bind(key)` with no command or block returns a chain of named commands:
37
+ `bind("-").split(:vertical).cwd(:current)`, `bind("c").new_window`.
38
+ - Named binding commands `split`, `new_window`, `cwd`, `resize_pane`, `zoom`,
39
+ `kill_pane`, `kill_window`, and `source`, and a direction for
40
+ `select_pane`. `split` accepts `:vertical`/`:horizontal` or the shorthand
41
+ `:v`/`:h`. They work in chains and in binding blocks.
42
+ - `comment` writes `#` lines into the generated file, and `hook` sets a
43
+ tmux hook (command string or block, optional `index:` slot, `:global`,
44
+ `:window`, or `:pane` scope).
45
+
46
+ ### Fixes
47
+
48
+ - `shell(...)` conditions reach the shell exactly as written. tmux no longer
49
+ expands `$` variables when the file loads or rejects shell syntax such as
50
+ `${VAR:-default}`.
51
+
52
+ ### Documentation
53
+
54
+ - The README opens with a hand-written tmux.conf beside its tmux.rb version,
55
+ and Examples move up ahead of Why. Tests check that both versions load
56
+ identically and that the key binding examples match their tmux comments.
57
+
58
+ ## 0.1.0 (2026-10-21)
4
59
 
5
60
  First public release, as the `tmux` gem (`require "tmux"`), with the
6
61
  `tmux.rb` command (also installed as `tmux_rb`).
data/README.md CHANGED
@@ -3,6 +3,59 @@
3
3
  tmux.rb is a Ruby DSL that compiles readable, structured block-based
4
4
  configuration into native tmux configuration and format strings.
5
5
 
6
+ ## At a glance
7
+
8
+ A small, hand-written `~/.tmux.conf`:
9
+
10
+ <!-- glance: tmux -->
11
+ ```tmux
12
+ set -g prefix C-a
13
+ unbind C-b
14
+ bind C-a send-prefix
15
+
16
+ set -g mouse on
17
+ set -g base-index 1
18
+ setw -g mode-keys vi
19
+
20
+ bind | split-window -h -c "#{pane_current_path}"
21
+ bind - split-window -v -c "#{pane_current_path}"
22
+ bind r source-file ~/.tmux.conf \; display-message "Reloaded"
23
+
24
+ set -g status-right "#{?window_zoomed_flag,#[fg=yellow]ZOOM #[fg=default],}#S"
25
+ ```
26
+
27
+ The same configuration in tmux.rb, which compiles to a file tmux loads
28
+ identically:
29
+
30
+ <!-- glance: ruby -->
31
+ ```ruby
32
+ Tmux.configure do
33
+ global.prefix = "C-a"
34
+ unbind "C-b"
35
+ bind("C-a").command(:send_prefix)
36
+
37
+ global.mouse = true
38
+ global.base_index = 1
39
+ window.mode_keys = :vi
40
+
41
+ bind("|").split(:h, cwd: :current)
42
+ bind("-").split(:v, cwd: :current)
43
+ bind("r")
44
+ .source("~/.tmux.conf")
45
+ .display_message("Reloaded")
46
+
47
+ global.status.right = Tmux.format do
48
+ if?(Tmux.window_zoomed_flag) do
49
+ style(fg: :yellow) { text "ZOOM " }
50
+ end
51
+ text Tmux.session_name
52
+ end
53
+ end
54
+ ```
55
+
56
+ The payoff grows with the configuration. Status lines are where hand-written
57
+ tmux gets hardest to read, and where the format DSL helps most:
58
+
6
59
  <!-- example: intro -->
7
60
  ```ruby
8
61
  # ~/.config/tmux/tmux.rb
@@ -19,7 +72,7 @@ Tmux.configure do
19
72
  left_segment "#{Tmux.session_name}@#{Tmux.host}", bg: :blue, fg: :black
20
73
  end
21
74
 
22
- bind "|", %q{split-window -h -c "#{pane_current_path}"}
75
+ bind("|").split(:horizontal, cwd: :current)
23
76
  end
24
77
  ```
25
78
 
@@ -43,6 +96,18 @@ the status bar set to the terminal's own colors. Named colors such as `:blue`,
43
96
  everywhere. Powerline edges need a font with Powerline glyphs, such as a
44
97
  [Nerd Font](https://www.nerdfonts.com).
45
98
 
99
+ ## Examples
100
+
101
+ - [examples/author_config.rb](https://github.com/cosmicbuffalo/tmux.rb/blob/main/examples/author_config.rb)
102
+ is the author's complete tmux configuration: structured status bars, pane
103
+ borders, and window tabs, plus integration with
104
+ [tmux-ai-attn](https://github.com/cosmicbuffalo/tmux-ai-attn).
105
+ - [examples/popular_configs](https://github.com/cosmicbuffalo/tmux.rb/blob/main/examples/popular_configs/README.md)
106
+ contains ten ports of well-known public tmux configurations. Each pinned
107
+ upstream config sits beside its Ruby version for comparison.
108
+ - [examples/window_status.rb](https://github.com/cosmicbuffalo/tmux.rb/blob/main/examples/window_status.rb)
109
+ is a standalone format file.
110
+
46
111
  ## Why
47
112
 
48
113
  Hand-written tmux configuration gets hard to change once it grows: status
@@ -593,6 +658,31 @@ end
593
658
 
594
659
  </details>
595
660
 
661
+ ### Named segments
662
+
663
+ `Tmux.segments` holds format blocks under names and compiles them, in order,
664
+ to one format, so part of a configuration can adjust a status line another
665
+ part defines: `insert` a segment `before:` or `after:` a named one, `replace`
666
+ one in place, or `remove` some. Each block is an ordinary format block, and
667
+ all of them run on one builder, so powerline edges join their neighbors as if
668
+ written together. Assign the result to an option like any format.
669
+
670
+ ```ruby
671
+ # Shared by every machine.
672
+ right = Tmux.segments do
673
+ segment(:path) { left_segment Tmux.pane_current_path, bg: "#2d2d30", fg: :white }
674
+ segment(:host) { left_segment [Tmux.session_name, "@", Tmux.host], bg: "#5eaceb", fg: :black }
675
+ end
676
+
677
+ # One machine adds a clock; a phone-sized variant drops the path.
678
+ right.insert(:clock, before: :host) { left_segment(bg: "#4e4e4e", fg: :white) { strftime " %H:%M " } }
679
+ right.remove(:path) if compact
680
+
681
+ Tmux.configure { global.status.right = right }
682
+ ```
683
+
684
+ An unknown name raises an error listing the segments there are.
685
+
596
686
  ### Expanding options
597
687
 
598
688
  `expand_option` inserts a user option's value and expands it as a format, for
@@ -825,11 +915,74 @@ end
825
915
 
826
916
  ### Key bindings
827
917
 
828
- `bind` maps a key to a tmux command string or a block of commands. Use the
829
- block form to pass command arguments without quoting them by hand.
830
- `table:` picks a key table, `no_prefix: true` binds without the prefix (`-n`),
831
- `repeat: true` allows repeating (`-r`), and `note:` adds a description (`-N`).
832
- `unbind` removes a binding.
918
+ `bind` maps a key to commands. Name the commands in a chain, write a block of
919
+ commands, or pass a tmux command string. `table:` picks a key table,
920
+ `no_prefix: true` binds without the prefix (`-n`), `repeat: true` allows
921
+ repeating (`-r`), and `note:` adds a description (`-N`). `unbind` removes a
922
+ binding.
923
+
924
+ Given only a key, `bind` returns a chain. Each method adds a command, and
925
+ `cwd` sets the directory for the `split` or `new_window` before it:
926
+
927
+ ```ruby
928
+ Tmux.configure do
929
+ # tmux: bind-key "-" split-window -v -c "#{pane_current_path}"
930
+ bind("-").split(:vertical).cwd(:current)
931
+
932
+ # tmux: bind-key "|" split-window -h -l "30%" -c "~/src"
933
+ bind("|").split(:horizontal, size: "30%", cwd: "~/src")
934
+
935
+ # tmux: bind-key "c" new-window
936
+ bind("c").new_window
937
+
938
+ # Commands run in order: a named window, then back to the last pane.
939
+ # tmux: bind-key "C" new-window -n "scratch" -c "#{pane_current_path}" \; select-pane -t "{last}"
940
+ bind("C").new_window(name: "scratch").cwd(:current).select_pane(target: "{last}")
941
+
942
+ # tmux: bind-key -r "h" select-pane -L
943
+ bind("h", repeat: true).select_pane(:left)
944
+
945
+ # tmux: bind-key -r "<" resize-pane -L 10
946
+ bind("<", repeat: true).resize_pane(:left, 10)
947
+
948
+ # tmux: bind-key -n "M-z" resize-pane -Z
949
+ bind("M-z", no_prefix: true).zoom
950
+
951
+ # tmux: bind-key "r" source-file "~/.tmux.conf" \; display-message "Reloaded"
952
+ bind("r").source("~/.tmux.conf").display_message("Reloaded")
953
+ end
954
+ ```
955
+
956
+ `split` takes tmux's direction names: `:vertical` (`-v`) puts the new pane
957
+ below, and `:horizontal` (`-h`) puts it to the right. `:v` and `:h` are
958
+ shorthand for them. Pane directions are
959
+ `:left`, `:right`, `:up`, and `:down`. The named commands are `split`,
960
+ `new_window`, `select_pane`, `resize_pane`, `zoom`, `kill_pane`,
961
+ `kill_window`, `source`, `display_message`, `display_menu`, `copy_mode`, and
962
+ `load_config`. Use `command` for any other tmux command (its arguments are
963
+ quoted for you) and `raw` for a command written exactly as tmux expects it.
964
+
965
+ The block form uses the same methods, one command per line, so `cwd` on its
966
+ own line applies to the `split` above it:
967
+
968
+ ```ruby
969
+ Tmux.configure do
970
+ # tmux: bind-key "|" split-window -h -c "some-dir"
971
+ bind "|" do
972
+ split :h # or :horizontal
973
+ cwd "some-dir"
974
+ end
975
+
976
+ # tmux: bind-key "C" new-window -n "scratch" -c "#{pane_current_path}" \; select-pane -t "{last}"
977
+ bind "C" do
978
+ new_window name: "scratch"
979
+ cwd :current
980
+ select_pane target: "{last}"
981
+ end
982
+ end
983
+ ```
984
+
985
+ Command strings pass through as written:
833
986
 
834
987
  ```ruby
835
988
  Tmux.configure do
@@ -869,9 +1022,8 @@ Tmux.configure do
869
1022
  end
870
1023
  ```
871
1024
 
872
- A binding block offers `command` for any tmux command (its arguments are
873
- quoted for you), `select_pane`, `copy_mode`, `display_message`,
874
- `display_menu`, `load_config`, and `raw`:
1025
+ Blocks suit longer bindings, such as a menu or a command with no named
1026
+ helper:
875
1027
 
876
1028
  ```ruby
877
1029
  Tmux.configure do
@@ -888,10 +1040,10 @@ Tmux.configure do
888
1040
  end
889
1041
  end
890
1042
 
891
- # Any command, with quoted arguments; select_pane can target a pane.
892
- # tmux: bind-key "N" new-window "-c" "#{pane_current_path}" \; select-pane -t "{last}"
893
- bind "N" do
894
- command :new_window, "-c", "\#{pane_current_path}"
1043
+ # Any command, with quoted arguments.
1044
+ # tmux: bind-key "S" swap-pane "-s" "{last}" \; select-pane -t "{last}"
1045
+ bind "S" do
1046
+ command :swap_pane, "-s", "{last}"
895
1047
  select_pane target: "{last}"
896
1048
  end
897
1049
 
@@ -910,16 +1062,16 @@ return one and several bindings can share it:
910
1062
  Tmux.configure do
911
1063
  def split_here(direction)
912
1064
  commands do
913
- command :split_window, direction, "-c", "\#{pane_current_path}"
1065
+ split direction, cwd: :current
914
1066
  display_message "split"
915
1067
  end
916
1068
  end
917
1069
 
918
- # tmux: bind-key "|" split-window "-h" -c "#{pane_current_path}" \; display-message "split"
919
- bind "|", split_here("-h")
1070
+ # tmux: bind-key "|" split-window -h -c "#{pane_current_path}" \; display-message "split"
1071
+ bind "|", split_here(:horizontal)
920
1072
 
921
- # tmux: bind-key "-" split-window "-v" -c "#{pane_current_path}" \; display-message "split"
922
- bind "-", split_here("-v")
1073
+ # tmux: bind-key "-" split-window -v -c "#{pane_current_path}" \; display-message "split"
1074
+ bind "-", split_here(:vertical)
923
1075
  end
924
1076
  ```
925
1077
 
@@ -1004,12 +1156,36 @@ Tmux.configure do
1004
1156
  end
1005
1157
  ```
1006
1158
 
1159
+ ### Comments and hooks
1160
+
1161
+ `comment` writes `#` lines into the generated file, for whoever reads or edits
1162
+ it. `hook` sets a tmux hook from a command string or a block of commands, as
1163
+ `bind` does; `index:` gives it its own slot so setting it again replaces that
1164
+ slot rather than adding a copy, and `scope:` picks `:global` (session hooks),
1165
+ `:window`, or `:pane`.
1166
+
1167
+ ```ruby
1168
+ Tmux.configure do
1169
+ # # Snapshot sessions whenever one closes.
1170
+ comment "Snapshot sessions whenever one closes."
1171
+
1172
+ # tmux: set-hook -g "session-closed[100]" "run-shell -b \"save-sessions\""
1173
+ hook "session-closed", %q{run-shell -b "save-sessions"}, index: 100
1174
+
1175
+ # tmux: set-hook -gw "pane-focus-in" "display-message \"focused\""
1176
+ hook("pane-focus-in", scope: :window) { display_message "focused" }
1177
+ end
1178
+ ```
1179
+
1007
1180
  ### Raw commands and composition
1008
1181
 
1009
1182
  `raw` passes tmux commands through verbatim (one per line; a trailing `\`
1010
1183
  continues a line), and `blank` adds an empty line. `append` includes another
1011
1184
  configuration's statements, and `use` accepts any object that responds to
1012
- `to_config`, such as a plugin's Ruby package.
1185
+ `to_config`, such as a plugin's Ruby package or one part of a configuration
1186
+ split across files. `use` writes a comment above the part naming it and the
1187
+ file its `to_config` is defined in (relative to the calling file's directory
1188
+ when it is inside it), so the generated config shows where each part begins.
1013
1189
 
1014
1190
  ```ruby
1015
1191
  shared = Tmux.configure { global.history_limit = 50_000 } # set-option -g history-limit 50000
@@ -1026,21 +1202,44 @@ Tmux.configure do
1026
1202
 
1027
1203
  # Another configuration's statements, in place.
1028
1204
  append shared
1029
- use clipboard
1205
+ use clipboard # preceded by "# --- Object (config.rb) ---"
1030
1206
  end
1031
1207
  ```
1032
1208
 
1033
- ## Examples
1209
+ ### Plugins
1034
1210
 
1035
- - [examples/author_config.rb](https://github.com/cosmicbuffalo/tmux.rb/blob/main/examples/author_config.rb)
1036
- is the author's complete tmux configuration: structured status bars, pane
1037
- borders, and window tabs, plus integration with
1038
- [tmux-ai-attn](https://github.com/cosmicbuffalo/tmux-ai-attn).
1039
- - [examples/popular_configs](https://github.com/cosmicbuffalo/tmux.rb/blob/main/examples/popular_configs/README.md)
1040
- contains ten ports of well-known public tmux configurations. Each pinned
1041
- upstream config sits beside its Ruby version for comparison.
1042
- - [examples/window_status.rb](https://github.com/cosmicbuffalo/tmux.rb/blob/main/examples/window_status.rb)
1043
- is a standalone format file.
1211
+ A configuration file can `require` the Ruby module of an installed tmux
1212
+ plugin by the plugin's name, however it was installed:
1213
+
1214
+ ```ruby
1215
+ require "tmux-ai-attn"
1216
+
1217
+ Tmux.configure do
1218
+ use TmuxAiAttn
1219
+ end
1220
+ ```
1221
+
1222
+ A plugin opts in by shipping `lib/<its directory name>.rb`, such as
1223
+ `tmux-ai-attn/lib/tmux-ai-attn.rb`. tmux.rb looks for plugins in this order;
1224
+ each place is either a plugin checkout or a directory of them, and the first
1225
+ copy of a plugin found wins:
1226
+
1227
+ 1. each `--plugin-path DIR` given to `build`, `check`, `diff`, or `load`
1228
+ 2. each entry of `TMUX_RB_PLUGIN_PATH`, separated by `:` like `PATH`
1229
+ 3. [TPM](https://github.com/tmux-plugins/tpm)'s plugin directory:
1230
+ `$TMUX_PLUGIN_MANAGER_PATH`, which TPM sets inside tmux, or else
1231
+ `~/.tmux/plugins` and `~/.config/tmux/plugins`
1232
+
1233
+ So a plugin installed with TPM needs no setup, and one cloned anywhere else
1234
+ needs only its location:
1235
+
1236
+ ```bash
1237
+ TMUX_RB_PLUGIN_PATH=~/src/tmux-ai-attn tmux.rb build tmux.rb --output ~/.tmux.conf
1238
+ ```
1239
+
1240
+ Only opted-in plugins' `lib` directories join Ruby's load path, after the
1241
+ entries already there, so `-I` and `RUBYLIB` take precedence. A failed
1242
+ `require` reports where tmux.rb looked.
1044
1243
 
1045
1244
  ## Development
1046
1245
 
@@ -1049,6 +1248,10 @@ bundle install
1049
1248
  bundle exec rake test
1050
1249
  ```
1051
1250
 
1251
+ `mise.toml` pins the Ruby that CI packages and releases with (3.4), so with
1252
+ [mise](https://mise.jdx.dev) installed, `mise install` in the checkout gets
1253
+ it, Bundler included.
1254
+
1052
1255
  `bundle exec rake test` uses the tmux on your `PATH`.
1053
1256
  `bundle exec rake test:tmux` builds each tmux version CI tests (3.2a, the
1054
1257
  newest release of each later minor version, and the development branch)
data/lib/tmux/cli.rb CHANGED
@@ -20,6 +20,7 @@ module Tmux
20
20
  @stdout = stdout
21
21
  @stderr = stderr
22
22
  @tmux_executable = "tmux"
23
+ @plugin_path = []
23
24
  end
24
25
 
25
26
  def run(arguments)
@@ -125,6 +126,9 @@ module Tmux
125
126
  opts.banner = "usage: tmux.rb #{synopsis}"
126
127
  yield opts if block_given?
127
128
  opts.on("--tmux PATH", "Target this tmux executable (default: tmux on PATH)") { |path| @tmux_executable = path }
129
+ opts.on("--plugin-path DIR", "Look for plugins in DIR (a plugin or a directory of them) first; repeatable") do |dir|
130
+ @plugin_path << dir
131
+ end
128
132
  opts.on("-h", "--help", "Show this help") { early = :help }
129
133
  opts.on("--version", "Show the tmux.rb version") { early = :version }
130
134
  end
@@ -145,14 +149,23 @@ module Tmux
145
149
  # Errors raised while the configuration runs are reported with the line
146
150
  # in the configuration file that raised them.
147
151
  def load_source(path)
148
- Tmux.load_file(path, tmux: @tmux_executable)
152
+ Tmux.load_file(path, tmux: @tmux_executable, plugin_path: @plugin_path)
149
153
  rescue SyntaxError => error
150
154
  raise Error, error.message
151
155
  rescue StandardError, ScriptError => error
152
156
  location = location_in(error, File.expand_path(path))
153
157
  raise if location.nil? && (error.is_a?(Error) || error.is_a?(SystemCallError))
154
158
 
155
- raise Error, "#{location || path}: #{error.message} (#{error.class})"
159
+ raise Error, "#{location || path}: #{error.message} (#{error.class})#{plugin_hint(error)}"
160
+ end
161
+
162
+ # For a failed require: where tmux.rb looked for plugins.
163
+ def plugin_hint(error)
164
+ return "" unless error.is_a?(LoadError)
165
+
166
+ "\n(plugins are looked up in #{Plugins.search_path(extra: @plugin_path).join(", ")}; " \
167
+ "add others with --plugin-path or TMUX_RB_PLUGIN_PATH. " \
168
+ "A plugin is found by name when it ships lib/<its directory name>.rb)"
156
169
  end
157
170
 
158
171
  # The innermost backtrace frame inside the configuration file itself.
@@ -32,6 +32,20 @@ module Tmux
32
32
  # separate entries until the binding is compiled, so callers never write tmux
33
33
  # command separators or quote command arguments by hand.
34
34
  class CommandBuilder
35
+ # A command built by one of the named helpers below, kept in parts so a
36
+ # modifier such as #cwd can still add a flag before it compiles.
37
+ Typed = Struct.new(:name, :flags) do
38
+ def to_s = [name, *flags].join(" ")
39
+ end
40
+ private_constant :Typed
41
+
42
+ # tmux's own names: a vertical split (-v) stacks the new pane below, a
43
+ # horizontal one (-h) puts it to the right. :v and :h are shorthand.
44
+ SPLIT_DIRECTIONS = { vertical: "-v", v: "-v", horizontal: "-h", h: "-h" }.freeze
45
+ PANE_DIRECTIONS = { left: "-L", right: "-R", up: "-U", down: "-D" }.freeze
46
+ CWD_COMMANDS = %w[split-window new-window].freeze
47
+ private_constant :SPLIT_DIRECTIONS, :PANE_DIRECTIONS, :CWD_COMMANDS
48
+
35
49
  def initialize = @commands = []
36
50
 
37
51
  # Any tmux command. Arguments are quoted for you; tmux expands $VARIABLES
@@ -48,13 +62,59 @@ module Tmux
48
62
  self
49
63
  end
50
64
 
51
- def select_pane(target: nil)
65
+ # split-window. `cwd:` starts the new pane in a directory; :current is the
66
+ # active pane's directory. `size:` is lines/columns or a "30%" string.
67
+ def split(direction, cwd: nil, size: nil)
68
+ flag = SPLIT_DIRECTIONS.fetch(direction) do
69
+ raise Error, "split direction must be :vertical (:v) or :horizontal (:h), not #{direction.inspect}"
70
+ end
71
+ flags = [flag]
72
+ flags.concat(["-l", ConfigCompiler.quote(size)]) if size
73
+ typed("split-window", flags, cwd:)
74
+ end
75
+
76
+ def new_window(name: nil, cwd: nil)
77
+ flags = []
78
+ flags.concat(["-n", ConfigCompiler.quote(name)]) if name
79
+ typed("new-window", flags, cwd:)
80
+ end
81
+
82
+ # Start the previous command (split or new_window) in `directory`;
83
+ # :current is the active pane's directory.
84
+ def cwd(directory)
85
+ last = @commands.last
86
+ unless last.is_a?(Typed) && CWD_COMMANDS.include?(last.name)
87
+ raise Error, "cwd must follow split or new_window"
88
+ end
89
+ raise Error, "#{last.name} already has a directory" if last.flags.include?("-c")
90
+
91
+ last.flags.concat(["-c", ConfigCompiler.quote(directory == :current ? "\#{pane_current_path}" : directory)])
92
+ self
93
+ end
94
+
95
+ # select-pane, by direction (:left, :right, :up, :down) and/or target.
96
+ def select_pane(direction = nil, target: nil)
52
97
  parts = ["select-pane"]
98
+ parts << pane_direction(direction) if direction
53
99
  parts.concat(["-t", ConfigCompiler.quote(target)]) if target
54
100
  @commands << parts.join(" ")
55
101
  self
56
102
  end
57
103
 
104
+ # resize-pane by `amount` cells (tmux's default is 1) in a direction.
105
+ def resize_pane(direction, amount = nil)
106
+ @commands << ["resize-pane", pane_direction(direction), amount&.to_i].compact.join(" ")
107
+ self
108
+ end
109
+
110
+ # Toggle the active pane's zoom (resize-pane -Z).
111
+ def zoom = raw("resize-pane -Z")
112
+ def kill_pane = raw("kill-pane")
113
+ def kill_window = raw("kill-window")
114
+
115
+ # source-file; `quiet: true` (-q) skips a missing file without an error.
116
+ def source(path, quiet: false) = raw("source-file#{' -q' if quiet} #{ConfigCompiler.quote(path)}")
117
+
58
118
  # Send one copy-mode command (`send-keys -X`) to a pane. `count:` maps to
59
119
  # tmux's -N repeat count, used by actions such as scroll-up and scroll-down.
60
120
  def copy_mode(action, target: nil, count: nil)
@@ -91,14 +151,52 @@ module Tmux
91
151
  self
92
152
  end
93
153
 
154
+ def empty? = @commands.empty?
155
+
94
156
  def build
95
157
  raise Error, "a command block must contain at least one command" if @commands.empty?
96
158
 
97
- @commands.join(" \\; ")
159
+ @commands.map(&:to_s).join(" \\; ")
98
160
  end
99
161
 
100
162
  private
101
163
 
164
+ def typed(name, flags, cwd: nil)
165
+ @commands << Typed.new(name, flags)
166
+ cwd ? self.cwd(cwd) : self
167
+ end
168
+
169
+ def pane_direction(direction)
170
+ PANE_DIRECTIONS.fetch(direction) do
171
+ raise Error, "pane direction must be :left, :right, :up, or :down, not #{direction.inspect}"
172
+ end
173
+ end
174
+
102
175
  def normalize(name) = name.to_s.tr("_", "-")
103
176
  end
177
+
178
+ # What `bind(key)` returns without a command or block. Each CommandBuilder
179
+ # method adds a command and rewrites the binding's configuration line, so the
180
+ # chain can stop anywhere: bind("c").new_window.cwd(:current)
181
+ class BindingChain
182
+ attr_reader :key
183
+
184
+ def initialize(key, prefix, nodes, index)
185
+ @key = key
186
+ @prefix = prefix
187
+ @nodes = nodes
188
+ @index = index
189
+ @commands = CommandBuilder.new
190
+ end
191
+
192
+ def empty? = @commands.empty?
193
+
194
+ (CommandBuilder.public_instance_methods(false) - %i[build empty?]).each do |name|
195
+ define_method(name) do |*arguments, **options, &block|
196
+ @commands.public_send(name, *arguments, **options, &block)
197
+ @nodes[@index] = ConfigNode::Command.new("#{@prefix} #{@commands.build}")
198
+ self
199
+ end
200
+ end
201
+ end
104
202
  end
@@ -2,7 +2,8 @@
2
2
 
3
3
  module Tmux
4
4
  # The context of a Tmux.configure block. Every DSL method returns the
5
- # builder (conditionals return a handle for `.else`), so calls can be chained.
5
+ # builder (conditionals return a handle for `.else`, and `bind(key)` a
6
+ # BindingChain), so calls can be chained.
6
7
  class ConfigBuilder
7
8
  include Evaluation
8
9
 
@@ -13,6 +14,7 @@ module Tmux
13
14
  @nodes = []
14
15
  @else_filled = {}
15
16
  @conditional_states = {}
17
+ @open_bindings = []
16
18
  end
17
19
 
18
20
  def switch(cases) = Tmux.switch(cases)
@@ -38,6 +40,32 @@ module Tmux
38
40
  self
39
41
  end
40
42
 
43
+ # A comment in the generated file: one "# " line per line of `text`, and a
44
+ # bare "#" for an empty one. tmux ignores comments; they are for whoever
45
+ # reads or edits the generated config.
46
+ def comment(text)
47
+ text.to_s.each_line(chomp: true) do |line|
48
+ @nodes << ConfigNode::Command.new(line.empty? ? "#" : "# #{line}")
49
+ end
50
+ self
51
+ end
52
+
53
+ # A hook, as set-hook: `name` fires `command`, a tmux command string or a
54
+ # block of commands as for #bind. `index:` gives the hook its own slot
55
+ # (name[index]), so setting it again replaces that slot instead of adding
56
+ # another copy. `scope:` is :global (session hooks), :window, or :pane.
57
+ def hook(name, command = nil, index: nil, scope: :global, &block)
58
+ raise ArgumentError, "hook #{name}: give a command or a block, not both" if command && block
59
+ raise ArgumentError, "hook #{name}: give a command or a block" unless command || block
60
+
61
+ command = commands(&block) if block
62
+ flag = {global: "-g", window: "-gw", pane: "-gp"}.fetch(scope) do
63
+ raise ArgumentError, "hook #{name}: scope must be :global, :window, or :pane"
64
+ end
65
+ slot = index.nil? ? name.to_s : "#{name}[#{Integer(index)}]"
66
+ raw "set-hook #{flag} #{ConfigCompiler.quote(slot)} #{ConfigCompiler.quote(command.to_s, expand: false)}"
67
+ end
68
+
41
69
  # Scoped options are generated from the selected target's complete catalog.
42
70
  def global = option_root(:global)
43
71
  def server = option_root(:server)
@@ -76,21 +104,29 @@ module Tmux
76
104
  ].compact.join(" ")
77
105
  end
78
106
 
107
+ # With neither a command nor a block, bind returns a chain that adds each
108
+ # command to the binding: `bind("-").split(:vertical).cwd(:current)`.
79
109
  def bind(key, command = nil, table: nil, repeat: false, no_prefix: false, note: nil, &block)
80
110
  raise Error, "bind cannot combine table: and no_prefix:" if table && no_prefix
81
111
  raise Error, "bind accepts either a command or a block, not both" if command && block
82
112
 
83
- command = commands(&block) if block
84
- raise Error, "bind requires a command or block" unless command
85
-
86
113
  parts = ["bind-key"]
87
114
  parts << "-r" if repeat
88
115
  parts << "-n" if no_prefix
89
116
  parts.concat(["-N", ConfigCompiler.quote(note)]) if note
90
117
  parts.concat(["-T", ConfigCompiler.quote(table)]) if table
91
118
  parts << ConfigCompiler.quote(key)
92
- parts << command
93
- raw parts.join(" ")
119
+ prefix = parts.join(" ")
120
+
121
+ unless command || block
122
+ chain = BindingChain.new(key, prefix, @nodes, @nodes.size)
123
+ @nodes << ConfigNode::Blank.new # replaced by the chain's first command
124
+ @open_bindings << chain
125
+ return chain
126
+ end
127
+
128
+ command = commands(&block) if block
129
+ raw "#{prefix} #{command}"
94
130
  end
95
131
 
96
132
  # source-file; `quiet: true` (-q) skips a missing file without an error.
@@ -149,10 +185,25 @@ module Tmux
149
185
 
150
186
  # Import another tmux config object into this config. `component` is anything
151
187
  # implementing #to_config (returning a Tmux::Config) — e.g. a plugin's Ruby
152
- # package. Splices its nodes in call order.
153
- def use(component) = append(component.to_config)
188
+ # package. Splices its nodes in call order, under a comment naming the
189
+ # component and the file that defines it, so the generated config shows
190
+ # where each part begins. Use #append to splice without the comment.
191
+ def use(component)
192
+ config = component.to_config
193
+ blank unless @nodes.empty? || @nodes.last.is_a?(ConfigNode::Blank)
194
+ # A configuration file is evaluated, so its frames have only a path.
195
+ caller = caller_locations(1, 1).first
196
+ comment "--- #{component_label(component, caller && (caller.absolute_path || caller.path))} ---"
197
+ append config
198
+ end
154
199
 
155
- def build = Config.new(@nodes, target: target).validate!
200
+ def build
201
+ if (open = @open_bindings.find(&:empty?))
202
+ raise Error, "bind #{open.key.inspect} has no command: chain one, such as .split(:vertical), or pass a command or block"
203
+ end
204
+
205
+ Config.new(@nodes, target: target).validate!
206
+ end
156
207
 
157
208
  private
158
209
 
@@ -181,6 +232,28 @@ module Tmux
181
232
  end.first
182
233
  end
183
234
 
235
+ # "Name (path)" for #use: a module's own name or an object's class name,
236
+ # and the file defining its to_config, relative to the calling file's
237
+ # directory when it is inside it, otherwise with the home directory as ~.
238
+ def component_label(component, caller_path)
239
+ name = component.is_a?(Module) ? component.name : component.class.name
240
+ file = begin
241
+ component.method(:to_config).source_location&.first
242
+ rescue NameError # to_config answered by method_missing
243
+ nil
244
+ end
245
+ [name, file && "(#{display_path(file, caller_path)})"].compact.join(" ")
246
+ end
247
+
248
+ def display_path(file, caller_path)
249
+ file = File.expand_path(file)
250
+ base = caller_path && "#{File.dirname(caller_path)}/"
251
+ return file.delete_prefix(base) if base && file.start_with?(base)
252
+
253
+ home = "#{Dir.home}/"
254
+ file.start_with?(home) ? "~/#{file.delete_prefix(home)}" : file
255
+ end
256
+
184
257
  def write_option(name, value, scope:, append: false, expand: true)
185
258
  @nodes << ConfigNode::SetOption.new(normalize_option(name), value, scope, append, expand)
186
259
  end
@@ -58,7 +58,10 @@ module Tmux
58
58
  parts = ["if-shell"]
59
59
  parts << "-b" if node.background
60
60
  parts << "-F" if node.format
61
- parts << self.class.quote(node.test)
61
+ # A shell test is for the shell: escape $ and a leading ~ so tmux's
62
+ # parser leaves them alone (it rejects shell syntax such as
63
+ # ${VAR:-default} in a double-quoted string).
64
+ parts << self.class.quote(node.test, expand: node.format)
62
65
  text = "#{parts.join(' ')} #{block(node.success)}"
63
66
  text += " #{block(node.failure)}" unless node.failure.empty?
64
67
  text
data/lib/tmux/dsl.rb CHANGED
@@ -16,6 +16,10 @@ module Tmux
16
16
  ConditionalFormat.new(builder, builder.if?(condition, &block))
17
17
  end
18
18
 
19
+ # Named format blocks that can be inserted, replaced, or removed by name
20
+ # before they compile to one format (see Segments).
21
+ def self.segments(&block) = Segments.new(&block)
22
+
19
23
  # left/centre/right zones assembled into one aligned format (see ZoneBuilder).
20
24
  def self.pane_border(&block)
21
25
  builder = ZoneBuilder.new
@@ -141,6 +141,7 @@ module Tmux
141
141
  def write(value, append: false, expand: true)
142
142
  name = settable!("assignment")
143
143
  value = Tmux.style_string(value) if @descriptor[:style] && value.is_a?(Hash)
144
+ value = value.to_format if !value.is_a?(Format) && value.respond_to?(:to_format)
144
145
  @builder.__send__(:write_option, name, value, scope: @scope, append: append, expand: expand)
145
146
  end
146
147
  end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Tmux
4
+ # Lets a configuration file `require` the Ruby module of an installed tmux
5
+ # plugin by name, such as `require "tmux-ai-attn"`, however the plugin was
6
+ # installed: by TPM, by hand, or by another tool.
7
+ #
8
+ # A plugin opts in by shipping lib/<its directory name>.rb. Its lib
9
+ # directory then joins the end of $LOAD_PATH, after -I, RUBYLIB, and
10
+ # anything already there. Plugins that have not opted in are never added,
11
+ # so their files cannot shadow another library.
12
+ module Plugins
13
+ # Where plugins are looked up, in order: each --plugin-path, then each
14
+ # entry of TMUX_RB_PLUGIN_PATH (separated like PATH), then TPM's plugin
15
+ # directory. Each is a plugin checkout or a directory of them. The first
16
+ # copy of a plugin found wins, so an explicit path overrides TPM's copy.
17
+ def self.search_path(env = ENV, extra: [])
18
+ configured = env.fetch("TMUX_RB_PLUGIN_PATH", "").split(File::PATH_SEPARATOR).reject(&:empty?)
19
+ (extra + configured + tpm_directories(env)).map { |path| File.expand_path(path) }.uniq
20
+ end
21
+
22
+ # TMUX_PLUGIN_MANAGER_PATH, which TPM sets in tmux's global environment,
23
+ # or else TPM's default locations.
24
+ def self.tpm_directories(env = ENV)
25
+ if (path = env["TMUX_PLUGIN_MANAGER_PATH"]) && !path.empty?
26
+ return [path]
27
+ end
28
+
29
+ config_home = env["XDG_CONFIG_HOME"]
30
+ config_home = File.join(Dir.home, ".config") if config_home.nil? || config_home.empty?
31
+ [File.join(Dir.home, ".tmux", "plugins"), File.join(config_home, "tmux", "plugins")]
32
+ end
33
+
34
+ # The lib directories of the opted-in plugins on the search path, one per
35
+ # plugin name, in search order.
36
+ def self.load_paths(env = ENV, extra: [])
37
+ found = {}
38
+ search_path(env, extra:).each do |path|
39
+ checkouts = opted_in?(path) ? [path] : Dir.glob(File.join(path, "*")).sort.select { |dir| opted_in?(dir) }
40
+ checkouts.each { |checkout| found[File.basename(checkout)] ||= File.join(checkout, "lib") }
41
+ end
42
+ found.values
43
+ end
44
+
45
+ def self.add_to_load_path(env = ENV, extra: [])
46
+ load_paths(env, extra:).each { |lib| $LOAD_PATH << lib unless $LOAD_PATH.include?(lib) }
47
+ end
48
+
49
+ def self.opted_in?(checkout) = File.file?(File.join(checkout, "lib", "#{File.basename(checkout)}.rb"))
50
+ private_class_method :opted_in?
51
+ end
52
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Tmux
4
+ # An ordered list of named format blocks that compiles to one format, so a
5
+ # status line built in one place can be adjusted in another: a machine's
6
+ # config inserts, replaces, or removes segments by name before the format is
7
+ # assigned. Blocks run in order on a single format builder when the format
8
+ # is built, so powerline edges join neighbors as if written in one block.
9
+ #
10
+ # right = Tmux.segments do
11
+ # segment(:path) { left_segment Tmux.pane_current_path, bg: "colour236", fg: :white }
12
+ # segment(:host) { left_segment Tmux.host, bg: :blue, fg: :black }
13
+ # end
14
+ # right.insert(:clock, before: :host) { left_segment "%H:%M", bg: "colour238", fg: :white }
15
+ # global.status.right = right
16
+ class Segments
17
+ def initialize(&block)
18
+ @segments = []
19
+ Evaluation.run(self, block) if block
20
+ end
21
+
22
+ # The segment names, in order.
23
+ def names = @segments.map(&:first)
24
+
25
+ # Adds a segment at the end.
26
+ def segment(name, &block)
27
+ raise Error, "segment #{name.inspect} needs a block" unless block
28
+ raise Error, "segment #{name.inspect} is already defined" if names.include?(name)
29
+
30
+ @segments << [name, block]
31
+ self
32
+ end
33
+
34
+ # Adds a segment just before or after an existing one.
35
+ def insert(name, before: nil, after: nil, &block)
36
+ raise Error, "insert #{name.inspect}: give before: or after:, not both" if before && after
37
+ raise Error, "insert #{name.inspect}: give before: or after:" unless before || after
38
+ raise Error, "segment #{name.inspect} needs a block" unless block
39
+ raise Error, "segment #{name.inspect} is already defined" if names.include?(name)
40
+
41
+ index = position(before || after)
42
+ @segments.insert(after ? index + 1 : index, [name, block])
43
+ self
44
+ end
45
+
46
+ # Swaps an existing segment's block for a new one, keeping its place.
47
+ def replace(name, &block)
48
+ raise Error, "segment #{name.inspect} needs a block" unless block
49
+
50
+ @segments[position(name)] = [name, block]
51
+ self
52
+ end
53
+
54
+ def remove(*names_to_remove)
55
+ names_to_remove.each { |name| @segments.delete_at(position(name)) }
56
+ self
57
+ end
58
+
59
+ def to_format
60
+ blocks = @segments.map(&:last)
61
+ Tmux.format { blocks.each { |block| evaluate(block) } }
62
+ end
63
+
64
+ def to_tmux = to_format.to_tmux
65
+ alias_method :to_s, :to_tmux
66
+
67
+ private
68
+
69
+ def position(name)
70
+ names.index(name) or
71
+ raise Error, "no segment #{name.inspect}; segments are #{names.map(&:inspect).join(', ')}"
72
+ end
73
+ end
74
+ end
data/lib/tmux/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Tmux
4
- VERSION = "0.1.0"
4
+ VERSION = "0.3.0"
5
5
  end
data/lib/tmux.rb CHANGED
@@ -18,6 +18,8 @@ require_relative "tmux/config_builder"
18
18
  require_relative "tmux/option_tree"
19
19
  require_relative "tmux/condition_compiler"
20
20
  require_relative "tmux/dsl"
21
+ require_relative "tmux/plugins"
22
+ require_relative "tmux/segments"
21
23
 
22
24
  module Tmux
23
25
  # Evaluates a configuration file and returns the Tmux::Config or
@@ -25,9 +27,12 @@ module Tmux
25
27
  # anonymous module, which keeps its constants and methods out of the global
26
28
  # namespace. Configuration files are trusted Ruby: the module is not a
27
29
  # sandbox. Logical operators in DSL conditions are captured before Ruby
28
- # evaluates them, so && / || build deferred tmux expressions.
29
- def self.load_file(path, tmux: nil)
30
+ # evaluates them, so && / || build deferred tmux expressions. The file can
31
+ # `require` the Ruby module of an installed plugin by name (see Plugins);
32
+ # `plugin_path` adds directories to search first.
33
+ def self.load_file(path, tmux: nil, plugin_path: [])
30
34
  target = tmux ? Target.for_executable(tmux) : Target.current
35
+ Plugins.add_to_load_path(extra: plugin_path)
31
36
  Target.with(target) { evaluate_file(path) }
32
37
  end
33
38
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tmux
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nick deLannoy
@@ -61,6 +61,8 @@ files:
61
61
  - lib/tmux/format_compiler.rb
62
62
  - lib/tmux/glyph.rb
63
63
  - lib/tmux/option_tree.rb
64
+ - lib/tmux/plugins.rb
65
+ - lib/tmux/segments.rb
64
66
  - lib/tmux/target.rb
65
67
  - lib/tmux/version.rb
66
68
  - lib/tmux/zone_builder.rb
@@ -86,7 +88,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
86
88
  - !ruby/object:Gem::Version
87
89
  version: '0'
88
90
  requirements: []
89
- rubygems_version: 3.6.7
91
+ rubygems_version: 3.6.9
90
92
  specification_version: 4
91
93
  summary: A readable Ruby DSL that compiles to native tmux configuration
92
94
  test_files: []