Compare commits

...

342 Commits

Author SHA1 Message Date
Kovid Goyal
cd7b4fcd8e version 0.23.1 2021-08-17 11:37:24 +05:30
Kovid Goyal
f67995d5d3 See if we can mollify CodeQL 2021-08-16 22:53:46 +05:30
Kovid Goyal
f0e7344bc8 Use bundled CA certs on Linux binary builds as well
Makes it consistent with macOS
2021-08-16 22:47:53 +05:30
Kovid Goyal
aa525c68c7 Only test bundled CA certs on macOS 2021-08-16 22:26:10 +05:30
Kovid Goyal
a2e25331a5 Dont check Linux CA locations on macOS 2021-08-16 22:23:24 +05:30
Kovid Goyal
d8f09d377f Install ca-certificates on Linux CI machines 2021-08-16 22:15:27 +05:30
Kovid Goyal
cc96cb1c75 Check a few more locations for CA certificates 2021-08-16 22:09:39 +05:30
Kovid Goyal
5966f04656 Add a build test for CA certificate loading 2021-08-16 20:44:47 +05:30
Kovid Goyal
dbce9a8f29 themes kitten: Fix only the first custom theme file being loaded
Fixes #3938
2021-08-16 20:27:21 +05:30
Kovid Goyal
4333552523 Matching windows/tabs: allow matching by recency
``recent:0`` matches the active window/tab, ``recent:1`` matches the
previous window/tab and so on
2021-08-16 18:29:06 +05:30
Kovid Goyal
c00e945f6e Make the clipboard size limit configurable
Fixes #3937
2021-08-16 17:29:36 +05:30
Kovid Goyal
56cb628ee8 macOS: Bundle mozilla's root certificates with kitty
Apple doesnt provide root certificates in a form useable by openssl
which means all ssl based network requests fail, so bundle our own

Fixes #3936
2021-08-16 17:16:03 +05:30
Kovid Goyal
827b6598b2 version 0.23.0 2021-08-16 07:38:02 +05:30
Kovid Goyal
59bafea06d Add some docs for non-interactive theme changing 2021-08-16 07:37:59 +05:30
Kovid Goyal
d61aca40b8 Make link to template.conf a download link 2021-08-16 07:14:49 +05:30
Kovid Goyal
bf704d35a2 Add a link to kitty-themes in the changelog 2021-08-16 07:11:05 +05:30
Kovid Goyal
fbc8881a96 Merge branch 'master' of github.com:kovidgoyal/kitty 2021-08-15 08:28:00 +05:30
Kovid Goyal
8cfb1efb01 hints kitten: Make the --program option work with --linenum-action=self
Fixes #3931
2021-08-15 08:27:25 +05:30
Kovid Goyal
f399b8466c Merge branch 'patch-1' of https://github.com/con-f-use/kitty 2021-08-14 19:42:19 +05:30
con-f-use
437ba69049 docs: typo in hint.rst, adaption to new layout 2021-08-14 15:19:27 +02:00
Kovid Goyal
dbc7e8e85d When dragging word or line selections, ensure the initially selected item is never deselected
This matches behavior in most other programs
Fixes #3930
2021-08-13 20:23:43 +05:30
Kovid Goyal
f3333ce941 Fix getting connection data from ssh command line when -- is used in the command line
This broke the remote file kitten when using the ssh kitten as the later
was changed to use -- recently.

Fixes #3929
2021-08-13 17:14:43 +05:30
Kovid Goyal
97a9261096 ... 2021-08-13 17:04:49 +05:30
Kovid Goyal
5a76dab3c6 ControlMaster must not suppress exceptions 2021-08-13 17:02:27 +05:30
Kovid Goyal
5a92d3f312 Fix a regression that broke the edit action in the remote file kitten 2021-08-13 16:59:40 +05:30
Kovid Goyal
b173dd1c39 Fix error getting editor in remote file kitten not being reported 2021-08-13 16:57:01 +05:30
Kovid Goyal
473e1a6f22 Fix #3926
Apparently nvim assumes cnorm doesn't affect cursor shape. It's
ambiguous whether cnorm should affect it or not. So to prevent
regressions in case other programs assume that as well, have it only
make the cursor visible and blinking, without changing its shape.
2021-08-13 09:31:18 +05:30
Kovid Goyal
9c4a890688 Adjust attenuation based on color 2021-08-11 12:41:09 +05:30
Kovid Goyal
a803c8bcc5 Make the visual bell flash more gentle, especially on dark themes
Fixes #2937
2021-08-11 12:09:25 +05:30
Kovid Goyal
5c7ce18379 Move visual bell code into shaders.c 2021-08-11 12:04:52 +05:30
Andrew Mayorov
aff6fdfa84 Make visual bell flash much more gentle
Right now visual bell makes background flash sharply with bright white
(when configured with darkish color theme). This causes eye strain,
especially prominent in unlit environments.

This change makes background bounce smoothly between regular bg color
and highlight (selection) bg color for the configured visual bell
duration. Intensity is animated with cubic easing functions. It
currently peaks at 20% of the duration, this is hardcoded.

Mark functions computing intensity and easing as inline

Do smarter blending of visual bell flash

Blend highlight color with pegtop's softlight mode over both background
and half as much over foreground. This should help with flash visibility
in light themed and inverted colors contexts.

Blend flash in BACKGROUND pass also

Revert "Do smarter blending of visual bell flash"

This reverts commit 9a269d55c7d04334b1c4891c42914423517dfad6.

Revert "Blend flash in BACKGROUND pass also"

This reverts commit 756332cb9d7576b08db78406e37349aa6d1df156.

Revert "Make visual bell flash much more gentle"

This reverts commit cbfe5d59ada2da690e14c7532a7468b0c307c462.

Render flash overlay in a separate drawcall

Trigger frequent repaints to make for smooth animation

Attenuate flash a bit more
2021-08-11 11:54:43 +05:30
Kovid Goyal
477a652b44 Function to update a theme file 2021-08-11 09:09:07 +05:30
Kovid Goyal
15e0b42f04 Make the regex for commenting settings more robust 2021-08-11 08:46:42 +05:30
Kovid Goyal
b25ea9c863 Fix #3913 2021-08-09 08:37:53 +05:30
Kovid Goyal
c838cb03c9 Do not allow reloading the config to affect allow_remote_control 2021-08-08 15:34:34 +05:30
Kovid Goyal
ba9adc127e Use realpath when creating conf.bak as well 2021-08-08 10:49:41 +05:30
Kovid Goyal
b7d603c4de Atomic save should preserve stat if the file exists 2021-08-08 10:41:46 +05:30
Kovid Goyal
71f1f3aa64 Atomic save should use the target of symlinks 2021-08-08 10:35:38 +05:30
Kovid Goyal
7d1c26202a Add completion for options that take choices 2021-08-08 10:08:15 +05:30
Kovid Goyal
80db2f6558 Completion for theme names 2021-08-08 09:57:57 +05:30
Kovid Goyal
e376c79dda Show the current theme name in kitty.conf as well 2021-08-08 09:42:07 +05:30
Kovid Goyal
5a47e0d2e4 Make reload_conf_in_all_kitties re-useable 2021-08-08 09:38:29 +05:30
Kovid Goyal
ca9143bebc Allow reloading conf in all kitty instances as well 2021-08-08 09:33:36 +05:30
Kovid Goyal
a49f6799de Print usage when no args provided to +runpy 2021-08-08 09:10:47 +05:30
Kovid Goyal
d916ecc4f3 Add a non-interactive mode to the themes kitten 2021-08-08 07:57:14 +05:30
Kovid Goyal
e1ed9aca10 clear_all_mouse_shortcuts -> clear_all_mouse_actions 2021-08-07 21:34:16 +05:30
Kovid Goyal
0e2f1b9405 Merge branch 'fork' of https://github.com/bdeshi/kitty 2021-08-07 21:30:57 +05:30
bdeshi
db5a2d2141 add clear_all_mouse_shortcuts option to clear mouse_maps 2021-08-07 21:33:56 +06:00
Kovid Goyal
a9771dccba Change list position in kittens intro 2021-08-07 18:40:36 +05:30
Kovid Goyal
4849e07c26 Document the themes kitten 2021-08-07 18:38:33 +05:30
Kovid Goyal
4645e78fa7 Reload config in parent kitty when running the themes kitten 2021-08-07 16:54:47 +05:30
Kovid Goyal
9e2590eb15 Set the KITTY_PID env var when running child processes 2021-08-07 16:48:34 +05:30
Kovid Goyal
94575a5cf6 Implement modifying of kitty.conf
An include for the current theme is added and
all existing color related settings are commented out
so that the theme overlays on kitty's default settings.
2021-08-07 16:34:41 +05:30
Kovid Goyal
a597a8d86b Make the recent list functional 2021-08-07 15:31:03 +05:30
Kovid Goyal
3287798efe terminfo: Fix "cnorm" the property for setting the cursor to normal using a solid block rather than a blinking block cursor
cnorm should match the default cursor in kitty, which is a blinking
block. Fixes #3906
2021-08-07 15:15:59 +05:30
Kovid Goyal
d01ac17334 Implement placing of selected theme in kitty config dir 2021-08-07 15:04:32 +05:30
Kovid Goyal
2c96727c45 Implement searching in the themes kitten 2021-08-07 11:17:32 +05:30
Kovid Goyal
ca1b2454bd Fix position output in matcher 2021-08-07 10:45:50 +05:30
Kovid Goyal
064fc17ce3 More work on themes kitten 2021-08-05 21:38:39 +05:30
Kovid Goyal
43ccf9cb41 Draw theme demo 2021-08-05 13:17:16 +05:30
Kovid Goyal
96857a197c Allow default theme to have no settings 2021-08-05 11:20:01 +05:30
Kovid Goyal
079ff7785c ... 2021-08-05 07:47:32 +05:30
Kovid Goyal
d6a6cbe153 Migrate import in test 2021-08-05 07:05:19 +05:30
Kovid Goyal
2486cfd45d Move match() into a more re-useable location 2021-08-05 06:59:24 +05:30
Kovid Goyal
30cb7286db Fix building on macOS
macOS defines newlocale() in xlocale.h
2021-08-05 06:47:45 +05:30
Kovid Goyal
9e7253c179 macOS: Set LANG to en_US if cocoa reports language as en_* that is not a valid locale
Fixes #3899
2021-08-05 06:29:21 +05:30
Kovid Goyal
276a82d1f7 Make get_all_actions() work in binary builds 2021-08-05 06:10:41 +05:30
Kovid Goyal
57ced9bc83 Dont send press event for shift+middle when grabbed
Fixes #3902
2021-08-05 05:03:22 +05:30
Kovid Goyal
3c3662b032 Limit display length for theme names 2021-08-04 23:18:57 +05:30
Kovid Goyal
f490b9a8bd Better error message for get_all_actions() when docstrings are missing 2021-08-04 22:58:05 +05:30
Kovid Goyal
c7ccedae95 ... 2021-08-04 22:27:48 +05:30
Kovid Goyal
03517459db Type check set_mode and reset_mode 2021-08-04 22:25:27 +05:30
Kovid Goyal
96326280e5 Use a pending update when drawing the screen 2021-08-04 22:06:05 +05:30
Kovid Goyal
9b7899780b Implement drawing the list of themes 2021-08-04 21:56:33 +05:30
Kovid Goyal
e01cd057e8 Fix timestamp not being updated in downloaded zip file comment
Also clean up tab bar formatting
2021-08-04 20:34:00 +05:30
Kovid Goyal
ba85ca1991 Finish the tab bar for the themes kitten 2021-08-04 19:06:07 +05:30
Kovid Goyal
92a9b71f21 More work on the themes kitten 2021-08-04 18:43:26 +05:30
Kovid Goyal
e50c26d1b9 Allow using a non-toal dict to init Options objects 2021-08-04 17:06:50 +05:30
Kovid Goyal
7090c24321 More work on the themes kitten 2021-08-04 14:13:09 +05:30
Kovid Goyal
55319cd6d6 FreeType: Round glyph advances
The old code would simply add advances and store as a float with
individual glyph positioning using floor() based on the advance +
offset. This breaks rendering of infinite length ligatures at some font
sizes as they either under or overflow. Rounding the advances seems to
fix it. Dont know if it will have other ill-effects for non infinite
length ligatures. If it does we can test total ligature length and
use rounding only for long ligatures.

Fixes #3896
2021-08-04 08:40:49 +05:30
Kovid Goyal
8a6b51441c More work on themes kitten 2021-08-04 07:36:09 +05:30
Kovid Goyal
36670b49a0 Make creation of kitty-themes.zip atomic 2021-08-03 17:47:47 +05:30
Kovid Goyal
a402d848d2 Work on themes kitten UI 2021-08-03 17:32:15 +05:30
Kovid Goyal
37c563802c typo 2021-08-03 12:58:38 +05:30
Kovid Goyal
2d7032973c Change the semantics of --title slightly
Now it no longer overrides the titles of windows/tabs created in the
session. This allows windows/tabs to have their own titles while fixing
the OS Window's title.
2021-08-03 09:51:53 +05:30
Kovid Goyal
70b5f5bce3 Fix kitty --title not overriding tab titles
It must set the OS Window title permanently.

Fixes #3893
2021-08-03 09:34:13 +05:30
Kovid Goyal
be34af4555 Remove inline from .c files
It is ignored by compilers and hides unused static functions
2021-08-03 09:11:17 +05:30
Kovid Goyal
815539a933 Clean up the docs for tab_bar_style 2021-08-03 08:52:19 +05:30
Kovid Goyal
ab889e2945 A new "slant" style for the tab bar 2021-08-03 08:45:55 +05:30
Kovid Goyal
b3231c8003 Fix a link in the conf docs 2021-08-02 21:58:39 +05:30
Kovid Goyal
5f6cb34f77 placeholder 2021-08-02 21:54:06 +05:30
Kovid Goyal
a99a080c50 More work on theme loading 2021-08-02 21:46:33 +05:30
Kovid Goyal
4a1ca8d582 Move theme parser into kitty code 2021-08-02 18:54:48 +05:30
Kovid Goyal
050eb5660d Start work on themes kitten 2021-08-02 17:56:31 +05:30
Kovid Goyal
13e59df1f8 version 0.22.2 2021-08-02 08:20:33 +05:30
Kovid Goyal
c797944923 Also set first underviced render frame request 2021-08-01 12:59:22 +05:30
Kovid Goyal
ade4e67b51 Possible fix for #3890
Try to ensure we have a functioning displaylink always.
GLFW skips over sleeping monitors during a poll and also
had a bug where the display link was not re-created for a monitor
that already had a glfw monitor entry.

Also add a bunch more debug reporting
2021-08-01 12:53:35 +05:30
Kovid Goyal
656f49f2ff ... 2021-08-01 07:56:55 +05:30
Kovid Goyal
0045244295 All option instances must not share the same color table 2021-07-31 18:44:39 +05:30
Kovid Goyal
6bfb704f6f When going from csd->no csd increase window height to compensate for titlebar.
Sway will send the next configure event (for example when focus changes)
with titlebar height added, so to avoid a sudden resize at that time,
bump the height by the titlebar.
2021-07-31 14:56:45 +05:30
Kovid Goyal
80cebdefcd Better fix for CSD toggling on Wayland
Draw CSD if the compositor wants us to. See #3888
2021-07-31 14:15:38 +05:30
Kovid Goyal
68cd863fe0 version 0.22.1 2021-07-31 12:03:42 +05:30
Kovid Goyal
65e5015d19 Allow linking to discussions in docs 2021-07-31 11:51:03 +05:30
Kovid Goyal
c26665ec4d Wayland: If the compositor turns off server side decorations after turning them on do not draw client side decorations
This matches the behavior of GNOME based clients and in any case sway
seems to get very confused if CSD is drawn.

Fixes #3888
2021-07-31 11:41:27 +05:30
Kovid Goyal
91d82ebf4b Remove unused import 2021-07-31 11:27:29 +05:30
Kovid Goyal
303e4baa58 Add GLFW API to set WM_COMMAND
Also have create_os_window take keyword arguments
2021-07-30 08:35:40 +05:30
Kovid Goyal
3c953d47ca Merge branch 'pr-fix-nix' of https://github.com/egnor/kitty 2021-07-29 14:23:08 +05:30
Kovid Goyal
5e629d5c09 Linux binary: Remove any RPATH build artifacts from bundled libraries
Thanks to Dan Egnor for pointing these out.
2021-07-29 13:12:49 +05:30
Kovid Goyal
c6ec2d4282 Update docs to reflect the fact that the shell is run with both --login and --interactive to read its env vars 2021-07-29 12:40:19 +05:30
Kovid Goyal
66b93a9af8 Merge branch 'pr-doc-editor-fix' of https://github.com/egnor/kitty 2021-07-29 12:24:17 +05:30
egnor
8d5479f55e minor tweaks to wording and formatting 2021-07-28 23:50:11 -07:00
egnor
96ce6c9504 Resolve some duplication in glossary.rst 2021-07-28 23:47:55 -07:00
egnor
0d55865545 more accurately describe editor behavior 2021-07-28 23:44:09 -07:00
Kovid Goyal
a1fc383e6f Cleanup the previous PR 2021-07-29 11:52:14 +05:30
Kovid Goyal
c3807e175d Merge branch 'pr-doc-editor' of https://github.com/egnor/kitty 2021-07-29 11:48:34 +05:30
Kovid Goyal
6f83f76d41 Make reading shell environment a bit more robust
Now ensure that --login flag is not duplicated. Also
run the shell in --interactive as well as --login mode.
2021-07-29 11:12:09 +05:30
egnor
9a56d619af clarify the text for the "editor" config variable slightly 2021-07-28 22:18:03 -07:00
Kovid Goyal
f692d586f7 Fix type checking in send_text 2021-07-29 09:04:07 +05:30
Kovid Goyal
d3d3e99979 broadcast kitten: Fix decoding of key events
No clue why mypy didnt catch this error
2021-07-29 08:55:34 +05:30
egnor
8e6a179efe fix shell.nix error with stdenv.lib.getLib 2021-07-28 17:16:52 -07:00
Kovid Goyal
17ff317d30 Allow specifying additional targets for detach_window 2021-07-28 21:50:09 +05:30
Kovid Goyal
faef9f0049 ... 2021-07-28 21:27:43 +05:30
Kovid Goyal
bb0c831601 Fix #3878 2021-07-28 18:22:08 +05:30
Kovid Goyal
9462654738 Update changelog 2021-07-28 15:52:54 +05:30
Kovid Goyal
e872169e4c Graphics protocol: Fix composing onto currently displayed frame not updating the frame on the GPU. Fixes #3874 2021-07-28 15:46:50 +05:30
Kovid Goyal
a22404abe6 Better names 2021-07-28 15:44:17 +05:30
Kovid Goyal
7c06313750 A couple more useful aliases 2021-07-28 15:40:48 +05:30
Kovid Goyal
6f265f448d DRYer 2021-07-28 15:39:21 +05:30
Kovid Goyal
acdc41bd03 Allow sending no payload 2021-07-28 13:39:15 +05:30
Kovid Goyal
bcff2a7fb6 Add aliases to GraphicsCommand to make it more useable 2021-07-28 13:28:21 +05:30
Kovid Goyal
94188fddce pep8-ify sample code 2021-07-28 11:13:29 +05:30
Kovid Goyal
3684e7f54a Merge branch 'cocoa-fix-m1' of https://github.com/horta/kitty 2021-07-28 07:45:50 +05:30
Danilo Horta
890181172f Fix "Cocoa: Failed to find service port...". 2021-07-28 00:39:50 +01:00
Kovid Goyal
9c9d68561e When calling the active tab idx setter do not re-record the current tab in the active tab history if the current tab will not actually change. Fixes #3871 2021-07-27 09:12:35 +05:30
Kovid Goyal
1bd39ff935 Use new URL scheme and define the kitty website centrally as much as possible 2021-07-27 09:03:11 +05:30
Kovid Goyal
17f3d2d581 DRYer 2021-07-27 08:44:50 +05:30
Kovid Goyal
55aa9e11db Dont use globals for role mapping 2021-07-27 08:39:04 +05:30
Kovid Goyal
bc895eacc5 Also prevent unknown roles from causing formatting to error 2021-07-27 08:07:11 +05:30
Kovid Goyal
6c8eb4a19a Fix #3869 2021-07-27 08:05:55 +05:30
Kovid Goyal
887347106d version 0.22.0 2021-07-26 13:57:09 +05:30
Kovid Goyal
419cf78984 A new remote control command to resize OS Windows 2021-07-25 22:57:00 +05:30
Kovid Goyal
aa339a8a9f Expose parameter in boss.py as well 2021-07-25 13:59:36 +05:30
Kovid Goyal
a2f7aedd9c Allow specifying which os window to toggle 2021-07-25 13:58:03 +05:30
Kovid Goyal
630379651e Use union instead of define for graphics commands aliases 2021-07-25 13:14:52 +05:30
Kovid Goyal
3d9b52fbc2 Functions to get and set OS Window size 2021-07-25 12:58:58 +05:30
Kovid Goyal
2e01c1f37e Wayland: Inform compositor of new window geometry when setting window size 2021-07-25 12:26:09 +05:30
Kovid Goyal
174abb352c Fix broken link 2021-07-24 08:29:25 +05:30
Kovid Goyal
85e028cab1 Add links to kitten source code 2021-07-24 08:15:52 +05:30
Kovid Goyal
ff191c9404 clipboard kitten: fix copies to clipboard not working without the --wait-for-completion option 2021-07-24 07:55:50 +05:30
Kovid Goyal
31da01d4df Add clipboard_control to query_terminal 2021-07-24 07:26:12 +05:30
Kovid Goyal
6d45a94125 Always ignore truncated OSC 52 2021-07-24 07:19:58 +05:30
Kovid Goyal
e7bfb04047 Fix mouse actions not working when caps lock or num lock are engaged
Fixes #3859
2021-07-24 07:06:46 +05:30
Kovid Goyal
b9033d721c print KeyPress on a new line 2021-07-24 07:02:52 +05:30
Kovid Goyal
41c0343d33 macOS: Fix automatic detection of bold/italic faces for fonts that use the family name as the full face name of the regular font not working
Fixes #3861
2021-07-23 23:06:42 +05:30
Kovid Goyal
aa8156a7fd Remove mentions of no-append 2021-07-23 22:28:34 +05:30
Kovid Goyal
e48adf7a07 Allow leading/trailing spaces in tab_activity_symbol 2021-07-23 22:26:10 +05:30
Kovid Goyal
8f214c51c0 Get rid of kitty's special OSC 52 protocol
A better solution from an ecosystem perspective is to just work with the
original protocol. I have modified kitty's escape parser to special case
OSC 52 handling without changing its max escape code size.

Basically, it works by splitting up OSC 52 escape codes longer than the
max size into a series of partial OSC 52 escape codes. These get
dispatched to the UI layer where it accumulates them upto the 8MB limit
and then sends to clipboard when the partial sequence ends.

See https://github.com/ranger/ranger/issues/1861
2021-07-23 22:18:02 +05:30
Kovid Goyal
096c4c78c7 Fix #3856 2021-07-23 08:13:47 +05:30
Kovid Goyal
257fce5a1b Merge branch 'dankamongmen/triangle-wrangle' of https://github.com/dankamongmen/kitty 2021-07-23 08:09:25 +05:30
nick black
182bc7b8f9 U+1fb3f: upper middle left to lower right 🭊🬿 2021-07-22 18:21:57 -04:00
Kovid Goyal
3c35999246 Fix code scanning warning 2021-07-22 22:08:55 +05:30
Kovid Goyal
340159b591 Graphics protocol: Support for frame composition
Fixes #3809
2021-07-22 18:58:59 +05:30
Kovid Goyal
075fb2eaf2 DRYer 2021-07-22 17:56:21 +05:30
Kovid Goyal
21a2768ec3 ... 2021-07-22 17:31:54 +05:30
Kovid Goyal
554c840d4e ssh kitten: exit with 255 for unknown arg to match ssh 2021-07-22 17:30:07 +05:30
Kovid Goyal
9c28a1ba31 ssh kitten: handle -- 2021-07-22 17:03:47 +05:30
Kovid Goyal
13fc921fa5 Dont hardcode the ignore path for sphinx-autobuild 2021-07-22 11:03:13 +05:30
Kovid Goyal
61f5d3972f Dont use scrollIntoView as it causes the main content to scroll as well 2021-07-21 16:39:57 +05:30
Kovid Goyal
5027bc743b Mark sidebar toc entry corresponding to current hash
Also scroll it to the top on initial page load
2021-07-21 14:41:01 +05:30
Kovid Goyal
9b8085220f ... 2021-07-21 14:16:53 +05:30
Kovid Goyal
54c04301cc Use html_css_files instead of add_css_file 2021-07-21 13:12:32 +05:30
Kovid Goyal
cfd3bc823c ... 2021-07-21 12:36:55 +05:30
Kovid Goyal
329d95fd3a Include all in page headings in the sidebar ToC
The furo theme tries to make this impossible, fortunately,
this being python, we dont care what it wants
2021-07-21 10:35:58 +05:30
Kovid Goyal
8dfef58f29 Use a glfw specific name for memfd_create 2021-07-20 21:49:11 +05:30
Kovid Goyal
eeb4d3fe55 Dont show individual tools in the page toc 2021-07-20 14:39:52 +05:30
Kovid Goyal
c6da4576b6 ... 2021-07-20 14:37:31 +05:30
Kovid Goyal
2417122ed3 Make the integration tools link targets 2021-07-20 14:28:44 +05:30
Kovid Goyal
e6c17e19d7 Turn on nitpicky in makefile rather than conf.py 2021-07-20 13:57:58 +05:30
Kovid Goyal
d98c2f89aa When redirecting preserve anchors 2021-07-20 13:51:50 +05:30
Kovid Goyal
624991b9b7 Use the builtin envvar role for env vars
Also fix some broken links
2021-07-20 13:29:39 +05:30
Kovid Goyal
c7ee776349 ... 2021-07-20 13:21:45 +05:30
Kovid Goyal
ffeacef394 Document the various env vars kitty uses/sets 2021-07-20 13:19:23 +05:30
Kovid Goyal
f4ebec6759 The graphics protocol spec should link to POSIX not the linux man page 2021-07-20 09:51:15 +05:30
Kovid Goyal
93e3e4d2b1 Also strip \r from marked text 2021-07-19 18:12:29 +05:30
Kovid Goyal
3633049ba5 Forgot to include \r in the url regex 2021-07-19 18:09:00 +05:30
Kovid Goyal
c566ed4643 hints kitten: Detect paths and hashes that appear over multiple lines
Fixes #3845
2021-07-19 17:35:48 +05:30
Kovid Goyal
af956f4d84 Fix debug print for long strings 2021-07-19 16:56:10 +05:30
Kovid Goyal
b70c72fc3b ... 2021-07-19 13:45:20 +05:30
Kovid Goyal
1f35694705 Render ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ with spaces at the edges
Matches rendering in most other programs and allows long chains of them to look better

Fixes #3844
2021-07-19 13:42:59 +05:30
Kovid Goyal
d912d96f00 More docs cleanups 2021-07-19 09:08:55 +05:30
Kovid Goyal
94f8fb4a4b Cleanup up some doc formatting 2021-07-19 08:45:56 +05:30
Kovid Goyal
103744e2ca Note the changed docs build requirements 2021-07-19 08:32:39 +05:30
Kovid Goyal
fe18a5de92 Use a shorter title 2021-07-18 22:19:47 +05:30
Kovid Goyal
9b0394860d typo 2021-07-18 19:56:06 +05:30
Kovid Goyal
380c7628d8 Use tabs for C/Python code samples 2021-07-18 13:43:26 +05:30
Kovid Goyal
f787a377c3 A new theme for the kitty website
Supports dark mode. Also re-organize the documentation
a bit, making it more hierarchical.

Have a nicer landing page
2021-07-18 13:29:33 +05:30
Kovid Goyal
7c1b819728 Use nicer URLs without .html suffix on website
Also easier insertion of analytics tag for the website without
needing a custom template.

The old .html URLs are redirected via meta http-equiv refresh, which is
all gh-pages supports
2021-07-17 21:25:29 +05:30
Kovid Goyal
8e5175e56b Revert "icat: Use scandir for slightly better performance"
This reverts commit 2e893690bd.
scandir is not recursive
2021-07-17 09:51:06 +05:30
Kovid Goyal
9e9d1a4e96 Add a glossary to define some commonly used terms in kitty 2021-07-17 06:36:56 +05:30
Kovid Goyal
fd475423cf Fix reference to option in changelog docs 2021-07-17 06:30:48 +05:30
Kovid Goyal
070911d458 Wayland: Fix initial_window_size in cells on scale != 1 screens
Fixes #3834
2021-07-17 06:04:56 +05:30
Kovid Goyal
3b585e6dbb Fix #3840 2021-07-17 05:46:08 +05:30
Kovid Goyal
2e893690bd icat: Use scandir for slightly better performance 2021-07-16 21:55:15 +05:30
Kovid Goyal
d052b020fa Check for dirs when getting mimetypes in a couple more places 2021-07-16 21:49:02 +05:30
Kovid Goyal
ac6224563b Cleanup previous PR 2021-07-16 21:43:56 +05:30
Kovid Goyal
a9630890fd Merge branch 'folder-mime' of https://github.com/william-gooch/kitty 2021-07-16 21:40:14 +05:30
Kovid Goyal
4b889750db Add a new variable `{num_window_groups}` for tab_title_template
See #3837
2021-07-16 19:25:24 +05:30
William Gooch
308bd0d81d Directories should have mime-type inode/directory. 2021-07-16 13:40:00 +01:00
Kovid Goyal
d55a86e39b Cleanup icdir creation 2021-07-13 08:00:15 +05:30
Kovid Goyal
0c193c3ab7 Merge branch 'add-icons' of https://github.com/Artturin/kitty 2021-07-13 07:57:27 +05:30
Artturin
6f513f5706 linux: install a scalable icon 2021-07-13 05:10:15 +03:00
Kovid Goyal
368bc91eed macOS: Render colors in the sRGB colorspace to match other macOS terminal applications
Fixes #2249
2021-07-12 17:34:03 +05:30
Kovid Goyal
3a322c5c6e Fix warning from sphinx 2021-07-12 13:22:39 +05:30
Kovid Goyal
c5ee044343 Merge branch 'patch-1' of https://github.com/con-f-use/kitty 2021-07-12 13:21:08 +05:30
con-f-use
19b918e56f mention kitten_alias in hits documentation
No idea if I correctly referenced this url: https://sw.kovidgoyal.net/kitty/conf.html#opt-kitty.kitten_alias
2021-07-12 07:48:34 +02:00
Kovid Goyal
cf5ed54c84 Dont add formatting escape codes to completion descriptions in ZSH
ZSH gets confused by them, causes the text to move up a line when
completing after the first line
2021-07-11 21:46:17 +05:30
Kovid Goyal
b813e1f7ab ... 2021-07-11 21:39:54 +05:30
Kovid Goyal
cdd8e52116 DRYer 2021-07-11 21:39:08 +05:30
Kovid Goyal
6945eb4186 Better complete debug function 2021-07-11 21:33:19 +05:30
Kovid Goyal
1d9626d493 Graphics protocol: Fix image without placements being deleted when screen scrolls 2021-07-10 14:05:53 +05:30
Kovid Goyal
75b73f6821 Allow using neighboring window operations in the stack layout 2021-07-09 08:54:22 +05:30
Kovid Goyal
f62f94381e also forgot to list the a=a key 2021-07-08 09:17:42 +05:30
Kovid Goyal
cd6b3da665 Fix turning off cursor blink via escape codes not working
Also fix cursor blink stopping after terminal reset. The default cursor
state should be blinking.

Fixes #3808

...
2021-07-07 20:45:46 +05:30
Kovid Goyal
25fb5d0ee6 Forgot to list the f key for a 2021-07-07 18:26:06 +05:30
Kovid Goyal
65b2ca8f57 Fix a typo that broke addition of default mouse mappings in gen-config
Also update options/types.py with new action name
2021-07-07 18:06:39 +05:30
Kovid Goyal
1ec07eb17a diff kitten: Remove limit on max line length of 4096 characters
Fixes #3806
2021-07-07 07:27:42 +05:30
Kovid Goyal
46fbf78da5 Fix #3804 2021-07-06 15:34:02 +05:30
Kovid Goyal
cea8d4a87d ... 2021-07-06 09:05:50 +05:30
Kovid Goyal
e07ba2c53d Dont move back glyph on overflow in infinite ligatures 2021-07-05 14:47:01 +05:30
Kovid Goyal
0af3f102aa ... 2021-07-05 14:38:07 +05:30
Kovid Goyal
a5b293401d Add an action to restore move-end behavior when extending selections 2021-07-04 19:02:33 +05:30
Kovid Goyal
05d0bda044 Allow selecting blanks at the start of the top line 2021-07-04 18:49:17 +05:30
Kovid Goyal
3dee3aba59 Fix #3794 2021-07-04 18:05:54 +05:30
Kovid Goyal
e732df46b8 Have right clicking to extend selection operate on the nearest selection boundary instead of the selection end. This matches both vim and xterm 2021-07-04 18:00:41 +05:30
Kovid Goyal
86a8b231f4 ... 2021-07-04 07:15:15 +05:30
Kovid Goyal
10d359c222 Better error message for application escape mode
tmux apparently uses it
2021-07-03 12:24:51 +05:30
Kovid Goyal
1ef895e246 When dumping commands dump stop_pending_mode at the correct place 2021-07-03 12:07:46 +05:30
Kovid Goyal
38ae370202 Fix #3789 2021-07-03 10:12:44 +05:30
Kovid Goyal
610a09817f Fix incorrect Sync terminfo entry 2021-07-03 09:18:33 +05:30
Kovid Goyal
c6938c9039 Add some missed actions 2021-07-02 21:43:18 +05:30
Kovid Goyal
7a8fb8f430 Merge branch 'dankamongmen/the-vs-then' of https://github.com/dankamongmen/kitty 2021-07-01 20:17:03 +05:30
nick black
3495591c5f [trivial] s/the/then/ 2021-07-01 10:34:43 -04:00
Kovid Goyal
050c31094b toggle_layout action to zoom/unzoom active window 2021-07-01 17:57:00 +05:30
Kovid Goyal
6a4668974b Forgot to mark layout actions 2021-07-01 17:38:26 +05:30
Kovid Goyal
026d200add Fix a bug in the implementation of the synchronized updates escape code that could cause incorrect parsing if either the pending buffer capacity or the pending timeout were exceeded
Fixes #3779
2021-07-01 15:32:53 +05:30
Kovid Goyal
fe991ee767 DRYer 2021-07-01 08:53:11 +05:30
Kovid Goyal
b2a219f9d8 Add the Sync non-standard capability for synchronized updates to terminfo
Since the geniuses at terminal-wg are trying their best to create chaos
by retroactively changing the escape code used for this feature, it is
good to have a property for it in terminfo. Since tmux already uses Sync
for it, follow that in kitty's terminfo.
2021-07-01 08:48:59 +05:30
Kovid Goyal
64810e0e0b Add some missing blank lines before code blocks 2021-07-01 07:22:49 +05:30
Kovid Goyal
6e5ed38b76 Add syntax highlighting for mouse_map 2021-06-30 15:56:03 +05:30
Kovid Goyal
8d308ef2b8 Add a ref to vim-kitty for syntax highlighting kitty.conf 2021-06-30 15:50:43 +05:30
Kovid Goyal
ab76ae3778 Dont set the filetype in the default config file modeline
This enables people using custom syntax highlighting such as
https://github.com/fladson/vim-kitty
2021-06-30 15:36:33 +05:30
Kovid Goyal
222055fcff Add link to detailed cp buffers docs 2021-06-30 15:15:41 +05:30
Kovid Goyal
247d700c30 Fix docs build failure 2021-06-30 15:12:46 +05:30
Kovid Goyal
cf41d56c00 Clean docstrings when generating actions docs 2021-06-30 15:06:12 +05:30
Kovid Goyal
a8f7b1eb92 Disable text justification in website
Looks really bad in many places as there are quite a few non-breakbale
phrases.
2021-06-30 15:03:06 +05:30
Kovid Goyal
90d3ce4162 make target to publish website 2021-06-30 15:01:25 +05:30
Kovid Goyal
bc66b7f16e Fix a bunch of broken links 2021-06-30 14:59:54 +05:30
Kovid Goyal
606708a96e Cross reference builtin shortcuts from actions 2021-06-30 14:52:47 +05:30
Kovid Goyal
2ec0d94c31 Document all mappable actions 2021-06-30 14:33:28 +05:30
Kovid Goyal
e6a17f78b6 Use the main VT parser in pending mode as well
Should get much closer semantics in the two cases and its nice not to
have an extra mini VT parser for pending mode. There is a performance
hit in pending mode, since now the pending mode bytes are round tripped
via utf-8 decoding/encoding, but its worth it for the code
simplification.
2021-06-30 10:52:22 +05:30
Kovid Goyal
d6b6d3f59f Make dispatch_unicode_char re-useable 2021-06-30 08:29:40 +05:30
Kovid Goyal
5932ddb0fe DRYer 2021-06-30 07:57:21 +05:30
Kovid Goyal
d1e5c2f86f ... 2021-06-29 22:31:23 +05:30
Kovid Goyal
1f2f25f7a3 Mark the mouse actions 2021-06-29 22:27:31 +05:30
Kovid Goyal
b0edbf2857 Mark more actions 2021-06-29 22:21:01 +05:30
Kovid Goyal
91f0da9dcd Document actions in the tab object 2021-06-29 20:12:39 +05:30
Kovid Goyal
3d5d60bc5b ... 2021-06-29 16:37:29 +05:30
Kovid Goyal
5c5599592a abort CSI parsing on NUL or DEL 2021-06-29 12:37:34 +05:30
Kovid Goyal
c60d09f3b2 Mark combine as an action 2021-06-29 12:28:44 +05:30
Kovid Goyal
5768c54c5b Add support for pending mode via SM/RM 2026
Because, why the hell not, it's not like I have an actual life.
More seriously, terminal-wg (aka Bikeshedder's Anonymous) is
pushing for it so it's likely at least one poor application writer
will fall for their propaganda.
2021-06-29 12:24:34 +05:30
Kovid Goyal
6d413e2492 Start documenting mappable actions 2021-06-28 21:44:52 +05:30
Kovid Goyal
331675d413 Fix ResourceWarning 2021-06-28 20:40:10 +05:30
Kovid Goyal
2105940286 Better error message for +launch 2021-06-28 19:38:51 +05:30
Kovid Goyal
90164dfee7 make clean should not clean bypy build artifacts 2021-06-28 06:39:12 +05:30
Kovid Goyal
73f641cb66 version 0.21.2 2021-06-28 06:22:35 +05:30
Kovid Goyal
3d51835b9b Avoid unneccessary mallocs and copying when return code points for word 2021-06-28 05:56:49 +05:30
Kovid Goyal
f358d76409 Fix type sig 2021-06-28 05:51:49 +05:30
Kovid Goyal
ce486e9244 Move the if condition out of the inner loops 2021-06-27 21:09:06 +05:30
Kovid Goyal
691b7215a0 Unicode input kitten: Fix searching when a word has more than 1024 matches
Fixes #3773
2021-06-27 21:04:43 +05:30
Kovid Goyal
5be45d0ff2 Turn on all warnings when running test suite 2021-06-26 12:55:53 +05:30
Kovid Goyal
8a4b326127 Finish completion for ssh kitten
Fixes #3760
2021-06-26 12:28:12 +05:30
Kovid Goyal
051374cd55 Add support for comma separated completions 2021-06-26 10:52:14 +05:30
Kovid Goyal
71cd92da29 Store match group properties on the match group object 2021-06-26 09:47:21 +05:30
Kovid Goyal
c2d3a0c8b4 Completion for choice args 2021-06-26 09:18:36 +05:30
Kovid Goyal
fe8b151666 Complete option 2021-06-25 22:53:55 +05:30
Kovid Goyal
9e2d67f7a1 Show option descriptions when completing in ZSH 2021-06-25 19:13:16 +05:30
Kovid Goyal
23ea3745ca Make zsh completion headings bold 2021-06-25 18:05:18 +05:30
Kovid Goyal
d8d5a8fada More work on completion for the SSH kitten 2021-06-25 17:50:08 +05:30
Kovid Goyal
21ce0e90bf Code to get list of known host names 2021-06-25 15:04:17 +05:30
Kovid Goyal
ec420b8012 Start work on completion for ssh kitten 2021-06-25 15:04:17 +05:30
Kovid Goyal
bd67899943 Allow using super and sub scripts in tab titles
The syntax is

{sup.whatever}

works by translating enhlish letters/number to their unicode
equivalents.

Fixes #3763
2021-06-25 15:02:43 +05:30
Kovid Goyal
4b7600f3a5 Nicer error message on unknown entry point 2021-06-25 10:25:54 +05:30
Kovid Goyal
5eabd69659 ... 2021-06-25 08:03:20 +05:30
Kovid Goyal
e83be21756 Add a note about completions for the SSH kitten 2021-06-25 08:02:28 +05:30
Kovid Goyal
13c58536be Cleanup previous PR and add changelog entry 2021-06-24 21:27:15 +05:30
Kovid Goyal
512dccdbfa Merge branch 'ripgrep-context' of https://github.com/allemangD/kitty 2021-06-24 21:25:11 +05:30
David Allemang
bb3a8453e0 Make hyperlinked_grep kitten respect context
Fix regex so that context lines (from -C option) are still hyperlinked.

Also add a case so that any non-matching lines are still output raw.
2021-06-24 11:04:35 -04:00
Kovid Goyal
e337fcaadc query terminal kitten: Allow querying font face and size information
Fixes #3756
2021-06-24 13:31:50 +05:30
Kovid Goyal
890a149a5d Move generation of query responses into the query classes 2021-06-24 12:31:17 +05:30
Kovid Goyal
5b3ac259ce Fix a resource warning 2021-06-24 11:27:02 +05:30
Kovid Goyal
ce50043048 Add an issue reference to the changelog 2021-06-23 14:16:41 +05:30
Kovid Goyal
ebfbf6082f ... 2021-06-21 21:23:29 +05:30
Kovid Goyal
b44bec2207 Move processing of coca_pending_actions() into its own function
Makes process_global_state less crowded and easier to grok
2021-06-21 21:03:41 +05:30
Kovid Goyal
576ce21fc8 macOS: Fix shortcuts in the global menu bar responding slowly when cursor blink is disabled/timed out
The event loop needed to be forced to tick over immediately otherwise
the changes were not being rendered till some other event such as mouse
motion or key release was not delivered.

Fixes #3693
2021-06-21 20:58:44 +05:30
Kovid Goyal
2ba015d0be Add an issue reference to the changelog
Fixes #3405
2021-06-21 16:46:49 +05:30
Kovid Goyal
98ae2ac96a ssh kitten: Use sh rather than /bin/sh
It's not actually required that sh be in /bin.  The hope is that fewer
users alias sh to non POSIX things than put sh in places other than /bin
2021-06-21 16:43:59 +05:30
Kovid Goyal
1c25ed7666 ssh kitten: Fix "Connection closed" message being printed by ssh when running remote commands
Don't force allocate a tty when running remote commands. This
matches ssh behavior as well.
2021-06-21 16:40:07 +05:30
Kovid Goyal
fd4c7a4ed2 ssh kitten: Support system where the login shell is a non-POSIX shell
Now the kitten passes its script to /bin/sh and detects the login shell
using various strategies based on the value of $USER on the remote
machine. The strategies are tried one after another till one succeeds:

1) getent passwd $USER
2) id -P
3) python pwd module
4) parsing /etc/passwd

The hope is that these strategies will fail on fewer systems than
relying on the login shell being POSIX compliant.
2021-06-21 16:30:49 +05:30
Kovid Goyal
32d275c138 Document how to use the new config framework with external kittens 2021-06-21 05:31:17 +05:30
Kovid Goyal
f8924286ce gen-config for third party kittens 2021-06-21 05:11:46 +05:30
Kovid Goyal
6e77345263 Ensure sys.path is preserved even if there are errors importing a custom kitten 2021-06-21 04:35:10 +05:30
Kovid Goyal
1438c64b9e Move the config generation code into kitty proper 2021-06-21 04:25:04 +05:30
Kovid Goyal
2ff1256aef mouse_discard_event -> discard_event 2021-06-21 04:01:45 +05:30
Kovid Goyal
5d169854c4 Merge branch 'typo' of https://github.com/Luflosi/kitty 2021-06-18 20:21:08 +05:30
Luflosi
e61d328cb0 Fix typo in changelog 2021-06-18 16:36:27 +02:00
Kovid Goyal
0c196888fb Clarify meaning of grabbed/ungrabbed a bit more 2021-06-18 17:56:21 +05:30
Kovid Goyal
85efed8308 Fix #3743 2021-06-18 17:54:13 +05:30
Kovid Goyal
857c88a951 Add a note to the keyboard protocol elucidating the use of separate main and alternate screen mode stacks in more detail 2021-06-18 09:58:19 +05:30
Kovid Goyal
74b0a7f6f8 Make it clearer that there are separate keyboard mode stacks for main and alternate screens 2021-06-18 09:41:35 +05:30
Kovid Goyal
5da5d00aec text typos 2021-06-18 08:20:32 +05:30
Kovid Goyal
eb59fae9b0 ... 2021-06-18 08:20:04 +05:30
Kovid Goyal
b6b38d6f44 Linux: Fix emoji/bitmapped fonts not useable in symbol_map 2021-06-18 08:01:23 +05:30
Kovid Goyal
4f4d9e0ae3 ... 2021-06-17 21:34:26 +05:30
Kovid Goyal
43c1776594 Handle systems that use less -F as pagers
Fix #3740
2021-06-17 21:33:26 +05:30
Kovid Goyal
397638998b Dont use static memory for the list of chars options
Saves a couple of KB of RAM and is more flexible in terms
of max number of allowed chars, although for large numbers one really
needs a hash for fast lookups.
2021-06-17 13:27:11 +05:30
Kovid Goyal
6ddbda00df Clean up url excluded chars PR 2021-06-17 13:11:23 +05:30
Kovid Goyal
df0bf74bfe Merge branch 'url_excluded_characters' of https://github.com/rbutoi/kitty 2021-06-17 13:01:31 +05:30
Radu Butoi
5ee0651f56 Add url_excluded_characters option to exclude characters from URLs.
This option, like select_by_word_characters, is a set of characters, but
for which to *exclude* from URL parsing. See
https://github.com/kovidgoyal/kitty/issues/3688#issuecomment-862711148.
2021-06-17 01:55:21 -04:00
Kovid Goyal
9ec1c28b35 Merge branch 'cleanup-adjust-baseline' of https://github.com/ytang/kitty 2021-06-16 21:24:59 +05:30
Yang Tang
bfdbf06731 Remove redundant code 2021-06-16 11:44:27 -04:00
Kovid Goyal
ca58b30c47 Fix compiler warning 2021-06-16 20:51:47 +05:30
Kovid Goyal
0fb2f383ac Clean up the baseline adjustment PR 2021-06-16 20:39:00 +05:30
Kovid Goyal
5d0eb1d330 Merge branch 'adjust-baseline' of https://github.com/ytang/kitty 2021-06-16 20:04:15 +05:30
Kovid Goyal
ee77144e2b Make the sample script a little nicer 2021-06-16 18:51:21 +05:30
Kovid Goyal
9d3a2cc219 Fix space based ligatures not rendering correctly
The new infinite ligature cache needed to be keyed by total number of
cells as well as total number of glyphs, otherwise a space based
ligature which is the same glyph rendered in different numbers of cells
wold render incorrectly when present in multiple forms. Fixes #3729
2021-06-16 18:41:01 +05:30
Yang Tang
e964ac86d5 Allow specifying adjust_baseline as either pixels or percentage 2021-06-16 01:11:51 -04:00
Yang Tang
bb26b3d549 Add option adjust_baseline to adjust the baseline position on macOS 2021-06-15 14:52:43 -04:00
Kovid Goyal
71c8d82c33 Merge branch 'doc-harfbuzz' of https://github.com/The-Compiler/kitty 2021-06-15 21:52:39 +05:30
Florian Bruhin
9fffe0d710 doc: Link to harfbuzz font feature format 2021-06-15 17:36:12 +02:00
Kovid Goyal
51f8b22dfa macOS: Fix middle-click to paste from clipboard not working
Fixes #3730
2021-06-15 13:45:50 +05:30
Kovid Goyal
63a36a1054 Add Smulx to terminfo
A couple of other terminals use it for styled underlines, in
contravention of the spec. But, in the interests of wider
interoperability add it to kitty as well.

Fixes #3725
2021-06-14 11:58:52 +05:30
Kovid Goyal
057084a708 Add support for XTVERSION version reporting escape code 2021-06-14 10:20:50 +05:30
211 changed files with 7379 additions and 3030 deletions

View File

@@ -22,7 +22,7 @@ If applicable, add screenshots to help explain your problem.
**Environment details**
```
Press Ctrl+Shift+F6 (cmd+option+, on macOS) in kitty, to copy debug output about kitty and its
Press Ctrl+Shift+F6 (cmd+option+comma on macOS) in kitty, to copy debug output about kitty and its
configuration to the clipboard and paste it here.
On older versions of kitty, run kitty --debug-config instead

View File

@@ -34,7 +34,7 @@ def install_deps():
run('brew', 'install', *items)
else:
run('sudo apt-get update')
run('sudo apt-get install -y libgl1-mesa-dev libxi-dev libxrandr-dev libxinerama-dev'
run('sudo apt-get install -y libgl1-mesa-dev libxi-dev libxrandr-dev libxinerama-dev ca-certificates'
' libxcursor-dev libxcb-xkb-dev libdbus-1-dev libxkbcommon-dev libharfbuzz-dev libx11-xcb-dev'
' libpng-dev liblcms2-dev libfontconfig-dev libxkbcommon-x11-dev libcanberra-dev uuid-dev')
if is_bundle:

View File

@@ -76,7 +76,7 @@ jobs:
python-version: 3.8
- name: Install build-only deps
run: pip install flake8 mypy types-requests types-docutils sphinx
run: pip install -r docs/requirements.txt flake8 mypy types-requests types-docutils
- name: Run pyflakes
run: python -m flake8 --count .

View File

@@ -1 +1 @@
See https://sw.kovidgoyal.net/kitty/changelog.html
See https://sw.kovidgoyal.net/kitty/changelog/

View File

@@ -10,9 +10,9 @@ config to reproduce the issue with).
### Contributing code
Install [the dependencies](https://sw.kovidgoyal.net/kitty/build.html#dependencies)
Install [the dependencies](https://sw.kovidgoyal.net/kitty/build/#dependencies)
using your favorite package manager. Build and run kitty [from
source](https://sw.kovidgoyal.net/kitty/build.html#install-and-run-from-source).
source](https://sw.kovidgoyal.net/kitty/build/#install-and-run-from-source).
Make a fork, submit your Pull Request. If it's a large/controversial change, open an issue
beforehand to discuss it, so that you don't waste your time making a pull

View File

@@ -1,3 +1,3 @@
To build from source: <https://sw.kovidgoyal.net/kitty/build.html>
To build from source: <https://sw.kovidgoyal.net/kitty/build/>
Pre-built binaries: <https://sw.kovidgoyal.net/kitty/binary.html>
Pre-built binaries: <https://sw.kovidgoyal.net/kitty/binary/>

View File

@@ -40,4 +40,11 @@ html:
linkcheck:
$(MAKE) FAIL_WARN=$(FAIL_WARN) -C docs linkcheck
website:
./publish.py --only website
docs: man html
develop-docs:
$(MAKE) -C docs develop-docs

View File

@@ -4,7 +4,7 @@ See https://sw.kovidgoyal.net/kitty/[the kitty website].
image:https://github.com/kovidgoyal/kitty/workflows/CI/badge.svg["Build status", link="https://github.com/kovidgoyal/kitty/actions?query=workflow%3ACI"]
https://sw.kovidgoyal.net/kitty/faq.html[Frequently Asked Questions]
https://sw.kovidgoyal.net/kitty/faq/[Frequently Asked Questions]
To ask other questions about kitty usage, use either the https://github.com/kovidgoyal/kitty/discussions/[discussions on GitHub] or the
https://www.reddit.com/r/KittyTerminal[Reddit community]

View File

@@ -24,6 +24,8 @@ def remote_control(args: List[str]) -> None:
def runpy(args: List[str]) -> None:
if len(args) < 2:
raise SystemExit('Usage: kitty +runpy "some python code"')
sys.argv = ['kitty'] + args[2:]
exec(args[1])
@@ -49,13 +51,22 @@ def complete(args: List[str]) -> None:
def launch(args: List[str]) -> None:
import runpy
sys.argv = args[1:]
exe = args[1]
try:
exe = args[1]
except IndexError:
raise SystemExit(
'usage: kitty +launch script.py [arguments to be passed to script.py ...]\n\n'
'script.py will be run with full access to kitty code. If script.py is '
'prefixed with a : it will be searched for in PATH'
)
if exe.startswith(':'):
import shutil
q = shutil.which(exe[1:])
if not q:
raise SystemExit('{} not found in PATH'.format(args[1][1:]))
raise SystemExit(f'{exe[1:]} not found in PATH')
exe = q
if not os.path.exists(exe):
raise SystemExit(f'{exe} does not exist')
runpy.run_path(exe, run_name='__main__')
@@ -80,8 +91,14 @@ def edit_config_file(args: List[str]) -> None:
def namespaced(args: List[str]) -> None:
func = namespaced_entry_points[args[1]]
func(args[1:])
try:
func = namespaced_entry_points[args[1]]
except KeyError:
pass
else:
func(args[1:])
return
raise SystemExit(f'{args[1]} is not a known entry point. Choices are: ' + ', '.join(namespaced_entry_points))
entry_points = {
@@ -102,21 +119,21 @@ namespaced_entry_points['complete'] = complete
def setup_openssl_environment() -> None:
# Workaround for Linux distros that have still failed to get their heads
# out of their asses and implement a common location for SSL certificates.
# It's not that hard people, there exists a wonderful tool called the symlink
# See https://www.mobileread.com/forums/showthread.php?t=256095
if 'SSL_CERT_FILE' not in os.environ and 'SSL_CERT_DIR' not in os.environ:
if os.access('/etc/pki/tls/certs/ca-bundle.crt', os.R_OK):
os.environ['SSL_CERT_FILE'] = '/etc/pki/tls/certs/ca-bundle.crt'
setattr(sys, 'kitty_ssl_env_var', 'SSL_CERT_FILE')
elif os.path.isdir('/etc/ssl/certs'):
os.environ['SSL_CERT_DIR'] = '/etc/ssl/certs'
setattr(sys, 'kitty_ssl_env_var', 'SSL_CERT_DIR')
# Use our bundled CA certificates instead of the system ones, since
# many systems come with no certificates in a useable form or have various
# locations for the certificates.
d = os.path.dirname
ext_dir: str = getattr(sys, 'kitty_extensions_dir')
if 'darwin' in sys.platform.lower():
cert_file = os.path.join(d(d(d(ext_dir))), 'cacert.pem')
else:
cert_file = os.path.join(d(ext_dir), 'cacert.pem')
os.environ['SSL_CERT_FILE'] = cert_file
setattr(sys, 'kitty_ssl_env_var', 'SSL_CERT_FILE')
def main() -> None:
if getattr(sys, 'frozen', False) and 'darwin' not in sys.platform.lower():
if getattr(sys, 'frozen', False) and getattr(sys, 'kitty_extensions_dir', ''):
setup_openssl_environment()
first_arg = '' if len(sys.argv) < 2 else sys.argv[1]
func = entry_points.get(first_arg)

View File

@@ -30,6 +30,7 @@ def initialize_constants():
kitty_constants['appname'] = re.search(
r'appname: str\s+=\s+(u{0,1})[\'"]([^\'"]+)[\'"]', src
).group(2)
kitty_constants['cacerts_url'] = 'https://curl.haxx.se/ca/cacert.pem'
return kitty_constants

View File

@@ -88,6 +88,17 @@ def copy_libs(env):
for x in binary_includes():
dest = env.bin_dir if '/bin/' in x else env.lib_dir
shutil.copy2(x, dest)
dest = os.path.join(dest, os.path.basename(x))
subprocess.check_call(['chrpath', '-d', dest])
def add_ca_certs(env):
print('Downloading CA certs...')
from urllib.request import urlopen
cdata = urlopen(kitty_constants['cacerts_url']).read()
dest = os.path.join(env.lib_dir, 'cacert.pem')
with open(dest, 'wb') as f:
f.write(cdata)
def copy_python(env):
@@ -218,6 +229,7 @@ def main():
build_launcher(env)
files = find_binaries(env)
fix_permissions(files)
add_ca_certs(env)
if not args.dont_strip:
strip_binaries(files)
if not args.skip_tests:

View File

@@ -170,6 +170,7 @@ class Freeze(object):
self.add_stdlib()
self.add_misc_libraries()
self.freeze_python()
self.add_ca_certs()
if not self.dont_strip:
self.strip_files()
if not self.skip_tests:
@@ -180,6 +181,15 @@ class Freeze(object):
return ret
@flush
def add_ca_certs(self):
print('\nDownloading CA certs...')
from urllib.request import urlopen
cdata = urlopen(kitty_constants['cacerts_url']).read()
dest = os.path.join(self.contents_dir, 'Resources', 'cacert.pem')
with open(dest, 'wb') as f:
f.write(cdata)
@flush
def strip_files(self):
print('\nStripping files...')

View File

@@ -2,7 +2,7 @@
#
# You can set these variables from the command line.
SPHINXOPTS = -j auto -T $(FAIL_WARN)
SPHINXOPTS = -n -q -j auto -T $(FAIL_WARN) $(OPTS)
SPHINXBUILD = sphinx-build
SPHINXPROJ = kitty
SOURCEDIR = .
@@ -18,3 +18,7 @@ help:
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
develop-docs:
sphinx-autobuild --ignore "$(abspath $(SOURCEDIR))/generated/*" --watch ../kitty --watch ../kittens -b dirhtml "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS)

View File

@@ -5,122 +5,15 @@
* Distributed under terms of the MIT license.
*/
.float-left-img {
float: left;
margin-right: 1em;
margin-bottom: 1em;
}
.float-right-img { float: right; margin-left: 1em; margin-bottom: 1em }
.half-with-img { max-width: 50% }
.fit-img { max-width: 95% }
div.body p, div.body dd, div.body li, div.body blockquote {
text-align: justify;
}
div.body {
min-width: 200px;
}
pre {
white-space: pre-wrap;
}
pre.pre {
white-space: pre;
}
a[href], input[type="submit"] { cursor: pointer; }
img[style] {
/* Used for :scale: images to have them render properly but still popup when clicked */
width: auto !important;
height: auto !important;
}
a {
text-decoration: none !important;
border-bottom: none !important;
}
body div.document {
margin-top: 1ex;
.sidebar-logo {
max-height: 128px;
}
.major-features li {
margin-top: 0.75ex;
margin-bottom: 0.75ex;
}
.support-form input[type=submit] {
border-radius: 6px;
box-shadow: rgb(255, 246, 175) 0px 1px 0px 0px;
background: linear-gradient(rgb(255, 236, 100) 5%, rgb(255, 171, 35) 100%) rgb(255, 236, 100);
border: 1px solid rgb(255, 170, 34);
display: inline-block;
color: rgb(51, 51, 51);
font-family: Arial;
font-size: 15px;
font-weight: bold;
padding: 6px 24px;
text-decoration: none;
text-shadow: rgb(255, 238, 102) 0px 1px 0px;
}
.support-form input[type=submit]:hover {
background: linear-gradient(rgb(255, 171, 35) 5%, rgb(255, 236, 100) 100%) rgb(255, 171, 35);
}
.support-form input[type=submit]:focus {
outline: 0;
}
div.sphinxsidebar {
font-size: inherit;
line-height: inherit;
max-height: 100%;
overflow-y: auto;
}
#sidebartoc li {
margin-top: 0.75ex;
margin-bottom: 0.75ex;
}
#sidebartoc ul {
list-style: none !important;
}
#sidebartoc a[href]:hover {
color: red;
}
.green {
color: green;
}
.cyan {
color: blue;
}
.env {
.sidebar-tree a.current {
font-style: italic;
}
.italic {
font-style: italic;
}
.bold {
font-weight: bold;
}
.title {
font-size: larger;
font-weight: bold
}

57
docs/_static/custom.js vendored Normal file
View File

@@ -0,0 +1,57 @@
/* vim:fileencoding=utf-8
*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPLv3 license
*/
(function() {
"use strict";
function get_sidebar_tree() {
return document.querySelector('.sidebar-tree');
}
function scroll_sidebar_node_into_view(a) {
var ss = get_sidebar_tree().closest('.sidebar-scroll');
if (!ss || !a) return;
ss.style.position = 'relative';
var pos = 0;
while (true) {
pos += a.offsetTop;
a = a.offsetParent;
if (!a || a == ss) break;
}
ss.scrollTop = pos;
}
function mark_current_link(sidebar_tree, a, onload) {
var li = a.closest('li.has-children');
while (li) {
li.querySelector('input[type=checkbox]').setAttribute('checked', 'checked');
li = li.parentNode.closest('li.has-children');
}
sidebar_tree.querySelectorAll('.current').forEach(function (elem) {
elem.classList.remove('current');
});
if (onload) scroll_sidebar_node_into_view(a);
a.classList.add('current');
}
function show_hash_in_sidebar(onload) {
var sidebar_tree = document.querySelector('.sidebar-tree');
if (document.location.hash.length > 1) {
var a = sidebar_tree.querySelector('a[href="' + document.location.hash + '"]');
if (a) mark_current_link(sidebar_tree, a, onload);
} else {
if (onload) scroll_sidebar_node_into_view(sidebar_tree.querySelector('.current-page a'));
}
}
document.addEventListener("DOMContentLoaded", function() {
show_hash_in_sidebar(true);
window.addEventListener('hashchange', show_hash_in_sidebar.bind(null, false));
});
}());

22
docs/_templates/base.html vendored Normal file
View File

@@ -0,0 +1,22 @@
{% extends "!base.html" %}
{% block extrahead %}
{{ super() }}
{%- if analytics_id %}
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{{ analytics_id }}']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
{% endif -%}
{% endblock %}

View File

@@ -1,6 +0,0 @@
{% extends "!layout.html" %}
{%- block extrahead %}
<!-- kitty analytics placeholder -->
{{ super() }}
{% endblock %}

View File

@@ -1,6 +0,0 @@
{%- if display_toc %}
<div>&nbsp;</div>
<div id="sidebartoc">
{{ toc }}
</div>
{%- endif %}

View File

@@ -1,22 +0,0 @@
{#
basic/searchbox.html
~~~~~~~~~~~~~~~~~~~~
Sphinx sidebar template: quick search box.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
#}
{%- if pagename != "search" and builder != "singlehtml" %}
<div id="searchbox" style="display: none" role="search">
<div class="searchformwrapper">
<form class="search" action="{{ pathto('search') }}" method="get">
<input type="text" name="q" placeholder="{{ _('Search') }}" />
<input type="submit" value="{{ _('Go') }}" style="cursor: pointer" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
{%- endif %}

View File

@@ -1,7 +0,0 @@
{% if pagename != "support" %}
<div id="support" style="text-align: center">
<form class="support-form" action="{{ pathto('support') }}" title="{{ _('Donate to support kitty development') }}">
<input type="submit" value="{{ _('Support kitty') }}">
</form>
</div>
{% endif %}

9
docs/actions.rst Normal file
View File

@@ -0,0 +1,9 @@
Mappable actions
-----------------------
.. highlight:: conf
The actions described below can be mapped to any key press or mouse action
using the ``map`` and ``mouse_map`` directives in :file:`kitty.conf`.
.. include:: /generated/actions.rst

View File

@@ -83,6 +83,10 @@ move it to another tab or another OS window::
map ctrl+f2 detach_window
# moves the window into a new Tab
map ctrl+f3 detach_window new-tab
# moves the window into the previously active tab
map ctrl+f3 detach_window tab-prev
# moves the window into the tab at the left of the active tab
map ctrl+f3 detach_window tab-left
# asks which tab to move the window into
map ctrl+f4 detach_window ask
@@ -102,6 +106,9 @@ the currently active window::
Other keyboard shortcuts
----------------------------------
The full list of actions that can be mapped to key presses is available
:doc:`here </actions>`.
================================== =======================
Action Shortcut
================================== =======================

View File

@@ -1,6 +1,9 @@
kitty - Binary install
Install kitty
========================
Binary install
----------------
.. |ins| replace:: curl -L :literal:`https://sw.kovidgoyal.net/kitty/installer.sh` | sh /dev/stdin
.. highlight:: sh

View File

@@ -1,5 +1,5 @@
Building kitty from source
==============================
Build from source
==================
.. image:: https://github.com/kovidgoyal/kitty/workflows/CI/badge.svg
:alt: Build status
@@ -25,24 +25,27 @@ Dependencies
Run-time dependencies:
* python >= 3.6
* harfbuzz >= 2.2.0
* zlib
* libpng
* liblcms2
* freetype (not needed on macOS)
* fontconfig (not needed on macOS)
* libcanberra (not needed on macOS)
* ImageMagick (optional, needed to use the ``kitty +kitten icat`` tool to display images in the terminal)
* pygments (optional, need for syntax highlighting in ``kitty +kitten diff``)
* ``python`` >= 3.6
* ``harfbuzz`` >= 2.2.0
* ``zlib``
* ``libpng``
* ``liblcms2``
* ``freetype`` (not needed on macOS)
* ``fontconfig`` (not needed on macOS)
* ``libcanberra`` (not needed on macOS)
* ``ImageMagick`` (optional, needed to use the ``kitty +kitten icat`` tool to display images in the terminal)
* ``pygments`` (optional, needed for syntax highlighting in ``kitty +kitten diff``)
Build-time dependencies:
* gcc or clang
* pkg-config
* For building on Linux in addition to the above dependencies you might also need to install the ``-dev`` packages for:
``libdbus-1-dev``, ``libxcursor-dev``, ``libxrandr-dev``, ``libxi-dev``, ``libxinerama-dev``, ``libgl1-mesa-dev``, ``libxkbcommon-x11-dev``, ``libfontconfig-dev``, ``libx11-xcb-dev``, ``liblcms2-dev``, and ``libpython3-dev``,
if they are not already installed by your distro.
* ``gcc`` or ``clang``
* ``pkg-config``
* For building on Linux in addition to the above dependencies you might also need to install the ``-dev`` packages for:
``libdbus-1-dev``, ``libxcursor-dev``, ``libxrandr-dev``, ``libxi-dev``, ``libxinerama-dev``,
``libgl1-mesa-dev``, ``libxkbcommon-x11-dev``, ``libfontconfig-dev``, ``libx11-xcb-dev``,
``liblcms2-dev``, and ``libpython3-dev``, if they are not already installed by your distro.
Install and run from source
------------------------------
@@ -78,8 +81,8 @@ you might have to rebuild the app.
.. note::
The released :file:`kitty.dmg` includes all dependencies, unlike the
:file:`kitty.app` built above and is built automatically by using the
<https://github.com/kovidgoyal/bypy>`_ however, that is designed to
run on Linux and is not for the faint of heart.
`bypy framework <https://github.com/kovidgoyal/bypy>`_ however, that is
designed to run on Linux and is not for the faint of heart.
.. note::
@@ -128,18 +131,19 @@ This allows users to install the terminfo file on servers into which they ssh,
without needing to install all of |kitty|.
.. note::
You need a couple of extra dependencies to build linux-package.
:file:`tic` to compile terminfo files, usually found in the
development package of :file:`ncurses`. Also, if you are building from
a git checkout instead of the released source code tarball, you will
need :file:`sphinx-build` from the `Sphinx documentation generator
<https://www.sphinx-doc.org/>`_.
You need a couple of extra dependencies to build linux-package.
:file:`tic` to compile terminfo files, usually found in the
development package of :file:`ncurses`. Also, if you are building from
a git checkout instead of the released source code tarball, you will
need to install the dependencies from ``docs/requirements.txt`` to
build the kitty documentation. They can be installed most easily with
``python -m pip -r docs/requirements.txt``.
This applies to creating packages for |kitty| for macOS package managers such as
brew or MacPorts as well.
.. note::
|kitty| has its own update check mechanism, if you would like to turn
it off for your package, use
``python3 setup.py linux-package --update-check-interval=0``
|kitty| has its own update check mechanism, if you would like to turn
it off for your package, use
``python3 setup.py linux-package --update-check-interval=0``

View File

@@ -4,6 +4,217 @@ Changelog
|kitty| is a feature-rich, cross-platform, *fast*, GPU based terminal.
To update |kitty|, :doc:`follow the instructions <binary>`.
0.23.1 [2021-08-17]
----------------------
- macOS: Fix themes kitten failing to download themes because of missing SSL
root certificates (:iss:`3936`)
- A new option :opt:`clipboard_max_size` to control the maximum size
of data that kitty will transmit to the system clipboard on behalf of
programs running inside it (:iss:`3937`)
- When matching windows/tabs in kittens or using remote control, allow matching
by recency. ``recent:0`` matches the active window/tab, ``recent:1`` matches
the previous window/tab and so on
- themes kitten: Fix only the first custom theme file being loaded correctly
(:iss:`3938`)
0.23.0 [2021-08-16]
----------------------
- A new :doc:`themes kitten </kittens/themes>` to easily change kitty themes.
Choose from almost two hundred themes in the `kitty themes repository
<https://github.com/kovidgoyal/kitty-themes>`_
- A new style for the tab bar that makes tabs looks like the tabs in a physical
tabbed file, see :opt:`tab_bar_style`
- Make the visual bell flash more gentle, especially on dark themes
(:pull:`2937`)
- Fix :option:`kitty --title` not overriding the OS Window title when multiple
tabs are present. Also this option is no longer used as the default title for
windows, allowing individual tabs/windows to have their own titles, even when
the OS Window has a fixed overall title (:iss:`3893`)
- Linux: Fix some very long ligatures being rendered incorrectly at some font
sizes (:iss:`3896`)
- Fix shift+middle click to paste sending a mouse press event but no release
event which breaks some applications that grab the mouse but cant handle
mouse events (:iss:`3902`)
- macOS: When the language is set to English and the country to one for which
an English locale does not exist, set :envvar:`LANG` to ``en_US.UTF-8``
(:iss:`3899`)
- terminfo: Fix "cnorm" the property for setting the cursor to normal using a
solid block rather than a blinking block cursor (:iss:`3906`)
- Add :opt:`clear_all_mouse_actions` to clear all mouse actions defined to
that point (:iss:`3907`)
- Fix the remote file kitten not working when using -- with ssh. The ssh kitten
was recently changed to do this (:iss:`3929`)
- When dragging word or line selections, ensure the initially selected item is
never deselected. This matches behavior in most other programs (:iss:`3930`)
- hints kitten: Make copy/paste with the :option:`kitty +kitten hints
--program` option work when using the ``self``
:option:`kitty +kitten hints --linenum-action` (:iss:`3931`)
0.22.2 [2021-08-02]
----------------------
- macOS: Fix a long standing bug that could cause kitty windows to stop
updating, that got worse in the previous release (:iss:`3890` and
:iss:`2016`)
- Wayland: A better fix for compositors like sway that can toggle client side
decorations on and off (:iss:`3888`)
0.22.1 [2021-07-31]
----------------------
- Fix a regression in the previous release that broke ``kitty --help`` (:iss:`3869`)
- Graphics protocol: Fix composing onto currently displayed frame not updating the frame on the GPU (:iss:`3874`)
- Fix switching to previously active tab after detaching a tab not working (:pull:`3871`)
- macOS: Fix an error on Apple silicon when enumerating monitors (:pull:`3875`)
- detach_window: Allow specifying the previously active tab or the tab to the left/right of
the active tab (:disc:`3877`)
- broadcast kitten: Fix a regression in ``0.20.0`` that broke sending of some
keys, such as backspace
- Linux binary: Remove any RPATH build artifacts from bundled libraries
- Wayland: If the compositor turns off server side decorations after turning
them on do not draw client side decorations (:iss:`3888`)
0.22.0 [2021-07-26]
----------------------
- Add a new :ref:`action-toggle_layout` action to easily zoom/unzoom a window
- When right clicking to extend a selection, move the nearest selection
boundary rather than the end of the selection. To restore previous behavior
use ``mouse_map right press ungrabbed mouse_selection move-end``.
- When opening hyperlinks, allow defining open actions for directories
(:pull:`3836`)
- When using the OSC 52 escape code to copy to clipboard allow large
copies (up to 8MB) without needing a kitty specific chunking protocol.
Note that if you used the chunking protocol in the past, it will no longer
work and you should switch to using the unmodified protocol which has the
advantage of working with all terminal emulators.
- Fix a bug in the implementation of the synchronized updates escape code that
could cause incorrect parsing if either the pending buffer capacity or the
pending timeout were exceeded (:iss:`3779`)
- A new remote control command to :program:`resize the OS Window <kitty @
resize-os-window>`
- Graphics protocol: Add support for composing rectangles from one animation
frame onto another (:iss:`3809`)
- diff kitten: Remove limit on max line length of 4096 characters (:iss:`3806`)
- Fix turning off cursor blink via escape codes not working (:iss:`3808`)
- Allow using neighboring window operations in the stack layout. The previous
window is considered the left and top neighbor and the next window is
considered the bottom and right neighbor (:iss:`3778`)
- macOS: Render colors in the sRGB colorspace to match other macOS terminal
applications (:iss:`2249`)
- Add a new variable ``{num_window_groups}`` for the :opt:`tab_title_template`
(:iss:`3837`)
- Wayland: Fix :opt:`initial_window_width/height <remember_window_size>` specified
in cells not working on High DPI screens (:iss:`3834`)
- A new theme for the kitty website with support for dark mode.
- Render ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ with spaces at the edges. Matches rendering in
most other programs and allows long chains of them to look better
(:iss:`3844`)
- hints kitten: Detect paths and hashes that appear over multiple lines.
Note that this means that all line breaks in the text are no longer \n
soft breaks are instead \r. If you use a custom regular expression that
is meant to match over line breaks, you will need to match over both.
(:iss:`3845`)
- Allow leading or trailing spaces in :opt:`tab_activity_symbol`
- Fix mouse actions not working when caps lock or num lock are engaged
(:iss:`3859`)
- macOS: Fix automatic detection of bold/italic faces for fonts that
use the family name as the full face name of the regular font not working
(:iss:`3861`)
- clipboard kitten: fix copies to clipboard not working without the
:option:`kitty +kitten clipboard --wait-for-completion` option
0.21.2 [2021-06-28]
----------------------
- A new :opt:`adjust_baseline` option to adjust the vertical alignment of text
inside a line (:pull:`3734`)
- A new :opt:`url_excluded_characters` option to exclude additional characters
when detecting URLs under the mouse (:pull:`3738`)
- Fix a regression in 0.21.0 that broke rendering of private use Unicode symbols followed
by spaces, when they also exist not followed by spaces (:iss:`3729`)
- ssh kitten: Support systems where the login shell is a non-POSIX shell
(:iss:`3405`)
- ssh kitten: Add completion (:iss:`3760`)
- ssh kitten: Fix "Connection closed" message being printed by ssh when running
remote commands
- Add support for the XTVERSION escape code
- macOS: Fix a regression in 0.21.0 that broke middle-click to paste from clipboard (:iss:`3730`)
- macOS: Fix shortcuts in the global menu bar responding slowly when cursor blink
is disabled/timed out (:iss:`3693`)
- When displaying scrollback ensure that the window does not quit if the amount
of scrollback is less than a screen and the user has the ``--quit-if-one-screen``
option enabled for less (:iss:`3740`)
- Linux: Fix Emoji/bitmapped fonts not use able in symbol_map
- query terminal kitten: Allow querying font face and size information
(:iss:`3756`)
- hyperlinked grep kitten: Fix context options not generating contextual output (:iss:`3759`)
- Allow using superscripts in tab titles (:iss:`3763`)
- Unicode input kitten: Fix searching when a word has more than 1024 matches (:iss:`3773`)
0.21.1 [2021-06-14]
----------------------
@@ -27,7 +238,7 @@ To update |kitty|, :doc:`follow the instructions <binary>`.
:kbd:`ctrl+shift`
- Allow remapping all mouse button press/release events to perform arbitrary
actions. :ref:`See details <conf-kitty-mouse.mousemap>`.
actions. :ref:`See details <conf-kitty-mouse.mousemap>` (:iss:`1033`)
- Support infinite length ligatures (:iss:`3504`)
@@ -1639,8 +1850,7 @@ To update |kitty|, :doc:`follow the instructions <binary>`.
using standard keyboards) via `IBus
<https://github.com/ibus/ibus/wiki/ReadMe>`_ (:iss:`469`)
- Implement completion for the kitty command in bash and zsh. See
:ref:`completion`.
- Implement completion for the kitty command in bash and zsh
- Render the text under the cursor in a fixed color, configurable via
the option :opt:`cursor_text_color` (:iss:`126`)

26
docs/color-stack.rst Normal file
View File

@@ -0,0 +1,26 @@
Saving and restoring colors
==============================
It is often useful for a full screen application with its own color themes to
set the default foreground, background, selection and cursor colors and the
ANSI color table. This allows for various performance optimizations when
drawing the screen. The problem is that if the user previously used the escape
codes to change these colors herself, then running the full screen application
will lose her changes even after it exits. To avoid this, kitty introduces a
new pair of *OSC* escape codes to push and pop the current color values from a
stack::
<ESC>]30001<ESC>\ # push onto stack
<ESC>]30101<ESC>\ # pop from stack
These escape codes save/restore the colors, default
background, default foreground, selection background, selection foreground and
cursor color and the 256 colors of the ANSI color table.
.. note:: In July 2020, after several years, XTerm copied this protocol
extension, without acknowledgement, and using incompatible escape codes
(XTPUSHCOLORS, XTPOPCOLORS, XTREPORTCOLORS). And they decided to save not
just the dynamic colors but the entire ANSI color table. In the interests of
promoting interoperability, kitty added support for XTerm's escape codes as
well, and changed this extension to also save/restore the entire ANSI color
table.

View File

@@ -22,7 +22,6 @@ from pygments.token import ( # type: ignore
Comment, Keyword, Literal, Name, Number, String, Whitespace
)
from sphinx import addnodes, version_info # type: ignore
from sphinx.environment.adapters.toctree import TocTree # type: ignore
from sphinx.util.logging import getLogger # type: ignore
kitty_src = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -30,7 +29,7 @@ if kitty_src not in sys.path:
sys.path.insert(0, kitty_src)
from kitty.conf.types import Definition # noqa
from kitty.constants import str_version # noqa
from kitty.constants import str_version, website_url # noqa
# config {{{
# -- Project information -----------------------------------------------------
@@ -60,8 +59,14 @@ extensions = [
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinx_copybutton',
'sphinx_inline_tabs',
"sphinxext.opengraph",
]
# URL for OpenGraph tags
ogp_site_url = website_url()
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -85,13 +90,10 @@ language: Optional[str] = None
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = [
'_build', 'Thumbs.db', '.DS_Store',
'generated/cli-*.rst', 'generated/conf-*.rst'
'_build', 'Thumbs.db', '.DS_Store', 'basic.rst',
'generated/cli-*.rst', 'generated/conf-*.rst', 'generated/actions.rst'
]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
rst_prolog = '''
.. |kitty| replace:: *kitty*
.. |version| replace:: VERSION
@@ -101,7 +103,6 @@ rst_prolog = '''
.. role:: bold
.. role:: cyan
.. role:: title
.. role:: env
'''.replace('VERSION', str_version)
@@ -111,32 +112,26 @@ rst_prolog = '''
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
html_theme = 'furo'
html_title = 'kitty'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'logo': 'kitty.png',
'show_powered_by': False,
'fixed_sidebar': True,
'sidebar_collapse': True,
'github_button': False,
'github_banner': True,
'github_user': 'kovidgoyal',
'github_repo': 'kitty',
# increase contrast of link color with text color
'link': '#00587d',
'link_hover': 'green',
html_theme_options: Dict[str, Any] = {
'sidebar_hide_name': True,
'navigation_with_keys': True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static', '../logo/kitty.png']
html_favicon = '../logo/kitty.png'
html_static_path = ['_static']
html_favicon = html_logo = '../logo/kitty.svg'
html_css_files = ['custom.css']
html_js_files = ['custom.js']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
@@ -146,17 +141,9 @@ html_favicon = '../logo/kitty.png'
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
html_sidebars = {
'**': [
'about.html',
'support.html',
'searchbox.html',
'localtoc.html',
'relations.html',
]
}
html_show_sourcelink = False
html_show_sphinx = False
manpages_url = 'https://man7.org/linux/man-pages/man{section}/{page}.{section}.html'
# -- Options for manual page output ------------------------------------------
@@ -220,28 +207,6 @@ def commit_role(name: str, rawtext: str, text: str, lineno: int, inliner: Any, o
# }}}
# Sidebar ToC {{{
def create_toc(app: Any, pagename: str) -> Optional[Any]:
tt = TocTree(app.env)
toctree = tt.get_toc_for(pagename, app.builder)
if toctree is not None:
subtree = toctree[toctree.first_child_matching_class(nodes.list_item)]
bl = subtree.first_child_matching_class(nodes.bullet_list)
if bl is None:
return None # Empty ToC
subtree = subtree[bl]
# for li in subtree.traverse(nodes.list_item):
# modify_li(li)
# subtree['ids'] = [ID]
return app.builder.render_partial(subtree)['fragment']
def add_html_context(app: Any, pagename: str, templatename: str, context: Any, *args: Any) -> None:
if 'toc' in context:
context['toc'] = create_toc(app, pagename) or context['toc']
# }}}
# CLI docs {{{
def write_cli_docs(all_kitten_names: Iterable[str]) -> None:
from kitty.cli import option_spec_as_rst
@@ -281,6 +246,11 @@ if you specify a program-to-run you can use the special placeholder
with open(f'generated/cli-kitten-{kitten}.rst', 'w') as f:
p = partial(print, file=f)
p('.. program::', f'kitty +kitten {kitten}')
p(f'\nSource code for {kitten}')
p('-' * 72)
p(f'\nThe source code for this kitten is `available on GitHub <https://github.com/kovidgoyal/kitty/tree/master/kittens/{kitten}>`_.')
p('\nCommand Line Interface')
p('-' * 72, file=f)
p('\n\n' + option_spec_as_rst(
data['options'], message=data['help_text'], usage=data['usage'], appname=f'kitty +kitten {kitten}',
heading_char='^'))
@@ -347,6 +317,8 @@ class ConfLexer(RegexLexer):
(r'(include)(\s+)(.+?)$', bygroups(Comment.Preproc, Whitespace, Name.Namespace)),
(r'(map)(\s+)(\S+)(\s+)', bygroups(
Keyword.Declaration, Whitespace, String, Whitespace), 'action'),
(r'(mouse_map)(\s+)(\S+)(\s+)(\S+)(\s+)(\S+)(\s+)', bygroups(
Keyword.Declaration, Whitespace, String, Whitespace, Name.Variable, Whitespace, String, Whitespace), 'action'),
(r'(symbol_map)(\s+)(\S+)(\s+)(.+?)$', bygroups(
Keyword.Declaration, Whitespace, String, Whitespace, Literal)),
(r'([a-zA-Z_0-9]+)(\s+)', bygroups(
@@ -510,9 +482,27 @@ def write_conf_docs(app: Any, all_kitten_names: Iterable[str]) -> None:
definition = get_kitten_conf_docs(kitten)
if definition:
generate_default_config(definition, f'kitten-{kitten}')
from kitty.actions import as_rst
with open('generated/actions.rst', 'w', encoding='utf-8') as f:
f.write(as_rst())
# }}}
def add_html_context(app: Any, pagename: str, templatename: str, context: Any, doctree: Any, *args: Any) -> None:
context['analytics_id'] = app.config.analytics_id
if 'toctree' in context:
# this is needed with furo to use all titles from pages
# in the sidebar (global) toc
original_toctee_function = context['toctree']
def include_sub_headings(**kwargs: Any) -> Any:
kwargs['titles_only'] = False
return original_toctee_function(**kwargs)
context['toctree'] = include_sub_headings
def setup(app: Any) -> None:
os.makedirs('generated/conf', exist_ok=True)
from kittens.runner import all_kitten_names
@@ -520,10 +510,11 @@ def setup(app: Any) -> None:
write_cli_docs(kn)
write_remote_control_protocol_docs()
write_conf_docs(app, kn)
app.add_css_file('custom.css')
app.add_config_value('analytics_id', '', 'env')
app.connect('html-page-context', add_html_context)
app.add_lexer('session', SessionLexer() if version_info[0] < 3 else SessionLexer)
app.add_role('link', link_role)
app.add_role('iss', partial(num_role, 'issues'))
app.add_role('pull', partial(num_role, 'pull'))
app.add_role('disc', partial(num_role, 'discussions'))
app.add_role('commit', commit_role)
app.connect('html-page-context', add_html_context)

View File

@@ -1,7 +1,5 @@
:tocdepth: 2
Configuring kitty
===============================
kitty.conf
-----------------------
.. highlight:: conf
@@ -34,11 +32,15 @@ expanded, so :code:`${USER}.conf` becomes :file:`name.conf` if
include other.conf
.. note:: Syntax highlighting for :file:`kitty.conf` in vim is available via
`vim-kitty <https://github.com/fladson/vim-kitty>`_.
.. include:: /generated/conf-kitty.rst
Sample kitty.conf
^^^^^^^^^^^^^^^^^^^^^
--------------------
.. only:: html
@@ -53,3 +55,14 @@ Sample kitty.conf
file with full documentation and all settings commented out. If you
have a pre-existing kitty.conf, then that will be used instead, delete
it to see the sample file.
All mappable actions
------------------------
See the :doc:`list of all the things you can make kitty can do </actions>`.
.. toctree::
:hidden:
actions

21
docs/deccara.rst Normal file
View File

@@ -0,0 +1,21 @@
Setting text styles/colors in arbitrary regions of the screen
------------------------------------------------------------------
There already exists an escape code to set *some* text attributes in arbitrary
regions of the screen, `DECCARA
<https://vt100.net/docs/vt510-rm/DECCARA.html>`_. However, it is limited to
only a few attributes. |kitty| extends this to work with *all* SGR attributes.
So, for example, this can be used to set the background color in an arbitrary
region of the screen.
The motivation for this extension is the various problems with the existing
solution for erasing to background color, namely the *background color erase
(bce)* capability. See
`this discussion <https://github.com/kovidgoyal/kitty/issues/160#issuecomment-346470545>`_
and `this FAQ <https://invisible-island.net/ncurses/ncurses.faq.html#bce_mismatches>`_
for a summary of problems with *bce*.
For example, to set the background color to blue in a
rectangular region of the screen from (3, 4) to (10, 11), you use::
<ESC>[2*x<ESC>[4;3;11;10;44$r<ESC>[*x

View File

@@ -0,0 +1,122 @@
.. _desktop_notifications:
Desktop notifications
=======================
|kitty| implements an extensible escape code (OSC 99) to show desktop
notifications. It is easy to use from shell scripts and fully extensible to
show title and body. Clicking on the notification can optionally focus the
window it came from, and/or send an escape code back to the application running
in that window.
The design of the escape code is partially based on the discussion in
the defunct
`terminal-wg <https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/13>`_
The escape code has the form::
<OSC> 99 ; metadata ; payload <terminator>
Here ``<OSC>`` is :code:`<ESC>]` and ``<terminator>`` is
:code:`<ESC><backslash>`. The metadata is a section of colon separated
:code:`key=value` pairs. Every key must be a single character from the set
:code:`a-zA-Z` and every value must be a word consisting of characters from
the set :code:`a-zA-Z0-9-_/\+.,(){}[]*&^%$#@!`~`. The payload must be
interpreted based on the metadata section. The two semi-colons *must* always be
present even when no metadata is present.
Before going into details, lets see how one can display a simple, single line
notification from a shell script::
printf '\x1b]99;;Hello world\x1b\\'
To show a message with a title and a body::
printf '\x1b]99;i=1:d=0;Hello world\x1b\\'
printf '\x1b]99;i=1:d=1:p=body;This is cool\x1b\\'
The most important key in the metadata is the ``p`` key, it controls how the
payload is interpreted. A value of ``title`` means the payload is setting the
title for the notification. A value of ``body`` means it is setting the body,
and so on, see the table below for full details.
The design of the escape code is fundamentally chunked, this is because
different terminal emulators have different limits on how large a single escape
code can be. Chunking is accomplished by the ``i`` and ``d`` keys. The ``i``
key is the *notification id* which can be any string containing the characters
``[a-zA-Z0-9_-+.]``. The ``d`` key stands for *done* and
can only take the values ``0`` and ``1``. A value of ``0`` means the
notification is not yet done and the terminal emulator should hold off
displaying it. A value of ``1`` means the notification is done, and should be
displayed. You can specify the title or body multiple times and the terminal
emulator will concatenate them, thereby allowing arbitrarily long text
(terminal emulators are free to impose a sensible limit to avoid
Denial-of-Service attacks).
Both the ``title`` and ``body`` payloads must be either UTF-8 encoded plain
text with no embedded escape codes, or UTF-8 text that is base64 encoded, in
which case there must be an ``e=1`` key in the metadata to indicate the payload
is base64 encoded.
When the user clicks the notification, a couple of things can happen, the
terminal emulator can focus the window from which the notification came, and/or
it can send back an escape code to the application indicating the notification
was activated. This is controlled by the ``a`` key which takes a comma
separated set of values, ``report`` and ``focus``. The value ``focus`` means
focus the window from which the notification was issued and is the default.
``report`` means send an escape code back to the application. The format of the
returned escape code is::
<OSC> 99 ; i=identifier ; <terminator>
The value of ``identifier`` comes from the ``i`` key in the escape code sent by
the application. If the application sends no identifier, then the terminal
*must* use ``i=0``. Actions can be preceded by a negative sign to turn them
off, so for example if you do not want any action, turn off the default
``focus`` action with::
a=-focus
Complete specification of all the metadata keys is in the table below. If a
terminal emulator encounters a key in the metadata it does not understand,
the key *must* be ignored, to allow for future extensibility of this escape
code. Similarly if values for known keys are unknown, the terminal emulator
*should* either ignore the entire escape code or perform a best guess effort
to display it based on what it does understand.
.. note::
It is possible to extend this escape code to allow specifying an icon for
the notification, however, given that some platforms, such as macOS, dont
allow displaying custom icons on a notification, at all, it was decided to
leave it out of the spec for the time being.
Similarly, features such as scheduled notifications could be added in future
revisions.
======= ==================== ========= =================
Key Value Default Description
======= ==================== ========= =================
``a`` Comma separated list ``focus`` What action to perform when the
of ``report``, notification is clicked
``focus``, with
optional leading
``-``
``d`` ``0`` or ``1`` ``1`` Indicates if the notification is
complete or not.
``e`` ``0`` or ``1`` ``0`` If set to ``1`` means the payload is base64 encoded UTF-8,
otherwise it is plain UTF-8 text with no C0 control codes in it
``i`` ``[a-zA-Z0-9-_+.]`` ``0`` Identifier for the notification
``p`` One of ``title`` or ``title`` Whether the payload is the notification title or body. If a
``body``. notification has no title, the body will be used as title.
======= ==================== ========= =================
.. note::
|kitty| also supports the legacy OSC 9 protocol developed by iTerm2 for
desktop notifications.

View File

@@ -3,9 +3,6 @@ Frequently Asked Questions
.. highlight:: sh
.. contents::
:local:
Some special symbols are rendered small/truncated in kitty?
-----------------------------------------------------------
@@ -36,7 +33,7 @@ it by adding the following to your vimrc::
let &t_ut=''
See :ref:`here <ext_styles>` for why |kitty| does not support background color erase.
See :doc:`here <deccara>` for why |kitty| does not support background color erase.
I get errors about the terminal being unknown or opening the terminal failing when SSHing into a different computer?
@@ -55,7 +52,8 @@ type it each time::
alias ssh="kitty +kitten ssh"
If for some reason that does not work (typically because the server is using a
non POSIX compliant shell), you can try using it with python instead::
non POSIX compliant shell as ``/bin/sh``), you can try using it with ``python``
instead::
kitty +kitten ssh use-python myserver
@@ -119,8 +117,15 @@ explicitly set a UTF-8 locale, like::
How do I change the colors in a running kitty instance?
------------------------------------------------------------
You can either use the
`OSC terminal escape codes <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Operating-System-Commands>`_
The easiest way to do it is to use the :doc:`themes kitten </kittens/themes>`,
to choose a new color theme. Simply run::
kitty +kitten themes
And choose your theme from the list.
Additionally, You can use the
`OSC terminal escape codes <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_
to set colors or you can define keyboard shortcuts to set colors, for example::
map f1 set_colors --configured /path/to/some/config/file/colors.conf
@@ -306,10 +311,6 @@ terminal and then switch to another and these terminals have different TERM
variables, tmux will break. You will need to restart it as tmux does not
support multiple terminfo definitions.
Copying to clipboard via OSC 52 will not work, because tmux does not support
the extended version of that protocol, you will need to add ``no-append`` to
:opt:`clipboard_control` in kitty.conf.
If you use any of the advanced features that kitty has innovated, such as
styled underlines, desktop notifications, extended keyboard support, etc.
they may or may not work, depending on the whims of tmux's maintainer, your

135
docs/glossary.rst Normal file
View File

@@ -0,0 +1,135 @@
:orphan:
Glossary
=========
.. glossary::
os_window
kitty has two kinds of windows. Operating System windows, refered to as :term:`OS
Window <os_window>`, and *kitty windows*. An OS Window consists of one or more kitty
:term:`tabs <tab>`. Each tab in turn consists of one or more *kitty
windows* organized in a :term:`layout`.
tab
A *tab* refers to a group of :term:`kitty windows <window>`, organized in
a :term:`layout`. Every :term:`OS Window <os_window>` contains one or more tabs.
layout
A *layout* is a system of organizing :term:`kitty windows <window>` in
groups inside a tab. The layout automatically maintains the size and
position of the windows, think of a layout as a tiling window manager for
the terminal. See :doc:`layouts` for details.
window
kitty has two kinds of windows. Operating System windows, refered to as :term:`OS
Window <os_window>`, and *kitty windows*. An OS Window consists of one or more kitty
:term:`tabs <tab>`. Each tab in turn consists of one or more *kitty
windows* organized in a :term:`layout`.
overlay
An *overlay window* is a :term:`kitty window <window>` that is placed on
top of an existing kitty window, entirely covering it. Overlays are used
throught kitty, for example, to display the :ref:`the scrollback buffer <scrollback>`,
to display :doc:`hints </kittens/hints>`, for :doc:`unicode input
</kittens/unicode-input>` etc.
hyperlinks
Terminals can have hyperlinks, just like the internet. In kitty you can
:doc:`control exactly what happens <open_actions>` when clicking on a
hyperlink, based on the type of link and its URL.
.. _env_vars:
Environment variables
------------------------
Variables that influence kitty behavior
.. envvar:: KITTY_CONFIG_DIRECTORY
Controls where kitty looks for :file:`kitty.conf` and other configuration
files. Defaults to :file:`~/.config/kitty`. For full details of the config
directory lookup mechanism see, :option:`kitty --config`.
.. envvar:: VISUAL
The terminal editor (such as ``vi`` or ``nano``) kitty uses, when, for
instance, opening :file:`kitty.conf` in response to :sc:`edit_config_file`.
.. envvar:: EDITOR
Same as :envvar:`VISUAL`. Used if :envvar:`VISUAL` is not set.
Variables that kitty sets when running child programs
.. envvar:: LANG
This is set only on macOS, and only if the country and language from the
macOS user settings form a valid locale.
.. envvar:: KITTY_WINDOW_ID
An integer that is the id for the kitty :term:`window` the program is running in.
Can be used with the :doc:`kitty remote control facility <remote-control>`.
.. envvar:: KITTY_PID
An integer that is the process id for the kitty process in which the program
is running. Allows programs to tell kitty to reload its config by sending it
the SIGUSR1 signal.
.. envvar:: WINDOWID
The id for the :term:`OS Window <os_window>` the program is running in. Only available
on platforms that have ids for their windows, such as X11 and macOS.
.. envvar:: TERM
The name of the terminal, defaults to ``xterm-kitty``. See :opt:`term`.
.. envvar:: TERMINFO
Path to a directory containing the kitty terminfo database.
.. envvar:: COLORTERM
Set to the value ``truecolor`` to indicate that kitty supports 16 million
colors.
.. envvar:: KITTY_LISTEN_ON
Set when the :doc:`remote control <remote-control>` facility is enabled and
the a socket is used for control via :option:`kitty --listen-on` or :opt:`listen_on`.
Contains the path to the socket. Avoids needs to use :option:`kitty @ --to` when
issuing remote control commands.
.. envvar:: KITTY_PIPE_DATA
Set to data describing the layout of the screen when running child
programs using :option:`launch --stdin-source` with the contents of the
screen/scrollback piped to them.
.. envvar:: KITTY_CHILD_CMDLINE
Set to the command line of the child process running in the kitty
window when calling the notification callback program on terminal bell, see
:opt:`command_on_bell`.
.. envvar:: KITTY_COMMON_OPTS
Set with the values of some common kitty options when running
kittens, so kittens can use them without needing to load kitty.conf.

View File

@@ -1,18 +1,16 @@
:tocdepth: 3
The terminal graphics protocol
==================================
Terminal graphics protocol
=================================
The goal of this specification is to create a flexible and performant protocol
that allows the program running in the terminal, hereafter called the *client*,
to render arbitrary pixel (raster) graphics to the screen of the terminal
emulator. The major design goals are
emulator. The major design goals are:
* Should not require terminal emulators to understand image formats.
* Should allow specifying graphics to be drawn at individual pixel positions.
* The graphics should integrate with the text, in particular it should be possible to draw graphics
below as well as above the text, with alpha blending. The graphics should also scroll with the text, automatically.
* Should use optimizations when the client is running on the same computer as the terminal emulator.
* Should not require terminal emulators to understand image formats.
* Should allow specifying graphics to be drawn at individual pixel positions.
* The graphics should integrate with the text, in particular it should be possible to draw graphics
below as well as above the text, with alpha blending. The graphics should also scroll with the text, automatically.
* Should use optimizations when the client is running on the same computer as the terminal emulator.
For some discussion regarding the design choices, see `#33
<https://github.com/kovidgoyal/kitty/issues/33>`_.
@@ -30,23 +28,19 @@ alpha-blending and text over graphics.
Some programs and libraries that use the kitty graphics protocol:
* `termpdf.py <https://github.com/dsanson/termpdf.py>`_ - a terminal PDF/DJVU/CBR viewer
* `ranger <https://github.com/ranger/ranger>`_ - a terminal file manager, with
image previews, see this `PR <https://github.com/ranger/ranger/pull/1077>`_
* :doc:`kitty-diff <kittens/diff>` - a side-by-side terminal diff program with support for images
* `pixcat <https://github.com/mirukana/pixcat>`_ - a third party CLI and python library that wraps the graphics protocol
* `neofetch <https://github.com/dylanaraps/neofetch>`_ - A command line system
information tool
* `viu <https://github.com/atanunq/viu>`_ - a terminal image viewer
* `glkitty <https://github.com/michaeljclark/glkitty>`_ - C library to draw OpenGL shaders in the terminal with a glgears demo
* `ctx.graphics <https://ctx.graphics/>`_ - Library for drawing graphics
* `timg <https://github.com/hzeller/timg>`_ - a terminal image and video viewer
* `notcurses <https://github.com/dankamongmen/notcurses>`_ - C library for terminal graphics with bindings for C++, Rust and Python
* `rasterm <https://github.com/BourgeoisBear/rasterm>`_ - Go library to display images in the the terminal
.. contents::
:local:
* `termpdf.py <https://github.com/dsanson/termpdf.py>`_ - a terminal PDF/DJVU/CBR viewer
* `ranger <https://github.com/ranger/ranger>`_ - a terminal file manager, with
image previews, see this `PR <https://github.com/ranger/ranger/pull/1077>`_
* :doc:`kitty-diff <kittens/diff>` - a side-by-side terminal diff program with support for images
* `pixcat <https://github.com/mirukana/pixcat>`_ - a third party CLI and python library that wraps the graphics protocol
* `neofetch <https://github.com/dylanaraps/neofetch>`_ - A command line system
information tool
* `viu <https://github.com/atanunq/viu>`_ - a terminal image viewer
* `glkitty <https://github.com/michaeljclark/glkitty>`_ - C library to draw OpenGL shaders in the terminal with a glgears demo
* `ctx.graphics <https://ctx.graphics/>`_ - Library for drawing graphics
* `timg <https://github.com/hzeller/timg>`_ - a terminal image and video viewer
* `notcurses <https://github.com/dankamongmen/notcurses>`_ - C library for terminal graphics with bindings for C++, Rust and Python
* `rasterm <https://github.com/BourgeoisBear/rasterm>`_ - Go library to display images in the the terminal
Getting the window size
@@ -57,28 +51,33 @@ client must be able to get the window size in pixels and the number of cells
per row and column. This can be done by using the ``TIOCGWINSZ`` ioctl. Some
code to demonstrate its use
In C:
.. tab:: C
.. code-block:: c
.. code-block:: c
#include <stdio.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <sys/ioctl.h>
int main(int argc, char **argv) {
struct winsize sz;
ioctl(0, TIOCGWINSZ, &sz);
printf("number of rows: %i, number of columns: %i, screen width: %i, screen height: %i\n", sz.ws_row, sz.ws_col, sz.ws_xpixel, sz.ws_ypixel);
return 0;
}
int main(int argc, char **argv) {
struct winsize sz;
ioctl(0, TIOCGWINSZ, &sz);
printf(
"number of rows: %i, number of columns: %i, screen width: %i, screen height: %i\n",
sz.ws_row, sz.ws_col, sz.ws_xpixel, sz.ws_ypixel);
return 0;
}
In Python:
.. code-block:: python
.. tab:: Python
import array, fcntl, sys, termios
buf = array.array('H', [0, 0, 0, 0])
fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, buf)
print('number of rows: {}, number of columns: {}, screen width: {}, screen height: {}'.format(*buf))
.. code-block:: python
import array, fcntl, sys, termios
buf = array.array('H', [0, 0, 0, 0])
fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, buf)
print((
'number of rows: {} number of columns: {}'
'screen width: {} screen height: {}').format(*buf))
Note that some terminals return ``0`` for the width and height values. Such
terminals should be modified to return the correct values. Examples of
@@ -98,32 +97,36 @@ features of the graphics protocol:
.. code-block:: python
import sys
from base64 import standard_b64encode
import sys
from base64 import standard_b64encode
def serialize_gr_command(cmd, payload=None):
cmd = ','.join('{}={}'.format(k, v) for k, v in cmd.items())
ans = []
w = ans.append
w(b'\033_G'), w(cmd.encode('ascii'))
if payload:
w(b';')
w(payload)
w(b'\033\\')
return b''.join(ans)
def write_chunked(cmd, data):
data = standard_b64encode(data)
while data:
chunk, data = data[:4096], data[4096:]
m = 1 if data else 0
cmd['m'] = m
sys.stdout.buffer.write(serialize_gr_command(cmd, chunk))
sys.stdout.flush()
cmd.clear()
def serialize_gr_command(**cmd):
payload = cmd.pop('payload', None)
cmd = ','.join('{}={}'.format(k, v) for k, v in cmd.items())
ans = []
w = ans.append
w(b'\033_G'), w(cmd.encode('ascii'))
if payload:
w(b';')
w(payload)
w(b'\033\\')
return b''.join(ans)
with open(sys.argv[-1], 'rb') as f:
write_chunked({'a': 'T', 'f': 100}, f.read())
def write_chunked(**cmd):
data = standard_b64encode(cmd.pop('data'))
while data:
chunk, data = data[:4096], data[4096:]
m = 1 if data else 0
sys.stdout.buffer.write(serialize_gr_command(payload=chunk, m=m,
**cmd))
sys.stdout.flush()
cmd.clear()
with open(sys.argv[-1], 'rb') as f:
write_chunked(a='T', f=100, data=f.read())
Save this script as :file:`png.py`, then you can use it to display any PNG
@@ -226,8 +229,9 @@ Value of `t` Meaning
is in a known temporary directory, such as :file:`/tmp`,
:file:`/dev/shm`, :file:`TMPDIR env var if present` and any platform
specific temporary directories.
``s`` A *shared memory object*, which on POSIX systems is a `POSIX shared memory object
<http://man7.org/linux/man-pages/man7/shm_overview.7.html>`_ and on Windows is a
``s`` A *shared memory object*, which on POSIX systems is a
`POSIX shared memory object <https://pubs.opengroup.org/onlinepubs/9699919799/functions/shm_open.html>`_
and on Windows is a
`Named shared memory object <https://docs.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory>`_.
The terminal emulator must read the data from the memory
object and then unlink and close it on POSIX and just
@@ -590,7 +594,7 @@ Clients can control animations by using the ``a=a`` key in the escape code sent
to the terminal.
The simplest is client driven animations, where the client transmits the frame
data and the also instructs the terminal to make a particular frame the current
data and then also instructs the terminal to make a particular frame the current
frame. To change the current frame, use the ``c`` key::
<ESC>_Ga=a,i=3,c=7<ESC>\
@@ -632,6 +636,45 @@ static background.
In particular, the first frame or *root frame* is created with the base image
data and has no gap, so its gap must be set using this control code.
Composing animation frames
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.22.0
Support for frame composition
Clients can *compose* animation frames, this means that they can compose pixels
in rectangular regions from one frame onto another frame. This allows for fast
and low band-width modification of frames.
To achieve this use the ``a=c`` key. The source frame is specified with
``r=frame number`` and the destination frame as ``c=frame number``. The size of
the rectangle is specified as ``w=width,h=height`` pixels. If unspecified, the
full image width and height are used. The offset of the rectangle from the
top-left corner for the source frame is specified by the ``x,y`` keys and the
destination frame by the ``X,Y`` keys. The composition operation is specified
by the ``C`` key with the default being to alpha blend the source rectangle
onto the destination rectangle. With ``C=1`` it will be a simple replacement
of pixels. For example::
<ESC>_Gi=1,r=7,c=9,w=23,h=27,X=4,Y=8,x=1,y=3<ESC>\
Will compose a ``23x27`` rectangle located at ``(4, 8)`` in the ``7th frame``
onto the rectangle located at ``(1, 3)`` in the ``9th frame``. These will be
in the image with ``id=1``.
If the frames or the image are not found the terminal emulator must
respond with `ENOENT`. If the rectangles go out of bounds of the image
the terminal must respond with `EINVAL`. If the source and destination frames are
the same and the rectangles overlap, the terminal must respond with `EINVAL`.
.. note::
In kitty, doing a composition will cause a frame to be *fully rendered*
potentially increasing its storage requirements, when the frame was previously
stored as a set of operations on other frames. If this happens and there
is not enough storage space, kitty will respond with ENOSPC.
Image persistence and storage quotas
-----------------------------------------
@@ -654,10 +697,10 @@ take, and the default value they take when missing. All integers are 32-bit.
Key Value Default Description
======= ==================== ========= =================
``a`` Single character. ``t`` The overall action this graphics command is performing.
``(t, T, q, p, d)`` ``t`` - transmit data, ``T`` - transmit data and display image,
``q`` - query terminal, ``p`` - put (display) previous transmitted image,
``(a, c, d, f, `` ``t`` - transmit data, ``T`` - transmit data and display image,
``p, q, t, T)`` ``q`` - query terminal, ``p`` - put (display) previous transmitted image,
``d`` - delete image, ``f`` - transmit data for animation frames,
``a`` - control animation
``a`` - control animation, ``c`` - compose animation frames
``q`` ``0, 1, 2`` ``0`` Suppress responses from the terminal to this graphics command.
@@ -711,6 +754,20 @@ Key Value Default Description
``Y`` Positive integer ``0`` The background color for pixels not
specified in the frame data. Must be in 32-bit RGBA format
**Keys for animation frame composition**
-----------------------------------------------------------
``c`` Positive integer ``0`` The 1-based frame number of the frame whose image data serves as the overlaid data
``r`` Positive integer ``0`` The 1-based frame number of the frame that is being edited.
``x`` Positive integer ``0`` The left edge (in pixels) of the destination rectangle
``y`` Positive integer ``0`` The top edge (in pixels) of the destination rectangle
``w`` Positive integer ``0`` The width (in pixels) of the source and destination rectangles. By default, the entire width is used
``h`` Positive integer ``0`` The height (in pixels) of the source and destination rectangles. By default, the entire height is used
``X`` Positive integer ``0`` The left edge (in pixels) of the source rectangle
``Y`` Positive integer ``0`` The top edge (in pixels) of the source rectangle
``C`` Positive integer ``0`` The composition mode for blending
pixels. Default is full alpha blending. ``1`` means a simple overwrite.
**Keys for animation control**
-----------------------------------------------------------

View File

@@ -1,421 +1,66 @@
:tocdepth: 2
==========================================================
kitty - the fast, featureful, GPU based terminal emulator
kitty
==========================================================
.. container:: major-features
*The fast, feature-rich, GPU based terminal emulator*
* Offloads rendering to the GPU for :doc:`lower system load <performance>` and
buttery smooth scrolling. Uses threaded rendering to minimize input latency.
.. toctree::
:hidden:
* Supports all modern terminal features: :doc:`graphics (images)
<graphics-protocol>`, unicode, `true-color
<https://gist.github.com/XVilka/8346728>`_,
OpenType ligatures, mouse protocol, :doc:`hyperlinks <open_actions>`,
focus tracking, `bracketed paste <https://cirw.in/blog/bracketed-paste>`_
and several :doc:`new terminal protocol extensions
<protocol-extensions>`.
quickstart
overview
faq
support
performance
changelog
integrations
protocol-extensions
* Supports tiling multiple terminal windows side by side in different
:ref:`layouts <layouts>` without needing to use an extra program like tmux
* Can be :doc:`controlled from scripts or the shell prompt <remote-control>`,
even over SSH.
.. tab:: Fast
* Has a framework for :ref:`kittens`, small terminal programs that can be used to
extend |kitty|'s functionality. For example, they are used for
:doc:`Unicode input <kittens/unicode-input>`, :doc:`Hints <kittens/hints>` and
:doc:`Side-by-side diff <kittens/diff>`.
* Offloads rendering to the GPU for :doc:`lower system load <performance>`
* Uses threaded rendering for absolutely minimal latency
* Performance tradeoffs can be :ref:`tuned <conf-kitty-performance>`
* Supports :ref:`startup sessions <sessions>` which allow you to specify
the window/tab layout, working directories and programs to run on startup.
.. tab:: Capable
* Cross-platform: |kitty| works on Linux and macOS, but because it uses only
OpenGL for rendering, it should be trivial to port to other Unix-like platforms.
* Graphics, with :doc:`images and animations <graphics-protocol>`
* Ligatures and emoji, with :opt:`per glyph font substitution <symbol_map>`
* :term:`Hyperlinks<hyperlinks>`, with :doc:`configurable actions <open_actions>`
* Allows you to open :ref:`the scrollback buffer <scrollback>` in a
separate window using arbitrary programs of your choice. This is useful for
browsing the history comfortably in a pager or editor.
.. tab:: Scriptable
* Has :ref:`multiple copy/paste buffers <cpbuf>`, like vim.
* Control from :doc:`scripts or the shell <remote-control>`
* Extend with :ref:`kittens <kittens>` using the Python language
* Use :ref:`startup sessions <sessions>` to specify working environments
.. tab:: Composable
* Programmble tabs, :ref:`splits <splits_layout>` and multiple :doc:`layouts <layouts>` to manage windows
* Browse the :ref:`entire history <scrollback>` or the output from the last command comfortably in pagers and editors
* Edit or download :doc:`remote files <kittens/remote_file>` in an existing SSH session
.. tab:: Cross-platform
* Linux
* macOS
* Various BSDs
.. tab:: Innovative
Pioneered various extensions to move the entire terminal ecosystem forward
* :doc:`graphics-protocol`
* :doc:`keyboard-protocol`
* Lots more in :doc:`protocol-extensions`
.. figure:: screenshots/screenshot.png
:alt: Screenshot, showing three programs in the 'Tall' layout
:align: center
:scale: 100%
:width: 100%
Screenshot, showing vim, tig and git running in |kitty| with the 'Tall' layout
.. contents::
:local:
:depth: 1
.. _quickstart:
Quickstart
--------------
Pre-built binaries of |kitty| are available for both macOS and Linux.
See the :doc:`binary install instructions </binary>`. You can also
:doc:`build from source </build>`.
Additionally, you can use your favorite package manager to install the |kitty|
package, but note that some Linux distribution packages are woefully outdated.
|kitty| is available in a vast number of package repositories for macOS
and Linux.
.. image:: https://repology.org/badge/tiny-repos/kitty.svg
:target: https://repology.org/project/kitty/versions
:alt: Number of repositories kitty is available in
See :doc:`Configuring kitty <conf>` for help on configuring |kitty| and
:doc:`Invocation <invocation>` for the command line arguments |kitty| supports.
Design philosophy
-------------------
|kitty| is designed for power keyboard users. To that end all its controls
work with the keyboard (although it fully supports mouse interactions as
well). Its configuration is a simple, human editable, single file for
easy reproducibility (I like to store configuration in source control).
The code in |kitty| is designed to be simple, modular and hackable. It is
written in a mix of C (for performance sensitive parts) and Python (for
easy hackability of the UI). It does not depend on any large and complex
UI toolkit, using only OpenGL for rendering everything.
Finally, |kitty| is designed from the ground up to support all modern
terminal features, such as unicode, true color, bold/italic fonts, text
formatting, etc. It even extends existing text formatting escape codes,
to add support for features not available elsewhere, such as colored and
styled (curly) underlines. One of the design goals of |kitty| is to be
easily extensible so that new features can be added in the future with
relatively little effort.
.. include:: basic.rst
.. _layouts:
Layouts
----------
A layout is an arrangement of multiple kitty *windows* inside a top-level OS window. You can create a new window
using the :sc:`new_window` key combination.
Currently, there are seven layouts available:
* **Fat** -- One (or optionally more) windows are shown full width on the top, the rest of the windows are shown side-by-side on the bottom
* **Grid** -- All windows are shown in a grid
* **Horizontal** -- All windows are shown side-by-side
* **Splits** -- Windows arranged in arbitrary patterns created using horizontal and vertical splits
* **Stack** -- Only a single maximized window is shown at a time
* **Tall** -- One (or optionally more) windows are shown full height on the left, the rest of the windows are shown one below the other on the right
* **Vertical** -- All windows are shown one below the other
By default, all layouts are enabled and you can switch between layouts using
the :sc:`next_layout` key combination. You can also create shortcuts to select
particular layouts, and choose which layouts you want to enable/disable, see
:ref:`conf-kitty-shortcuts.layout` for examples. The first layout listed in
:opt:`enabled_layouts` becomes the default layout.
For more details on the layouts and how to use them see :doc:`layouts`.
.. _kittens:
Kittens
------------------
|kitty| has a framework for easily creating terminal programs that make use of
its advanced features. These programs are called kittens. They are used both
to add features to |kitty| itself and to create useful standalone programs.
Some prominent kittens:
:doc:`icat <kittens/icat>`
Display images in the terminal
:doc:`diff <kittens/diff>`
A fast, side-by-side diff for the terminal with syntax highlighting and
images
:doc:`Unicode Input <kittens/unicode-input>`
Easily input arbitrary unicode characters in |kitty| by name or hex code.
:doc:`Hints <kittens/hints>`
Select and open/paste/insert arbitrary text snippets such as URLs,
filenames, words, lines, etc. from the terminal screen.
:doc:`Remote file <kittens/remote_file>`
Edit, open, or download remote files over SSH easily, by simply clicking on
the filename.
:doc:`Hyperlinked grep <kittens/hyperlinked_grep>`
Search your files using `ripgrep <https://github.com/BurntSushi/ripgrep>`_
and open the results directly in your favorite editor in the terminal,
at the line containing the search result, simply by clicking on the result you want.
:doc:`Broadcast <kittens/broadcast>`
Type in one kitty window and have it broadcast to all (or a subset) of
other kitty windows.
:doc:`Panel <kittens/panel>`
Draw a GPU accelerated dock panel on your desktop showing the output
from an arbitrary terminal program.
:doc:`Clipboard <kittens/clipboard>`
Copy/paste to the clipboard from shell scripts, even over SSH.
You can also :doc:`Learn to create your own kittens <kittens/custom>`.
Configuring kitty
-------------------
|kitty| is highly configurable, everything from keyboard shortcuts to
painting frames-per-second. Press :sc:`edit_config_file` in kitty
to open its fully commented sample config file in your text editor.
For details see the :doc:`configuration docs <conf>`.
Remote control
------------------
|kitty| has a very powerful system that allows you to control it from the
:doc:`shell prompt, even over SSH <remote-control>`. You can change colors,
fonts, open new windows, tabs, set their titles, change window layout, get text
from one window and send text to another, etc, etc. The possibilities are
endless. See the :doc:`tutorial <remote-control>` to get started.
.. _sessions:
Startup Sessions
------------------
You can control the tabs, window layout, working directory, startup programs,
etc. by creating a "session" file and using the :option:`kitty --session`
command line flag or the :opt:`startup_session` option in :file:`kitty.conf`.
For example:
.. code-block:: session
# Set the window layout for the current tab
layout tall
# Set the working directory for windows in the current tab
cd ~
# Create a window and run the specified command in it
launch zsh
# Create a window with some environment variables set and run
# vim in it
launch --env FOO=BAR vim
# Set the title for the next window
launch --title "Chat with x" irssi --profile x
# Create a new tab (the part after new_tab is the optional tab
# name which will be displayed in the tab bar, if omitted, the
# title of the active window will be used instead)
new_tab my tab
cd ~/somewhere
# Set the layouts allowed in this tab
enabled_layouts tall, stack
# Set the current layout
layout stack
launch zsh
# Create a new OS window
new_os_window
# set new window size to 80x25 cells
os_window_size 80c 25c
# set the --class for the new OS window
os_window_class mywindow
launch sh
# Make the current window the active (focused) window
focus
launch emacs
.. note::
The :doc:`launch <launch>` command when used in a session file
cannot create new OS windows, or tabs.
Mouse features
-------------------
* You can click on a URL to open it in a browser.
* You can double click to select a word and then drag to select more words.
* You can triple click to select a line and then drag to select more lines.
* You can triple click while holding :kbd:`ctrl+alt` to select from clicked
point to end of line.
* You can right click to extend a previous selection.
* You can hold down :kbd:`ctrl+alt` and drag with the mouse to select in
columns.
* Selecting text automatically copies it to the primary clipboard (on
platforms with a primary clipboard).
* You can middle click to paste from the primary clipboard (on platforms
with a primary clipboard).
* You can select text with kitty even when a terminal program has grabbed
the mouse by holding down the :kbd:`shift` key.
All these actions can be customized in :file:`kitty.conf` as described
:ref:`here <conf-kitty-mouse.mousemap>`.
Font control
-----------------
|kitty| has extremely flexible and powerful font selection features. You can
specify individual families for the regular, bold, italic and bold+italic
fonts. You can even specify specific font families for specific ranges of
unicode characters. This allows precise control over text rendering. It can
come in handy for applications like powerline, without the need to use patched
fonts. See the various font related configuration directives in
:ref:`conf-kitty-fonts`.
.. _scrollback:
The scrollback buffer
-----------------------
|kitty| supports scrolling back to view history, just like most terminals. You
can use either keyboard shortcuts or the mouse scroll wheel to do so. However,
|kitty| has an extra, neat feature. Sometimes you need to explore the
scrollback buffer in more detail, maybe search for some text or refer to it
side-by-side while typing in a follow-up command. |kitty| allows you to do this
by pressing the :sc:`show_scrollback` key-combination, which will open the
scrollback buffer in your favorite pager program (which is ``less`` by default).
Colors and text formatting are preserved. You can explore the scrollback buffer
comfortably within the pager.
Additionally, you can pipe the contents of the scrollback buffer to an
arbitrary, command running in a new window, tab or overlay, for example::
map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R
Would open the scrollback buffer in a new window when you press the :kbd:`F1`
key. See :sc:`show_scrollback` for details.
If you want to use it with an editor such as vim to get more powerful features,
you can see tips for doing so, in
`this thread <https://github.com/kovidgoyal/kitty/issues/719>`_.
If you wish to store very large amounts of scrollback to view using the piping or
:sc:`show_scrollback` features, you can use the :opt:`scrollback_pager_history_size`
option.
.. _cpbuf:
Multiple copy/paste buffers
-----------------------------
In addition to being able to copy/paste from the system clipboard, in |kitty| you
can also setup an arbitrary number of copy paste buffers. To do so, simply add
something like the following to your :file:`kitty.conf`::
map f1 copy_to_buffer a
map f2 paste_from_buffer a
This will allow you to press :kbd:`F1` to copy the current selection to an
internal buffer named ``a`` and :kbd:`F2` to paste from that buffer. The buffer
names are arbitrary strings, so you can define as many such buffers as you
need.
Marks
-------------
kitty has the ability to mark text on the screen based on regular expressions.
This can be useful to highlight words or phrases when browsing output from long
running programs or similar. To learn how this feature works, see :doc:`marks`.
Frequently Asked Questions
---------------------------------
The list of Frequently Asked Questions (*FAQ*) is :doc:`available here <faq>`.
.. _completion:
Cool integrations for kitty with other CLI tools
--------------------------------------------------
kitty provides extremely powerful interfaces such as :doc:`remote-control` and
:doc:`kittens/custom` and :doc:`kittens/icat`
that allow it to be integrated with other tools seamlessly. For a list of such
user created integrations, see: :doc:`integrations`.
Completion for kitty
---------------------------------
|kitty| comes with completion for the ``kitty`` command for popular shells.
bash
~~~~~~~~
Add the following to your :file:`~/.bashrc`
.. code-block:: sh
source <(kitty + complete setup bash)
Older versions of bash (for example, v3.2) do not support
process substitution with the source command, in which
case you can try an alternative:
.. code-block:: sh
source /dev/stdin <<<"$(kitty + complete setup bash)"
zsh
~~~~~~~~~
Add the following to your :file:`~/.zshrc`
.. code-block:: sh
autoload -Uz compinit
compinit
# Completion for kitty
kitty + complete setup zsh | source /dev/stdin
The important thing above is to make sure the call to |kitty| to load the zsh
completions happens after the call to :file:`compinit`.
fish
~~~~~~~~
For versions of fish earlier than 3.0.0, add the following to your
:file:`~/.config/fish/config.fish`. Later versions source completions by default.
.. code-block:: sh
kitty + complete setup fish | source
Changelog
------------------
See :doc:`changelog`.
.. toctree::
:hidden:
:glob:
*
kittens/*
generated/rc
To get started see :doc:`quickstart`.

View File

@@ -1,3 +1,5 @@
:tocdepth: 2
Integrations with other tools
================================
@@ -12,149 +14,245 @@ Image and document viewers
Powered by kitty's :doc:`graphics-protocol` there exist many tools for viewing
images and other types of documents directly in your terminal, even over SSH.
.. _tool_termpdf:
`termpdf.py <https://github.com/dsanson/termpdf.py>`_
a terminal PDF/DJVU/CBR viewer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A terminal PDF/DJVU/CBR viewer
.. _tool_mdcat:
`mdcat <https://github.com/lunaryorn/mdcat>`_
Display markdown files nicely formatted with images in the terminal
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Display markdown files nicely formatted with images in the terminal
.. _tool_ranger:
`ranger <https://github.com/ranger/ranger>`_
a terminal file manager, with previews of file contents powered by kitty's graphics protocol.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A terminal file manager, with previews of file contents powered by kitty's graphics protocol.
.. _tool_nnn:
`nnn <https://github.com/jarun/nnn/>`_
another terminal file manager, with previews of file contents powered by kitty's graphics protocol.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Another terminal file manager, with previews of file contents powered by kitty's graphics protocol.
.. _tool_hunter:
`hunter <https://github.com/rabite0/hunter>`_
another terminal file manager, with previews of file contents powered by kitty's graphics protocol.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Another terminal file manager, with previews of file contents powered by kitty's graphics protocol.
.. _tool_koneko:
`koneko <https://github.com/twenty5151/koneko>`_
browse images from the pixiv artist community directly in kitty.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Browse images from the pixiv artist community directly in kitty.
.. _tool_viu:
`viu <https://github.com/atanunq/viu>`_
view images in the terminal, similar to kitty's icat.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
View images in the terminal, similar to kitty's icat.
.. _tool_nb:
`nb <https://github.com/xwmx/nb>`_
command line and local web note-taking, bookmarking, archiving, and
knowledge base application that uses kitty's graphics protocol for images.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
command line and local web note-taking, bookmarking, archiving, and
knowledge base application that uses kitty's graphics protocol for images.
.. _tool_w3m:
`w3m <https://github.com/tats/w3m>`_
A text mode WWW browser that supports kitty's graphics protocol to display
images.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A text mode WWW browser that supports kitty's graphics protocol to display
images.
.. _tool_timg:
`timg <https://github.com/hzeller/timg>`_
A terminal image and video viewer, that displays static and animated
images or plays videos. Fast multi-threaded loading, JPEG exif rotation,
grid view and connecting to the webcam make it a versatile terminal utility.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A terminal image and video viewer, that displays static and animated
images or plays videos. Fast multi-threaded loading, JPEG exif rotation,
grid view and connecting to the webcam make it a versatile terminal utility.
System and data visualisation tools
---------------------------------------
.. _tool_neofetch:
`neofetch <https://github.com/dylanaraps/neofetch>`_
A command line system information tool that shows images using kitty's graphics protocol
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A command line system information tool that shows images using kitty's graphics protocol
.. _tool_matplotlib:
`matplotlib <https://github.com/jktr/matplotlib-backend-kitty>`_
show matplotlib plots directly in kitty
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Show matplotlib plots directly in kitty
.. _tool_KittyTerminalImage:
`KittyTerminalImages.jl <https://github.com/simonschoelly/KittyTerminalImages.jl>`_
show images from Julia directly in kitty
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Show images from Julia directly in kitty
.. _tool_euporie:
`euporie <https://github.com/joouha/euporie>`_
a text-based user interface for running and editing Jupyter notebooks,
powered by kitty's graphics protocol for displaying plots
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A text-based user interface for running and editing Jupyter notebooks,
powered by kitty's graphics protocol for displaying plots
.. _tool_gnuplot:
`gnuplot <http://www.gnuplot.info/>`_
a graphing and data visualization tool that can be made to display its
output in kitty with the following bash snippet::
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function iplot {
cat <<EOF | gnuplot
set terminal pngcairo enhanced font 'Fira Sans,10'
set autoscale
set samples 1000
set output '|kitty +kitten icat --stdin yes'
set object 1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb"#fdf6e3" behind
plot $@
set output '/dev/null'
EOF
}
A graphing and data visualization tool that can be made to display its
output in kitty with the following bash snippet:
Add this to bashrc and then to plot a function, simply do::
.. code-block:: sh
iplot 'sin(x*3)*exp(x*.2)'
function iplot {
cat <<EOF | gnuplot
set terminal pngcairo enhanced font 'Fira Sans,10'
set autoscale
set samples 1000
set output '|kitty +kitten icat --stdin yes'
set object 1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb"#fdf6e3" behind
plot $@
set output '/dev/null'
EOF
}
Add this to bashrc and then to plot a function, simply do:
.. code-block:: sh
iplot 'sin(x*3)*exp(x*.2)'
.. tool_onefetch:
`onefetch <https://github.com/o2sh/onefetch>`_
a tool to fetch information about your git repositories
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A tool to fetch information about your git repositories
.. tool_patat:
`patat <https://github.com/jaspervdj/patat>`_
terminal based presentations using pandoc and kitty's image protocol for
images
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Terminal based presentations using pandoc and kitty's image protocol for
images
.. tool_wttr:
`wttr.in <https://github.com/chubin/wttr.in>`_
a tool to display weather information in your terminal with curl
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A tool to display weather information in your terminal with curl
.. tool_wl_clipboard:
`wl-clipboard-manager <https://github.com/maximbaz/wl-clipboard-manager>`_
view and manage the system clipboard under Wayland in your kitty terminal
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
View and manage the system clipboard under Wayland in your kitty terminal
.. tool_dmenu_term:
`dmenu-term <https://github.com/maximbaz/dmenu-term>`_
run applications on your system with fuzzy find inside a kitty window
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run applications on your system with fuzzy find inside a kitty window
Editor integration
-----------------------
kitty can be integrated into many different terminal editors to add features
|kitty| can be integrated into many different terminal editors to add features
such a split windows, previews, REPLs etc.
.. tool_kakoune:
`kakoune <https://kakoune.org/>`_
integrates with kitty to use native kitty windows for its windows/panels and REPLs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
integrates with kitty to use native kitty windows for its windows/panels and REPLs.
.. tool_vim_slime:
`vim-slime <https://github.com/jpalardy/vim-slime#kitty>`_
uses kitty remote control for a Lisp REPL.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
uses kitty remote control for a Lisp REPL.
.. tool_vim_kitty_navigator:
`vim-kitty-navigator <https://github.com/knubie/vim-kitty-navigator>`_
allows you to navigate seamlessly between vim and kitty splits using a consistent set of hotkeys.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
allows you to navigate seamlessly between vim and kitty splits using a consistent set of hotkeys.
.. tool_vim_test:
`vim-test <https://github.com/vim-test/vim-test>`_
allows easily running tests in a terminal window
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Allows easily running tests in a terminal window
.. tool_hologram:
`hologram.nvim <https://github.com/edluffy/hologram.nvim>`_
terminal image viewer for nvim
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Terminal image viewer for nvim
Scrollback manipulation
-------------------------
.. tool_kitty_search:
`kitty-search <https://github.com/trygveaa/kitty-kitten-search>`_
Live incremental search of the scrollback buffer.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Live incremental search of the scrollback buffer.
.. tool_kitty_grab:
`kitty-grab <https://github.com/yurikhan/kitty_grab>`_
keyboard based text selection for the kitty scrollback buffer.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Keyboard based text selection for the kitty scrollback buffer.
Miscellaneous
------------------
.. tool_kitty_smart_tab:
`kitty-smart-tab <https://github.com/yurikhan/kitty-smart-tab>`_
use keys to either control tabs or pass them onto running applications if
no tabs are present
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
use keys to either control tabs or pass them onto running applications if
no tabs are present
.. tool_kitty_smart_scroll:
`kitty-smart-scroll <https://github.com/yurikhan/kitty-smart-scroll>`_
use keys to either scroll or pass them onto running applications if
no scrollback buffer is present
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
use keys to either scroll or pass them onto running applications if
no scrollback buffer is present
`reload keybindings <https://github.com/kovidgoyal/kitty/issues/1292#issuecomment-582388769>`_
reload key bindings from :file:`kitty.conf` without needing to restart
kitty
.. tool_kitti3:
`kitti3 <https://github.com/LandingEllipse/kitti3>`_
allow using kitty as a drop-down terminal under the i3 window manager
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
allow using kitty as a drop-down terminal under the i3 window manager
.. tool_weechat_hints:
`weechat-hints <https://github.com/GermainZ/kitty-weechat-hints>`_
URL hints kitten for WeeChat that works without having to use WeeChat's
raw-mode.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
URL hints kitten for WeeChat that works without having to use WeeChat's
raw-mode.
.. tool_glkitty:
`glkitty <https://github.com/michaeljclark/glkitty>`_
C library to draw OpenGL shaders in the terminal with a glgears demo
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
C library to draw OpenGL shaders in the terminal with a glgears demo

View File

@@ -1,3 +1,5 @@
:orphan:
The kitty command line interface
====================================

View File

@@ -1,5 +1,5 @@
A protocol for comprehensive keyboard handling in terminals
=================================================================
Comprehensive keyboard handling in terminals
==============================================
There are various problems with the current state of keyboard handling in
terminals. They include:
@@ -41,12 +41,14 @@ If you are an application or library developer just interested in using this
protocol to make keyboard handling simpler and more robust in your application,
without too many changes, do the following:
#. Emit the escape code ``CSI > 1 u`` at application startup or when entering
alternate screen mode
#. Emit the escape code ``CSI > 1 u`` at application startup if using the main
screen or when entering alternate screen mode, if using the alternate
screen.
#. All key events will now be sent in only a few forms to your application,
that are easy to parse unambiguously.
#. Emit the escape sequence ``CSI < u`` at application exit or just before
leaving alternate screen mode to restore the previously used keyboard mode.
#. Emit the escape sequence ``CSI < u`` at application exit if using the main
screen or just before leaving alternate screen mode if using the alternate screen,
to restore the previously used keyboard mode.
Key events will all be delivered to your application either as plain UTF-8
text, or using the following escape codes, for those keys that do not produce
@@ -266,6 +268,15 @@ and alternate screens. If a pop request is received that empties the stack,
all flags are reset. If a push request is received and the stack is full, the
oldest entry from the stack must be evicted.
.. note:: The main and alternate screens in the terminal emulator must maintain
their own, independent, keyboard mode stacks. This is so that a program that
uses the alternate screen such as an editor, can change the keyboard mode
in the alternate screen only, without affecting the mode in the main screen
or even knowing what that mode is. Without this, and if no stack is
implemented for keyboard modes (such as in some legacy terminal emulators)
the editor would have to somehow know what the keyboard mode of the main
screen is and restore to that mode on exit.
.. note:: In the interests of interoperation, the XTerm specific sequences
`CSI > 4; 1 m` and `CSI > 4; 0 m` are treated as `CSI > 1 u` and `CSI < 1 u`.
These codes cause XTerm to use the CSI u encoding for more keys and are therefore

View File

@@ -1,6 +1,8 @@
broadcast - type text in all kitty windows
broadcast
==================================================
*Type text in all kitty windows simultaneously*
The ``broadcast`` kitten can be used to type text simultaneously in
all kitty windows (or a subset as desired).
@@ -17,7 +19,4 @@ are selected.
.. program:: kitty +kitten broadcast
Command Line Interface
--------------------------
.. include:: /generated/cli-kitten-broadcast.rst

View File

@@ -1,6 +1,8 @@
clipboard - copy/paste to the system clipboard
clipboard
==================================================
*Copy/paste to the system clipboard from shell scripts*
.. highlight:: sh
@@ -21,7 +23,4 @@ use::
.. program:: kitty +kitten clipboard
Command Line Interface
--------------------------
.. include:: /generated/cli-kitten-clipboard.rst

View File

@@ -103,7 +103,8 @@ terminal program, you can tell the kittens system to run the
``handle_result()`` function without first running the ``main()`` function.
For example, here is a kitten that "zooms/unzooms" the current terminal window
by switching to the stack layout or back to the previous layout.
by switching to the stack layout or back to the previous layout. This is
equivalent to the builtin :ref:`action-toggle_layout` action.
Create a file in the kitty config folder, :file:`~/.config/kitty/zoom_toggle.py`
@@ -185,6 +186,104 @@ The output of print statements will go to the ``STDOUT`` of the kitty process.
So if you run kitty from another kitty instance, the output will be visible
in the first kitty instance.
Adding options to kittens
----------------------------
If you would like to use kitty's config framework to make your kittens
configurable, you will need some boilerplate. In the directory
of your kitten make the following files.
:file:`kitten_options_definition.py`
.. code-block:: python
from kitty.conf.types import Action, Definition
definition = Definition(
'!kitten_options_utils',
Action(
'map', 'parse_map',
{'key_definitions': 'kitty.conf.utils.KittensKeyMap'},
['kitty.types.ParsedShortcut', 'kitty.conf.utils.KeyAction']
),
)
agr = definition.add_group
egr = definition.end_group
opt = definition.add_option
map = definition.add_map
# main options {{{
agr('main', 'Main')
opt('some_option', '33',
option_type='some_option_parser',
long_text='''
Help text for this option
'''
)
egr() # }}}
# shortcuts {{{
agr('shortcuts', 'Keyboard shortcuts')
map('Quit', 'quit q quit')
egr() # }}}
:file:`kitten_options_utils.py`
.. code-block:: python
from kitty.conf.utils import KittensKeyDefinition, key_func, parse_kittens_key
func_with_args, args_funcs = key_func()
FuncArgsType = Tuple[str, Sequence[Any]]
def some_option_parser(val: str) -> int:
return int(val) + 3000
def parse_map(val: str) -> Iterable[KittensKeyDefinition]:
x = parse_kittens_key(val, args_funcs)
if x is not None:
yield x
Then run::
kitty +runpy 'from kitty.conf.generate import main; main()' /path/to/kitten_options_definition.py
You can parse and read the options in your kitten using the following code:
.. code-block:: python
from .kitten_options_types import Options, defaults
from kitty.conf.utils import load_config as _load_config, parse_config_base
from typing import Optional, Iterable, Dict, Any
def load_config(*paths: str, overrides: Optional[Iterable[str]] = None) -> Options:
from .kitten_options_parse import (
create_result_dict, merge_result_dicts, parse_conf_item
)
def parse_config(lines: Iterable[str]) -> Dict[str, Any]:
ans: Dict[str, Any] = create_result_dict()
parse_config_base(
lines,
parse_conf_item,
ans,
)
return ans
overrides = tuple(overrides) if overrides is not None else ()
opts_dict, paths = _load_config(defaults, parse_config, merge_result_dicts, *paths, overrides=overrides)
opts = Options(opts_dict)
opts.config_paths = paths
opts.config_overrides = overrides
return opts
See the code for the builtin diff kitten for examples of creating more options
and keyboard shortcuts.
.. _external_kittens:
Kittens created by kitty users

View File

@@ -1,6 +1,8 @@
kitty-diff - A fast side-by-side diff tool with syntax highlighting and images
kitty-diff
================================================================================
*A fast side-by-side diff tool with syntax highlighting and images*
.. highlight:: sh
Major Features
@@ -21,13 +23,10 @@ Major Features
.. figure:: ../screenshots/diff.png
:alt: Screenshot, showing a sample diff
:align: center
:scale: 100%
:width: 100%
Screenshot, showing a sample diff
.. contents::
:local:
Installation
---------------
@@ -35,7 +34,7 @@ Installation
Simply :ref:`install kitty <quickstart>`. You also need
to have either the `git <https://git-scm.com/>`_ program or the ``diff`` program
installed. Additionally, for syntax highlighting to work,
`pygments <http://pygments.org/>`_ must be installed (note that pygments is
`pygments <https://pygments.org/>`_ must be installed (note that pygments is
included in the macOS kitty app).
@@ -121,8 +120,8 @@ Why does this work only in kitty?
The diff kitten makes use of various features that are :doc:`kitty only
</protocol-extensions>`, such as the :doc:`kitty graphics protocol
</graphics-protocol>`, the :ref:`extended keyboard protocol
<extended-key-protocol>`, etc. It also leverages terminal program
</graphics-protocol>`, the :doc:`extended keyboard protocol
</keyboard-protocol>`, etc. It also leverages terminal program
infrastructure I created for all of kitty's other kittens to reduce the amount
of code needed (the entire implementation is under 2000 lines of code).
@@ -143,9 +142,6 @@ configuration directives.
.. include:: /generated/conf-kitten-diff.rst
Command Line Interface
-------------------------
.. include:: /generated/cli-kitten-diff.rst

View File

@@ -9,7 +9,7 @@ browser.
.. figure:: ../screenshots/hints_mode.png
:alt: URL hints mode
:align: center
:scale: 100%
:width: 100%
URL hints mode
@@ -88,8 +88,12 @@ Now run kitty with::
When you press the :kbd:`F1` key you will be able to select a word to
look it up in the Google dictionary.
Command Line Interface
-------------------------
.. include:: ../generated/cli-kitten-hints.rst
.. note::
To avoid having to specify the same command line options on every invocation,
you can use the :opt:`kitten_alias` option in :file:`kitty.conf`, creating aliases
that have common sets of options. For example::
kitten_alias myhints hints --alphabet qfjdkslaureitywovmcxzpq1234567890

View File

@@ -58,7 +58,7 @@ Then, for example, for ZSH, add the following to :file:`.zshrc`::
compdef _rg hg
To learn more about kitty's powerful framework for customizing URL click
actions, :doc:`see here <../open_actions>`.
actions, :doc:`see here </open_actions>`.
Hopefully, someday this functionality will make it into some `upstream grep
<https://github.com/BurntSushi/ripgrep/issues/665>`_

View File

@@ -1,6 +1,8 @@
icat - Display images in the terminal
icat
========================================
*Display images in the terminal*
The ``icat`` kitten can be used to display arbitrary images in the |kitty|
terminal. Using it is as simple as::
@@ -35,7 +37,4 @@ The ``icat`` kitten has various command line arguments to allow it to be used
from inside other programs to display images. In particular, :option:`--place`,
:option:`--detect-support` and :option:`--print-window-size`.
Command Line Interface
--------------------------
.. include:: /generated/cli-kitten-icat.rst

View File

@@ -14,7 +14,7 @@ using terminal programs instead of GUI toolkits.
.. figure:: ../screenshots/panel.png
:alt: Screenshot, showing a sample panel
:align: center
:scale: 100%
:width: 100%
Screenshot, showing a sample panel
@@ -37,7 +37,4 @@ print out ``Hello, world!``. You can make the terminal program as complex as
you like, as demonstrated in the screenshot above.
Command Line Interface
-------------------------
.. include:: ../generated/cli-kitten-panel.rst

View File

@@ -15,7 +15,4 @@ for *XTGETTCAP* to see the syntax for the escape code and read the source
of this kitten to find the values of the keys for the various queries.
Command Line Interface
-------------------------
.. include:: ../generated/cli-kitten-query_terminal.rst

View File

@@ -11,15 +11,16 @@ Then hold down :kbd:`ctrl+shift` and click the name of the file.
.. figure:: ../screenshots/remote_file.png
:alt: Remote file actions
:align: center
:scale: 100%
:width: 100%
Remote file actions
|kitty| will ask you what you want to do with the remote file. You can choose
to *Edit* it in which case kitty will download it and open it locally in your
``EDITOR``. As you make changes to the file, they are automatically transferred
to the remote computer. Note that this happens without needing to install *any*
special software on the server, beyond ``ls`` that supports hyperlinks.
:envvar:`EDITOR`. As you make changes to the file, they are automatically
transferred to the remote computer. Note that this happens without needing
to install *any* special software on the server, beyond ``ls`` that supports
hyperlinks.
.. versionadded:: 0.19.0

66
docs/kittens/themes.rst Normal file
View File

@@ -0,0 +1,66 @@
Changing kitty colors
========================
The themes kitten allows you to easily change color themes, from a collection
of almost two hundred pre-built themes available at `kitty-themes
<https://github.com/kovidgoyal/kitty-themes>`_. To use it, simply run::
kitty +kitten themes
The kitten allows you to pick a theme, with live previews of the colors. You
can choose between light and dark themes and search by theme name by just
typing a few characters from the name.
The kitten maintains a list of recently used themes to allow quick switching.
If you want to restore the colors to default, you can do so by choosing the
``Default`` theme.
.. versionadded:: 0.23.0
The themes kitten
How it works
----------------
A theme in kitty is just a :file:`.conf` file containing kitty settings.
When you select a theme, the kitten simply copies the :file:`.conf` file
to :file:`~/.config/kitty/current-theme.conf` and adds an include for
:file:`current-theme.conf` to :file:`kitty.conf`. It also comments out
any existing color settings in :file:`kitty.conf` so they do not interfere.
Once that's done, the kitten sends kitty a signal to make it reload its config.
Using your own themes
-----------------------
You can also create your own themes as :file:`.conf` files. Put them in the
:file:`themes` sub-directory of the kitty config directory, usually,
:file:`~/.config/kitty/themes` and the kitten will automatically add them to
the list of themes. You can use this to modify the builtin themes, by giving
the conf file the name :file:`Some theme name.conf` to override the builtin
theme of that name. Note that after doing so you have to run the kitten and
choose that theme once for your changes to be applied.
Contributing new themes
-------------------------
If you wish to contribute a new theme to the kitty theme repository, simply
go to `kitty-themes <https://github.com/kovidgoyal/kitty-themes>`_ and open a pull request
asking to add your contributions to the repository. Use the file
:download:`template.conf <https://github.com/kovidgoyal/kitty-themes/raw/master/template.conf>` as
a template when creating your theme.
Changing the theme non-interactively
---------------------------------------
You can specify the theme name as an argument when invoking the kitten
to have it change to that theme instantly. For example::
kitty +kitten theme --reload-in=all Dimmed Monokai
Will change the theme to ``Dimmed Monokai`` in all running kitty
instances. See below for more details on non-interactive operation.
.. include:: ../generated/cli-kitten-themes.rst

View File

@@ -7,7 +7,7 @@ Press :sc:`input_unicode_character` to start the unicode input widget, shown bel
.. figure:: ../screenshots/unicode.png
:alt: A screenshot of the unicode input widget
:align: center
:scale: 100%
:width: 100%
A screenshot of the unicode input widget
@@ -28,7 +28,4 @@ You can switch between modes using either the function keys or by pressing
:kbd:`Ctrl+Shift+Tab`.
Command Line Interface
-------------------------
.. include:: ../generated/cli-kitten-unicode_input.rst

67
docs/kittens_intro.rst Normal file
View File

@@ -0,0 +1,67 @@
.. _kittens:
Extend with kittens
-----------------------
.. toctree::
:hidden:
:glob:
kittens/icat
kittens/diff
kittens/unicode-input
kittens/themes
kittens/hints
kittens/remote_file
kittens/hyperlinked_grep
kittens/custom
kittens/*
|kitty| has a framework for easily creating terminal programs that make use of
its advanced features. These programs are called kittens. They are used both
to add features to |kitty| itself and to create useful standalone programs.
Some prominent kittens:
:doc:`icat <kittens/icat>`
Display images in the terminal
:doc:`diff <kittens/diff>`
A fast, side-by-side diff for the terminal with syntax highlighting and
images
:doc:`Unicode Input <kittens/unicode-input>`
Easily input arbitrary unicode characters in |kitty| by name or hex code.
:doc:`Hints <kittens/hints>`
Select and open/paste/insert arbitrary text snippets such as URLs,
filenames, words, lines, etc. from the terminal screen.
:doc:`Remote file <kittens/remote_file>`
Edit, open, or download remote files over SSH easily, by simply clicking on
the filename.
:doc:`Hyperlinked grep <kittens/hyperlinked_grep>`
Search your files using `ripgrep <https://github.com/BurntSushi/ripgrep>`_
and open the results directly in your favorite editor in the terminal,
at the line containing the search result, simply by clicking on the result you want.
:doc:`Broadcast <kittens/broadcast>`
Type in one :term:`kitty window <window>` and have it broadcast to all (or a subset) of
other :term:`kitty windows <window>`.
:doc:`Panel <kittens/panel>`
Draw a GPU accelerated dock panel on your desktop showing the output
from an arbitrary terminal program.
:doc:`Clipboard <kittens/clipboard>`
Copy/paste to the clipboard from shell scripts, even over SSH.
You can also :doc:`Learn to create your own kittens <kittens/custom>`.

View File

@@ -1,5 +1,5 @@
Launching programs in new windows/tabs
========================================
The :command:`launch` command
--------------------------------
.. program:: launch
@@ -42,7 +42,7 @@ The piping environment
--------------------------
When using :option:`launch --stdin-source`, the program to which the data is
piped has a special environment variable declared, ``KITTY_PIPE_DATA`` whose
piped has a special environment variable declared, :envvar:`KITTY_PIPE_DATA` whose
contents are::
KITTY_PIPE_DATA={scrolled_by}:{cursor_x},{cursor_y}:{lines},{columns}

View File

@@ -1,5 +1,5 @@
Layouts
============
Arrange windows
-------------------
kitty has the ability to define its own windows that can be tiled next to each
other in arbitrary arrangements, based on *Layouts*, see below for examples:
@@ -8,7 +8,7 @@ other in arbitrary arrangements, based on *Layouts*, see below for examples:
.. figure:: screenshots/screenshot.png
:alt: Screenshot, showing three programs in the 'Tall' layout
:align: center
:scale: 100%
:width: 100%
Screenshot, showing vim, tig and git running in |kitty| with the 'Tall' layout
@@ -16,7 +16,7 @@ other in arbitrary arrangements, based on *Layouts*, see below for examples:
.. figure:: screenshots/splits.png
:alt: Screenshot, showing windows in the 'Splits' layout
:align: center
:scale: 100%
:width: 100%
Screenshot, showing windows with arbitrary arrangement in the 'Splits'
layout
@@ -27,9 +27,6 @@ you can switch layouts using :sc:`next_layout`. To control which layouts
are available use :opt:`enabled_layouts`, the first listed layout becomes
the default. Individual layouts and how to use them are described below.
.. contents::
:local:
The Stack Layout
------------------

View File

@@ -1,11 +1,14 @@
Marks
=================
Mark text on screen
---------------------
kitty has the ability to mark text on the screen based on regular expressions.
This can be useful to highlight words or phrases when browsing output from long
running programs or similar. Lets start with a few examples:
Examples
----------
Suppose we want to be able to highlight the word ERROR in the current window.
Add the following to :file:`kitty.conf`::
@@ -89,12 +92,11 @@ The syntax of the :code:`toggle_marker` command is::
Here :code:`marker-type` is one of:
* :code:`text` - simple substring matching
* :code:`itext` - case-insensitive substring matching
* :code:`regex` - A python regular expression
* :code:`iregex` - A case-insensitive python regular expression
* :code:`function` - An arbitrary function defined in a python file, see
:ref:`marker_funcs`.
* :code:`text` - simple substring matching
* :code:`itext` - case-insensitive substring matching
* :code:`regex` - A python regular expression
* :code:`iregex` - A case-insensitive python regular expression
* :code:`function` - An arbitrary function defined in a python file, see :ref:`marker_funcs`.
.. _marker_funcs:

View File

@@ -1,10 +1,11 @@
Customizing the actions taken when clicking on links
Scripting the mouse click
======================================================
|kitty| has support for `terminal hyperlinks <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>`_. These
|kitty| has support for `terminal hyperlinks
<https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>`_. These
are generated by many terminal programs, such as ``ls``, ``gcc``, ``systemd``,
``mdcat``, etc. You can customize exactly what happens when clicking on these hyperlinks
in |kitty|.
:ref:`tool_mdcat`, etc. You can customize exactly what happens when clicking on these
hyperlinks in |kitty|.
You can tell kitty to take arbitrarily many, complex actions
when a link is clicked. Let us illustrate with some examples, first. Create
@@ -85,7 +86,7 @@ lines. The various available criteria are:
:file:`mime.types` in the kitty configuration directory. Useful if your
system MIME database does not have definitions you need. This file is
in the standard format of one definition per line, like: ``text/plain rst
md``.
md``. Note that the MIME type for directories is ``inode/directory``.
``ext``
A comma separated list of file extensions, for example: ``jpeg, tar.gz``

283
docs/overview.rst Normal file
View File

@@ -0,0 +1,283 @@
Overview
==============
Design philosophy
-------------------
|kitty| is designed for power keyboard users. To that end all its controls
work with the keyboard (although it fully supports mouse interactions as
well). Its configuration is a simple, human editable, single file for
easy reproducibility (I like to store configuration in source control).
The code in |kitty| is designed to be simple, modular and hackable. It is
written in a mix of C (for performance sensitive parts) and Python (for
easy hackability of the UI). It does not depend on any large and complex
UI toolkit, using only OpenGL for rendering everything.
Finally, |kitty| is designed from the ground up to support all modern
terminal features, such as unicode, true color, bold/italic fonts, text
formatting, etc. It even extends existing text formatting escape codes,
to add support for features not available elsewhere, such as colored and
styled (curly) underlines. One of the design goals of |kitty| is to be
easily extensible so that new features can be added in the future with
relatively little effort.
.. include:: basic.rst
Configuring kitty
-------------------
|kitty| is highly configurable, everything from keyboard shortcuts to
painting frames-per-second. Press :sc:`edit_config_file` in kitty
to open its fully commented sample config file in your text editor.
For details see the :doc:`configuration docs <conf>`.
.. toctree::
:hidden:
conf
.. _layouts:
Layouts
----------
A :term:`layout` is an arrangement of multiple :term:`kitty windows <window>`
inside a top-level :term:`OS window <os_window>`. The layout manages all its
windows automatically, resizing and moving them as needed. You can create a new
:term:`window` using the :sc:`new_window` key combination.
Currently, there are seven layouts available:
* **Fat** -- One (or optionally more) windows are shown full width on the top, the rest of the windows are shown side-by-side on the bottom
* **Grid** -- All windows are shown in a grid
* **Horizontal** -- All windows are shown side-by-side
* **Splits** -- Windows arranged in arbitrary patterns created using horizontal and vertical splits
* **Stack** -- Only a single maximized window is shown at a time
* **Tall** -- One (or optionally more) windows are shown full height on the left, the rest of the windows are shown one below the other on the right
* **Vertical** -- All windows are shown one below the other
By default, all layouts are enabled and you can switch between layouts using
the :sc:`next_layout` key combination. You can also create shortcuts to select
particular layouts, and choose which layouts you want to enable/disable, see
:ref:`conf-kitty-shortcuts.layout` for examples. The first layout listed in
:opt:`enabled_layouts` becomes the default layout.
For more details on the layouts and how to use them see :doc:`the documentation
<layouts>`.
.. toctree::
:hidden:
layouts
Extending kitty
------------------
kitty has a powerful framework for scripting. You can create small terminal
programs called :doc:`kittens <kittens_intro>`. These can used to add features
to kitty, for example, :doc:`editing remote files <kittens/remote_file>` or
:doc:`inputting unicode characters <kittens/unicode-input>`. They can also be
used to create programs that leverage kitty's powerful features, for example,
:doc:`viewing images <kittens/icat>` or :doc:`diffing files with images
<kittens/diff>`.
You can :doc:`create your own kittens to scratch your own itches
<kittens/custom>`.
For a list of all the builtin kittens, :ref:`see here <kittens>`.
.. toctree::
:hidden:
kittens_intro
Remote control
------------------
|kitty| has a very powerful system that allows you to control it from the
:doc:`shell prompt, even over SSH <remote-control>`. You can change colors,
fonts, open new :term:`windows <window>`, :term:`tabs <tab>`, set their titles,
change window layout, get text
from one window and send text to another, etc, etc. The possibilities are
endless. See the :doc:`tutorial <remote-control>` to get started.
.. toctree::
:hidden:
remote-control
.. _sessions:
Startup Sessions
------------------
You can control the :term:`tabs <tab>`, :term:`kitty window <window>` layout,
working directory, startup programs,
etc. by creating a "session" file and using the :option:`kitty --session`
command line flag or the :opt:`startup_session` option in :file:`kitty.conf`.
For example:
.. code-block:: session
# Set the layout for the current tab
layout tall
# Set the working directory for windows in the current tab
cd ~
# Create a window and run the specified command in it
launch zsh
# Create a window with some environment variables set and run
# vim in it
launch --env FOO=BAR vim
# Set the title for the next window
launch --title "Chat with x" irssi --profile x
# Create a new tab (the part after new_tab is the optional tab
# name which will be displayed in the tab bar, if omitted, the
# title of the active window will be used instead)
new_tab my tab
cd ~/somewhere
# Set the layouts allowed in this tab
enabled_layouts tall, stack
# Set the current layout
layout stack
launch zsh
# Create a new OS window
new_os_window
# set new window size to 80x25 cells
os_window_size 80c 25c
# set the --class for the new OS window
os_window_class mywindow
launch sh
# Make the current window the active (focused) window
focus
launch emacs
.. note::
The :doc:`launch <launch>` command when used in a session file
cannot create new OS windows, or tabs.
Creating tabs/windows
-------------------------------
kitty can be told to run arbitrary programs in new :term:`tabs <tab>`,
:term:`windows <window>` or :term:`overlays <overlay>` at a keypress.
To learn how to do this, see :doc:`here <launch>`.
.. toctree::
:hidden:
launch
Mouse features
-------------------
* You can click on a URL to open it in a browser.
* You can double click to select a word and then drag to select more words.
* You can triple click to select a line and then drag to select more lines.
* You can triple click while holding :kbd:`ctrl+alt` to select from clicked
point to end of line.
* You can right click to extend a previous selection.
* You can hold down :kbd:`ctrl+alt` and drag with the mouse to select in
columns.
* Selecting text automatically copies it to the primary clipboard (on
platforms with a primary clipboard).
* You can middle click to paste from the primary clipboard (on platforms
with a primary clipboard).
* You can select text with kitty even when a terminal program has grabbed
the mouse by holding down the :kbd:`shift` key.
All these actions can be customized in :file:`kitty.conf` as described
:ref:`here <conf-kitty-mouse.mousemap>`.
You can also customize what happens when clicking on :term:`hyperlinks` in kitty,
having it open files in your editor, download remote files, open things
in your browser, etc.
For details, see :doc:`here <open_actions>`.
.. toctree::
:hidden:
open_actions
Font control
-----------------
|kitty| has extremely flexible and powerful font selection features. You can
specify individual families for the regular, bold, italic and bold+italic
fonts. You can even specify specific font families for specific ranges of
unicode characters. This allows precise control over text rendering. It can
come in handy for applications like powerline, without the need to use patched
fonts. See the various font related configuration directives in
:ref:`conf-kitty-fonts`.
.. _scrollback:
The scrollback buffer
-----------------------
|kitty| supports scrolling back to view history, just like most terminals. You
can use either keyboard shortcuts or the mouse scroll wheel to do so. However,
|kitty| has an extra, neat feature. Sometimes you need to explore the
scrollback buffer in more detail, maybe search for some text or refer to it
side-by-side while typing in a follow-up command. |kitty| allows you to do this
by pressing the :sc:`show_scrollback` key-combination, which will open the
scrollback buffer in your favorite pager program (which is ``less`` by default).
Colors and text formatting are preserved. You can explore the scrollback buffer
comfortably within the pager.
Additionally, you can pipe the contents of the scrollback buffer to an
arbitrary, command running in a new :term:`window`, :term:`tab` or :term:`overlay`,
for example::
map f1 launch --stdin-source=@screen_scrollback --stdin-add-formatting less +G -R
Would open the scrollback buffer in a new :term:`window` when you press the :kbd:`F1`
key. See :sc:`show_scrollback` for details.
If you want to use it with an editor such as vim to get more powerful features,
you can see tips for doing so, in
`this thread <https://github.com/kovidgoyal/kitty/issues/719>`_.
If you wish to store very large amounts of scrollback to view using the piping or
:sc:`show_scrollback` features, you can use the :opt:`scrollback_pager_history_size`
option.
.. _cpbuf:
Multiple copy/paste buffers
-----------------------------
In addition to being able to copy/paste from the system clipboard, in |kitty| you
can also setup an arbitrary number of copy paste buffers. To do so, simply add
something like the following to your :file:`kitty.conf`::
map f1 copy_to_buffer a
map f2 paste_from_buffer a
This will allow you to press :kbd:`F1` to copy the current selection to an
internal buffer named ``a`` and :kbd:`F2` to paste from that buffer. The buffer
names are arbitrary strings, so you can define as many such buffers as you
need.
Marks
-------------
kitty has the ability to mark text on the screen based on regular expressions.
This can be useful to highlight words or phrases when browsing output from long
running programs or similar. To learn how this feature works, see :doc:`marks`.
.. toctree::
:hidden:
marks

View File

@@ -1,4 +1,4 @@
|kitty| Performance
Performance
===================
The main goals for |kitty| performance are user perceived latency while typing

View File

@@ -1,3 +1,5 @@
:orphan:
Working with the screen and history buffer contents
======================================================

View File

@@ -1,7 +1,7 @@
Extensions to the xterm protocol
Terminal protocol extensions
===================================
|kitty| has a few extensions to the xterm protocol, to enable advanced features.
|kitty| has extensions to the legacy terminal protocol, to enable advanced features.
These are typically in the form of new or re-purposed escape codes. While these
extensions are currently |kitty| specific, it would be nice to get some of them
adopted more broadly, to push the state of terminal emulators forward.
@@ -19,301 +19,14 @@ If you wish to discuss these extensions, propose additions/changes to them
please do so by opening issues in the `GitHub
<https://github.com/kovidgoyal/kitty/issues>`_ bug tracker.
.. contents::
:local:
Colored and styled underlines
-------------------------------
.. toctree::
:maxdepth: 1
|kitty| supports colored and styled (wavy) underlines. This is of particular
use in terminal editors such as vim and emacs to display red, wavy underlines
under mis-spelled words and/or syntax errors. This is done by re-purposing some
SGR escape codes that are not used in modern terminals (`CSI codes
<https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences>`_)
To set the underline style::
<ESC>[4:0m # this is no underline
<ESC>[4:1m # this is a straight underline
<ESC>[4:2m # this is a double underline
<ESC>[4:3m # this is a curly underline
<ESC>[4:4m # this is a dotted underline (not implemented in kitty)
<ESC>[4:5m # this is a dashed underline (not implemented in kitty)
<ESC>[4m # this is a straight underline (for backwards compat)
<ESC>[24m # this is no underline (for backwards compat)
To set the underline color (this is reserved and as far as I can tell not actually used for anything)::
<ESC>[58...m
This works exactly like the codes ``38, 48`` that are used to set foreground and
background color respectively.
To reset the underline color (also previously reserved and unused)::
<ESC>[59m
The underline color must remain the same under reverse video, if it has a
color, if not, it should follow the foreground color.
To detect support for this feature in a terminal emulator, query the terminfo database
for the ``Su`` boolean capability.
Graphics rendering
---------------------
See :doc:`/graphics-protocol` for a description
of this protocol to enable drawing of arbitrary raster images in the terminal.
.. _extended-key-protocol:
Keyboard handling
-------------------
kitty has a :doc:`keyboard protocol <keyboard-protocol>` for reporting key
presses to terminal applications that solves all key handling issues in
terminal applications.
.. _ext_styles:
Setting text styles/colors in arbitrary regions of the screen
------------------------------------------------------------------
There already exists an escape code to set *some* text attributes in arbitrary
regions of the screen, `DECCARA
<https://vt100.net/docs/vt510-rm/DECCARA.html>`_. However, it is limited to
only a few attributes. |kitty| extends this to work with *all* SGR attributes.
So, for example, this can be used to set the background color in an arbitrary
region of the screen.
The motivation for this extension is the various problems with the existing
solution for erasing to background color, namely the *background color erase
(bce)* capability. See
`this discussion <https://github.com/kovidgoyal/kitty/issues/160#issuecomment-346470545>`_
and `this FAQ <https://invisible-island.net/ncurses/ncurses.faq.html#bce_mismatches>`_
for a summary of problems with *bce*.
For example, to set the background color to blue in a
rectangular region of the screen from (3, 4) to (10, 11), you use::
<ESC>[2*x<ESC>[4;3;11;10;44$r<ESC>[*x
Saving and restoring colors
---------------------------------------------------------------------------------
It is often useful for a full screen application with its own color themes to
set the default foreground, background, selection and cursor colors and the
ANSI color table. This allows for various performance optimizations when
drawing the screen. The problem is that if the user previously used the escape
codes to change these colors herself, then running the full screen application
will lose her changes even after it exits. To avoid this, kitty introduces a
new pair of *OSC* escape codes to push and pop the current color values from a
stack::
<ESC>]30001<ESC>\ # push onto stack
<ESC>]30101<ESC>\ # pop from stack
These escape codes save/restore the colors, default
background, default foreground, selection background, selection foreground and
cursor color and the 256 colors of the ANSI color table.
.. note:: In July 2020, after several years, XTerm copied this protocol
extension, without acknowledgement, and using incompatible escape codes
(XTPUSHCOLORS, XTPOPCOLORS, XTREPORTCOLORS). And they decided to save not
just the dynamic colors but the entire ANSI color table. In the interests of
promoting interoperability, kitty added support for XTerm's escape codes as
well, and changed this extension to also save/restore the entire ANSI color
table.
Pasting to clipboard
----------------------
|kitty| implements the OSC 52 escape code protocol to get/set the clipboard
contents (controlled via the :opt:`clipboard_control` setting). There is one
difference in kitty's implementation compared to some other terminal emulators.
|kitty| allows sending arbitrary amounts of text to the clipboard. It does so
by modifying the protocol slightly. Successive OSC 52 escape codes to set the
clipboard will concatenate, so::
<ESC>]52;c;<payload1><ESC>\
<ESC>]52;c;<payload2><ESC>\
will result in the clipboard having the contents ``payload1 + payload2``. To
send a new string to the clipboard send an OSC 52 sequence with an invalid payload
first, for example::
<ESC>]52;c;!<ESC>\
Here ``!`` is not valid base64 encoded text, so it clears the clipboard.
Further, since it is invalid, it should be ignored by terminal emulators
that do not support this extension, thereby making it safe to use, simply
always send it before starting a new OSC 52 paste, even if you aren't chunking
up large pastes, that way kitty won't concatenate your paste, and it will have
no ill-effects in other terminal emulators.
In case you're using software that can't be easily adapted to this
protocol extension, it can be disabled by specifying ``no-append`` to the
:opt:`clipboard_control` setting.
.. _unscroll:
Unscrolling the screen
-----------------------
This is a small extension to the `SD (Pan up) escape code
<https://vt100.net/docs/vt510-rm/SD.html>`_ from the VT-420 terminal. The
``SD`` escape code normally causes the text on screen to scroll down by the
specified number of lines, with empty lines appearing at the top of the screen.
This extension allows the new lines to be filled in from the scrollback buffer
instead of being blank.
The motivation for this is that many modern shells will show completions in a
block of lines under the cursor, this causes some of the on-screen text to be
lost even after the completion is completed, because it has scrolled off
screen. This escape code allows that text to be restored.
If the scrollback buffer is empty or there is no scrollback buffer, such as for
the alternate screen, then the newly inserted lines must be empty, just as with
the original ``SD`` escape code. The maximum number of lines that can be
scrolled down is implementation defined, but must be at least one screen worth.
The syntax of the escape code is identical to that of ``SD`` except that it has
a trailing ``+`` modifier. This is legal under the `ECMA 48 standard
<https://www.ecma-international.org/publications-and-standards/standards/ecma-48/>`_
and unused for any other purpose as far as I can tell. So for example, to
unscroll three lines, the escape code would be::
CSI 3 + T
See `discussion here
<https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/30>`_.
.. versionadded:: 0.20.2
.. _desktop_notifications:
Desktop notifications
---------------------------------
|kitty| implements an extensible escape code (OSC 99) to show desktop
notifications. It is easy to use from shell scripts and fully extensible to
show title and body. Clicking on the notification can optionally focus the
window it came from, and/or send an escape code back to the application running
in that window.
The design of the escape code is partially based on the discussion in
the defunct
`terminal-wg <https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/13>`_
The escape code has the form::
<OSC> 99 ; metadata ; payload <terminator>
Here ``<OSC>`` is :code:`<ESC>]` and ``<terminator>`` is
:code:`<ESC><backslash>`. The metadata is a section of colon separated
:code:`key=value` pairs. Every key must be a single character from the set
:code:`a-zA-Z` and every value must be a word consisting of characters from
the set :code:`a-zA-Z0-9-_/\+.,(){}[]*&^%$#@!`~`. The payload must be
interpreted based on the metadata section. The two semi-colons *must* always be
present even when no metadata is present.
Before going into details, lets see how one can display a simple, single line
notification from a shell script::
printf '\x1b]99;;Hello world\x1b\\'
To show a message with a title and a body::
printf '\x1b]99;i=1:d=0;Hello world\x1b\\'
printf '\x1b]99;i=1:d=1:p=body;This is cool\x1b\\'
The most important key in the metadata is the ``p`` key, it controls how the
payload is interpreted. A value of ``title`` means the payload is setting the
title for the notification. A value of ``body`` means it is setting the body,
and so on, see the table below for full details.
The design of the escape code is fundamentally chunked, this is because
different terminal emulators have different limits on how large a single escape
code can be. Chunking is accomplished by the ``i`` and ``d`` keys. The ``i``
key is the *notification id* which can be any string containing the characters
``[a-zA-Z0-9_-+.]``. The ``d`` key stands for *done* and
can only take the values ``0`` and ``1``. A value of ``0`` means the
notification is not yet done and the terminal emulator should hold off
displaying it. A value of ``1`` means the notification is done, and should be
displayed. You can specify the title or body multiple times and the terminal
emulator will concatenate them, thereby allowing arbitrarily long text
(terminal emulators are free to impose a sensible limit to avoid
Denial-of-Service attacks).
Both the ``title`` and ``body`` payloads must be either UTF-8 encoded plain
text with no embedded escape codes, or UTF-8 text that is base64 encoded, in
which case there must be an ``e=1`` key in the metadata to indicate the payload
is base64 encoded.
When the user clicks the notification, a couple of things can happen, the
terminal emulator can focus the window from which the notification came, and/or
it can send back an escape code to the application indicating the notification
was activated. This is controlled by the ``a`` key which takes a comma
separated set of values, ``report`` and ``focus``. The value ``focus`` means
focus the window from which the notification was issued and is the default.
``report`` means send an escape code back to the application. The format of the
returned escape code is::
<OSC> 99 ; i=identifier ; <terminator>
The value of ``identifier`` comes from the ``i`` key in the escape code sent by
the application. If the application sends no identifier, then the terminal
*must* use ``i=0``. Actions can be preceded by a negative sign to turn them
off, so for example if you do not want any action, turn off the default
``focus`` action with::
a=-focus
Complete specification of all the metadata keys is in the table below. If a
terminal emulator encounters a key in the metadata it does not understand,
the key *must* be ignored, to allow for future extensibility of this escape
code. Similarly if values for known keys are unknown, the terminal emulator
*should* either ignore the entire escape code or perform a best guess effort
to display it based on what it does understand.
.. note::
It is possible to extend this escape code to allow specifying an icon for
the notification, however, given that some platforms, such as macOS, dont
allow displaying custom icons on a notification, at all, it was decided to
leave it out of the spec for the time being.
Similarly, features such as scheduled notifications could be added in future
revisions.
======= ==================== ========= =================
Key Value Default Description
======= ==================== ========= =================
``a`` Comma separated list ``focus`` What action to perform when the
of ``report``, notification is clicked
``focus``, with
optional leading
``-``
``d`` ``0`` or ``1`` ``1`` Indicates if the notification is
complete or not.
``e`` ``0`` or ``1`` ``0`` If set to ``1`` means the payload is base64 encoded UTF-8,
otherwise it is plain UTF-8 text with no C0 control codes in it
``i`` ``[a-zA-Z0-9-_+.]`` ``0`` Identifier for the notification
``p`` One of ``title`` or ``title`` Whether the payload is the notification title or body. If a
``body``. notification has no title, the body will be used as title.
======= ==================== ========= =================
.. note::
|kitty| also supports the legacy OSC 9 protocol developed by iTerm2 for
desktop notifications.
underlines
graphics-protocol
keyboard-protocol
desktop-notifications
unscroll
color-stack
deccara

28
docs/quickstart.rst Normal file
View File

@@ -0,0 +1,28 @@
.. _quickstart:
Quickstart
===========
.. toctree::
:hidden:
binary
build
Pre-built binaries of |kitty| are available for both macOS and Linux.
See the :doc:`binary install instructions </binary>`. You can also
:doc:`build from source </build>`.
Additionally, you can use your favorite package manager to install the |kitty|
package, but note that some Linux distribution packages are woefully outdated.
|kitty| is available in a vast number of package repositories for macOS
and Linux.
.. image:: https://repology.org/badge/tiny-repos/kitty.svg
:target: https://repology.org/project/kitty/versions
:alt: Number of repositories kitty is available in
See :doc:`Configuring kitty <conf>` for help on configuring |kitty| and
:doc:`Invocation <invocation>` for the command line arguments |kitty| supports.
For a tour of kitty's design and features, see the :doc:`/overview`.

View File

@@ -1,5 +1,5 @@
Documentation for the kitty remote control protocol
======================================================
The kitty remote control protocol
==================================
The kitty remote control protocol is a simple protocol that involves sending
data to kitty in the form of JSON. Any individual command of kitty has the
@@ -37,5 +37,4 @@ with the following command line::
echo -en '\eP@kitty-cmd{"cmd":"ls","version":[0,14,2]}\e\' | socat - unix:/tmp/test | awk '{ print substr($0, 13, length($0) - 14) }' | jq -c '.data | fromjson' | jq .
.. include:: generated/rc.rst

View File

@@ -1,17 +1,15 @@
:tocdepth: 2
Controlling kitty from scripts or the shell
==============================================
Control kitty from scripts
----------------------------
.. highlight:: sh
Tutorial
----------
|kitty| can be controlled from scripts or the shell prompt. You can open new
windows, send arbitrary text input to any window, name windows and tabs, etc.
Let's walk through a few examples of controlling |kitty|.
Tutorial
------------
Start by running |kitty| as::
kitty -o allow_remote_control=yes -o enabled_layouts=tall
@@ -142,6 +140,8 @@ running on other computers (for example, over ssh) or as other users.
kitty, as if you were running with ``allow_remote_control`` turned on.
.. _rc_mapping:
Mapping key presses to remote control commands
--------------------------------------------------
@@ -172,10 +172,15 @@ Now press, F1 and start typing, what you type will be sent to all windows,
live, as you type it.
Documentation for the remote control protocol
The remote control protocol
-----------------------------------------------
If you wish to develop your own client to talk to |kitty|, you
can use the :doc:`rc_protocol`.
can use the :doc:`protocol specification <rc_protocol>`.
.. toctree::
:hidden:
rc_protocol
.. include:: generated/cli-kitty-at.rst

5
docs/requirements.txt Normal file
View File

@@ -0,0 +1,5 @@
sphinx
furo
sphinx-copybutton
sphinxext-opengraph
sphinx-inline-tabs

36
docs/underlines.rst Normal file
View File

@@ -0,0 +1,36 @@
Colored and styled underlines
================================
|kitty| supports colored and styled (wavy) underlines. This is of particular
use in terminal editors such as vim and emacs to display red, wavy underlines
under mis-spelled words and/or syntax errors. This is done by re-purposing some
SGR escape codes that are not used in modern terminals (`CSI codes
<https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences>`_)
To set the underline style::
<ESC>[4:0m # this is no underline
<ESC>[4:1m # this is a straight underline
<ESC>[4:2m # this is a double underline
<ESC>[4:3m # this is a curly underline
<ESC>[4:4m # this is a dotted underline (not implemented in kitty)
<ESC>[4:5m # this is a dashed underline (not implemented in kitty)
<ESC>[4m # this is a straight underline (for backwards compat)
<ESC>[24m # this is no underline (for backwards compat)
To set the underline color (this is reserved and as far as I can tell not actually used for anything)::
<ESC>[58...m
This works exactly like the codes ``38, 48`` that are used to set foreground and
background color respectively.
To reset the underline color (also previously reserved and unused)::
<ESC>[59m
The underline color must remain the same under reverse video, if it has a
color, if not, it should follow the foreground color.
To detect support for this feature in a terminal emulator, query the terminfo database
for the ``Su`` boolean capability.

34
docs/unscroll.rst Normal file
View File

@@ -0,0 +1,34 @@
.. _unscroll:
Unscrolling the screen
========================
This is a small extension to the `SD (Pan up) escape code
<https://vt100.net/docs/vt510-rm/SD.html>`_ from the VT-420 terminal. The
``SD`` escape code normally causes the text on screen to scroll down by the
specified number of lines, with empty lines appearing at the top of the screen.
This extension allows the new lines to be filled in from the scrollback buffer
instead of being blank.
The motivation for this is that many modern shells will show completions in a
block of lines under the cursor, this causes some of the on-screen text to be
lost even after the completion is completed, because it has scrolled off
screen. This escape code allows that text to be restored.
If the scrollback buffer is empty or there is no scrollback buffer, such as for
the alternate screen, then the newly inserted lines must be empty, just as with
the original ``SD`` escape code. The maximum number of lines that can be
scrolled down is implementation defined, but must be at least one screen worth.
The syntax of the escape code is identical to that of ``SD`` except that it has
a trailing ``+`` modifier. This is legal under the `ECMA 48 standard
<https://www.ecma-international.org/publications-and-standards/standards/ecma-48/>`_
and unused for any other purpose as far as I can tell. So for example, to
unscroll three lines, the escape code would be::
CSI 3 + T
See `discussion here
<https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/30>`_.
.. versionadded:: 0.20.2

View File

@@ -250,7 +250,7 @@ def write_header(text: str, path: str) -> None:
def graphics_parser() -> None:
flag = frozenset
keymap: KeymapType = {
'a': ('action', flag('tTqpdfa')),
'a': ('action', flag('tTqpdfac')),
'd': ('delete_action', flag('aAiIcCfFnNpPqQxXyYzZ')),
't': ('transmission_type', flag('dfts')),
'o': ('compressed', flag('z')),

View File

@@ -2,426 +2,8 @@
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import inspect
import os
import pprint
import re
import textwrap
from typing import (
Any, Callable, Dict, Iterator, List, Set, Tuple, Union, get_type_hints
)
from kitty.conf.types import Definition, MultiOption, Option, unset
def chunks(lst: List, n: int) -> Iterator[List]:
for i in range(0, len(lst), n):
yield lst[i:i + n]
def atoi(text: str) -> str:
return f'{int(text):08d}' if text.isdigit() else text
def natural_keys(text: str) -> Tuple[str, ...]:
return tuple(atoi(c) for c in re.split(r'(\d+)', text))
def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
class_lines: List[str] = []
tc_lines: List[str] = []
a = class_lines.append
t = tc_lines.append
a('class Options:')
t('class Parser:')
choices = {}
imports: Set[Tuple[str, str]] = set()
tc_imports: Set[Tuple[str, str]] = set()
def type_name(x: type) -> str:
ans = x.__name__
if x.__module__ and x.__module__ != 'builtins':
imports.add((x.__module__, x.__name__))
return ans
def option_type_as_str(x: Any) -> str:
if hasattr(x, '__name__'):
return type_name(x)
ans = repr(x)
ans = ans.replace('NoneType', 'None')
return ans
def option_type_data(option: Union[Option, MultiOption]) -> Tuple[Callable, str]:
func = option.parser_func
if func.__module__ == 'builtins':
return func, func.__name__
th = get_type_hints(func)
rettype = th['return']
typ = option_type_as_str(rettype)
if isinstance(option, MultiOption):
typ = typ[typ.index('[') + 1:-1]
typ = typ.replace('Tuple', 'Dict', 1)
return func, typ
is_mutiple_vars = {}
option_names = set()
color_table = list(map(str, range(256)))
def parser_function_declaration(option_name: str) -> None:
t('')
t(f' def {option_name}(self, val: str, ans: typing.Dict[str, typing.Any]) -> None:')
for option in sorted(defn.iter_all_options(), key=lambda a: natural_keys(a.name)):
option_names.add(option.name)
parser_function_declaration(option.name)
if isinstance(option, MultiOption):
mval: Dict[str, Dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
func, typ = option_type_data(option)
for val in option:
if val.add_to_default:
gr = mval[val.only]
for k, v in func(val.defval_as_str):
gr[k] = v
is_mutiple_vars[option.name] = typ, mval
sig = inspect.signature(func)
tc_imports.add((func.__module__, func.__name__))
if len(sig.parameters) == 1:
t(f' for k, v in {func.__name__}(val):')
t(f' ans["{option.name}"][k] = v')
else:
t(f' for k, v in {func.__name__}(val, ans["{option.name}"]):')
t(f' ans["{option.name}"][k] = v')
continue
if option.choices:
typ = 'typing.Literal[{}]'.format(', '.join(repr(x) for x in option.choices))
ename = f'choices_for_{option.name}'
choices[ename] = typ
typ = ename
func = str
elif defn.has_color_table and option.is_color_table_color:
func, typ = option_type_data(option)
t(f' ans[{option.name!r}] = {func.__name__}(val)')
tc_imports.add((func.__module__, func.__name__))
cnum = int(option.name[5:])
color_table[cnum] = '0x{:06x}'.format(func(option.defval_as_string).__int__())
continue
else:
func, typ = option_type_data(option)
try:
params = inspect.signature(func).parameters
except Exception:
params = {}
if 'dict_with_parse_results' in params:
t(f' {func.__name__}(val, ans)')
else:
t(f' ans[{option.name!r}] = {func.__name__}(val)')
if func.__module__ != 'builtins':
tc_imports.add((func.__module__, func.__name__))
defval = repr(func(option.defval_as_string))
if option.macos_defval is not unset:
md = repr(func(option.macos_defval))
defval = f'{md} if is_macos else {defval}'
imports.add(('kitty.constants', 'is_macos'))
a(f' {option.name}: {typ} = {defval}')
if option.choices:
t(' val = val.lower()')
t(f' if val not in self.choices_for_{option.name}:')
t(f' raise ValueError(f"The value {{val}} is not a valid choice for {option.name}")')
t(f' ans["{option.name}"] = val')
t('')
t(f' choices_for_{option.name} = frozenset({option.choices!r})')
for option_name, (typ, mval) in is_mutiple_vars.items():
a(f' {option_name}: {typ} = ' '{}')
for parser, aliases in defn.deprecations.items():
for alias in aliases:
parser_function_declaration(alias)
tc_imports.add((parser.__module__, parser.__name__))
t(f' {parser.__name__}({alias!r}, val, ans)')
action_parsers = {}
def resolve_import(ftype: str) -> str:
if '.' in ftype:
fmod, ftype = ftype.rpartition('.')[::2]
else:
fmod = f'{loc}.options.utils'
imports.add((fmod, ftype))
return ftype
for aname, action in defn.actions.items():
option_names.add(aname)
action_parsers[aname] = func = action.parser_func
th = get_type_hints(func)
rettype = th['return']
typ = option_type_as_str(rettype)
typ = typ[typ.index('[') + 1:-1]
a(f' {aname}: typing.List[{typ}] = []')
for imp in action.imports:
resolve_import(imp)
for fname, ftype in action.fields.items():
ftype = resolve_import(ftype)
a(f' {fname}: {ftype} = ' '{}')
parser_function_declaration(aname)
t(f' for k in {func.__name__}(val):')
t(f' ans[{aname!r}].append(k)')
tc_imports.add((func.__module__, func.__name__))
if defn.has_color_table:
imports.add(('array', 'array'))
a(' color_table: array = array("L", (')
for grp in chunks(color_table, 8):
a(' ' + ', '.join(grp) + ',')
a(' ))')
a(' config_paths: typing.Tuple[str, ...] = ()')
a(' config_overrides: typing.Tuple[str, ...] = ()')
a('')
a(' def __init__(self, options_dict: typing.Optional[typing.Dict[str, typing.Any]] = None) -> None:')
a(' if options_dict is not None:')
a(' for key in option_names:')
a(' setattr(self, key, options_dict[key])')
a('')
a(' @property')
a(' def _fields(self) -> typing.Tuple[str, ...]:')
a(' return option_names')
a('')
a(' def __iter__(self) -> typing.Iterator[str]:')
a(' return iter(self._fields)')
a('')
a(' def __len__(self) -> int:')
a(' return len(self._fields)')
a('')
a(' def _copy_of_val(self, name: str) -> typing.Any:')
a(' ans = getattr(self, name)')
a(' if isinstance(ans, dict):\n ans = ans.copy()')
a(' elif isinstance(ans, list):\n ans = ans[:]')
a(' return ans')
a('')
a(' def _asdict(self) -> typing.Dict[str, typing.Any]:')
a(' return {k: self._copy_of_val(k) for k in self}')
a('')
a(' def _replace(self, **kw: typing.Any) -> "Options":')
a(' ans = Options()')
a(' for name in self:')
a(' setattr(ans, name, self._copy_of_val(name))')
a(' for name, val in kw.items():')
a(' setattr(ans, name, val)')
a(' return ans')
a('')
a(' def __getitem__(self, key: typing.Union[int, str]) -> typing.Any:')
a(' k = option_names[key] if isinstance(key, int) else key')
a(' try:')
a(' return getattr(self, k)')
a(' except AttributeError:')
a(' pass')
a(' raise KeyError(f"No option named: {k}")')
if defn.has_color_table:
a('')
a(' def __getattr__(self, key: str) -> typing.Any:')
a(' if key.startswith("color"):')
a(' q = key[5:]')
a(' if q.isdigit():')
a(' k = int(q)')
a(' if 0 <= k <= 255:')
a(' x = self.color_table[k]')
a(' return Color((x >> 16) & 255, (x >> 8) & 255, x & 255)')
a(' raise AttributeError(key)')
a('')
a(' def __setattr__(self, key: str, val: typing.Any) -> typing.Any:')
a(' if key.startswith("color"):')
a(' q = key[5:]')
a(' if q.isdigit():')
a(' k = int(q)')
a(' if 0 <= k <= 255:')
a(' self.color_table[k] = int(val)')
a(' return')
a(' object.__setattr__(self, key, val)')
a('')
a('')
a('defaults = Options()')
for option_name, (typ, mval) in is_mutiple_vars.items():
a(f'defaults.{option_name} = {mval[""]!r}')
if mval['macos']:
imports.add(('kitty.constants', 'is_macos'))
a('if is_macos:')
a(f' defaults.{option_name}.update({mval["macos"]!r}')
if mval['macos']:
imports.add(('kitty.constants', 'is_macos'))
a('if not is_macos:')
a(f' defaults.{option_name}.update({mval["linux"]!r}')
for aname, func in action_parsers.items():
a(f'defaults.{aname} = [')
only: Dict[str, List[Tuple[str, Callable]]] = {}
for sc in defn.iter_all_maps(aname):
if not sc.add_to_default:
continue
text = sc.parseable_text
if sc.only:
only.setdefault(sc.only, []).append((text, func))
else:
for val in func(text):
a(f' # {sc.name}')
a(f' {val!r},')
a(']')
if only:
imports.add(('kitty.constants', 'is_macos'))
for cond, items in only.items():
cond = 'is_macos' if cond == 'macos' else 'not is_macos'
a(f'if {cond}:')
for (text, func) in items:
for val in func(text):
a(f' defaults.{aname}.append({val!r})')
t('')
t('')
t('def create_result_dict() -> typing.Dict[str, typing.Any]:')
t(' return {')
for oname in is_mutiple_vars:
t(f' {oname!r}: {{}},')
for aname in defn.actions:
t(f' {aname!r}: [],')
t(' }')
t('')
t('')
t(f'actions = frozenset({tuple(defn.actions)!r})')
t('')
t('')
t('def merge_result_dicts(defaults: typing.Dict[str, typing.Any], vals: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:')
t(' ans = {}')
t(' for k, v in defaults.items():')
t(' if isinstance(v, dict):')
t(' ans[k] = merge_dicts(v, vals.get(k, {}))')
t(' elif k in actions:')
t(' ans[k] = v + vals.get(k, [])')
t(' else:')
t(' ans[k] = vals.get(k, v)')
t(' return ans')
tc_imports.add(('kitty.conf.utils', 'merge_dicts'))
t('')
t('')
t('parser = Parser()')
t('')
t('')
t('def parse_conf_item(key: str, val: str, ans: typing.Dict[str, typing.Any]) -> bool:')
t(' func = getattr(parser, key, None)')
t(' if func is not None:')
t(' func(val, ans)')
t(' return True')
t(' return False')
preamble = ['# generated by gen-config.py DO NOT edit', '# vim:fileencoding=utf-8', '']
a = preamble.append
def output_imports(imports: Set, add_module_imports: bool = True) -> None:
a('import typing')
seen_mods = {'typing'}
mmap: Dict[str, List[str]] = {}
for mod, name in imports:
mmap.setdefault(mod, []).append(name)
for mod in sorted(mmap):
names = sorted(mmap[mod])
lines = textwrap.wrap(', '.join(names), 100)
if len(lines) == 1:
s = lines[0]
else:
s = '\n '.join(lines)
s = f'(\n {s}\n)'
a(f'from {mod} import {s}')
if add_module_imports and mod not in seen_mods and mod != s:
a(f'import {mod}')
seen_mods.add(mod)
output_imports(imports)
a('')
if choices:
a('if typing.TYPE_CHECKING:')
for name, cdefn in choices.items():
a(f' {name} = {cdefn}')
a('else:')
for name in choices:
a(f' {name} = str')
a('')
a('option_names = ( # {{''{')
a(' ' + pprint.pformat(tuple(sorted(option_names, key=natural_keys)))[1:] + ' # }}''}')
class_def = '\n'.join(preamble + ['', ''] + class_lines)
preamble = ['# generated by gen-config.py DO NOT edit', '# vim:fileencoding=utf-8', '']
a = preamble.append
output_imports(tc_imports, False)
return class_def, '\n'.join(preamble + ['', ''] + tc_lines)
def generate_c_conversion(loc: str, ctypes: List[Option]) -> str:
lines: List[str] = []
basic_converters = {
'int': 'PyLong_AsLong', 'uint': 'PyLong_AsUnsignedLong', 'bool': 'PyObject_IsTrue',
'float': 'PyFloat_AsFloat', 'double': 'PyFloat_AsDouble',
'time': 'parse_s_double_to_monotonic_t', 'time-ms': 'parse_ms_long_to_monotonic_t'
}
for opt in ctypes:
lines.append('')
lines.append(f'static void\nconvert_from_python_{opt.name}(PyObject *val, Options *opts) ''{')
is_special = opt.ctype.startswith('!')
if is_special:
func = opt.ctype[1:]
lines.append(f' {func}(val, opts);')
else:
func = basic_converters.get(opt.ctype, opt.ctype)
lines.append(f' opts->{opt.name} = {func}(val);')
lines.append('}')
lines.append('')
lines.append(f'static void\nconvert_from_opts_{opt.name}(PyObject *py_opts, Options *opts) ''{')
lines.append(f' PyObject *ret = PyObject_GetAttrString(py_opts, "{opt.name}");')
lines.append(' if (ret == NULL) return;')
lines.append(f' convert_from_python_{opt.name}(ret, opts);')
lines.append(' Py_DECREF(ret);')
lines.append('}')
lines.append('')
lines.append('static bool\nconvert_opts_from_python_opts(PyObject *py_opts, Options *opts) ''{')
for opt in ctypes:
lines.append(f' convert_from_opts_{opt.name}(py_opts, opts);')
lines.append(' if (PyErr_Occurred()) return false;')
lines.append(' return true;')
lines.append('}')
preamble = ['// generated by gen-config.py DO NOT edit', '// vim:fileencoding=utf-8', '#pragma once', '#include "to-c.h"']
return '\n'.join(preamble + ['', ''] + lines)
def write_output(loc: str, defn: Definition) -> None:
cls, tc = generate_class(defn, loc)
with open(os.path.join(*loc.split('.'), 'options', 'types.py'), 'w') as f:
f.write(cls + '\n')
with open(os.path.join(*loc.split('.'), 'options', 'parse.py'), 'w') as f:
f.write(tc + '\n')
ctypes = []
for opt in defn.root_group.iter_all_non_groups():
if isinstance(opt, Option) and opt.ctype:
ctypes.append(opt)
if ctypes:
c = generate_c_conversion(loc, ctypes)
with open(os.path.join(*loc.split('.'), 'options', 'to-c-generated.h'), 'w') as f:
f.write(c + '\n')
from kitty.conf.generate import write_output
def main() -> None:

View File

@@ -388,7 +388,8 @@ def gen_ucd() -> None:
rmap[0xfe0e], rmap[0xfe0f]
))
with open('kittens/hints/url_regex.py', 'w') as f:
f.write("url_delimiters = '{}' # noqa".format(''.join(classes_to_regex(cz, exclude='\n'))))
f.write('# generated by gen-wcwidth.py, do not edit\n\n')
f.write("url_delimiters = '{}' # noqa".format(''.join(classes_to_regex(cz, exclude='\n\r'))))
def gen_names() -> None:

View File

@@ -91,7 +91,7 @@ compare_timers(const void *a_, const void *b_) {
return (a->trigger_at > b->trigger_at) ? 1 : (a->trigger_at < b->trigger_at) ? -1 : 0;
}
static inline void
static void
update_timers(EventLoopData *eld) {
if (eld->timers_count > 1) qsort(eld->timers, eld->timers_count, sizeof(eld->timers[0]), compare_timers);
}
@@ -164,7 +164,7 @@ prepareForPoll(EventLoopData *eld, monotonic_t timeout) {
return timeout;
}
static inline struct timespec
static struct timespec
calc_time(monotonic_t nsec) {
struct timespec result;
result.tv_sec = nsec / (1000LL * 1000LL * 1000LL);
@@ -271,7 +271,7 @@ wakeupEventLoop(EventLoopData *eld) {
}
#ifndef HAS_EVENT_FD
static inline void
static void
closeFds(int *fds, size_t count) {
while(count--) {
if (*fds > 0) {
@@ -375,7 +375,7 @@ GLFWAPI char* utf_8_strndup(const char* source, size_t max_length) {
int createAnonymousFile(off_t size) {
int ret, fd = -1, shm_anon = 0;
#ifdef HAS_MEMFD_CREATE
fd = memfd_create("glfw-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
fd = glfw_memfd_create("glfw-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) return -1;
// We can add this seal before calling posix_fallocate(), as the file
// is currently zero-sized anyway.

View File

@@ -453,7 +453,7 @@ void* _glfwLoadLocalVulkanLoaderNS(void)
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
static inline bool
static bool
is_ctrl_tab(NSEvent *event, NSEventModifierFlags modifierFlags) {
if (
(modifierFlags == NSEventModifierFlagControl &&
@@ -464,7 +464,7 @@ is_ctrl_tab(NSEvent *event, NSEventModifierFlags modifierFlags) {
return false;
}
static inline bool
static bool
is_cmd_period(NSEvent *event, NSEventModifierFlags modifierFlags) {
if (modifierFlags != NSEventModifierFlagCommand) return false;
if ([event.charactersIgnoringModifiers isEqualToString:@"."]) return true;
@@ -703,7 +703,7 @@ typedef struct {
static Timer timers[128] = {{0}};
static size_t num_timers = 0;
static inline void
static void
remove_timer_at(size_t idx) {
if (idx < num_timers) {
Timer *t = timers + idx;

View File

@@ -41,8 +41,22 @@
// Get the name of the specified display, or NULL
//
static char* getDisplayName(CGDirectDisplayID displayID)
static char*
getDisplayName(CGDirectDisplayID displayID, NSScreen* screen)
{
// IOKit doesn't work on Apple Silicon anymore
// Luckily, 10.15 introduced -[NSScreen localizedName].
// Use it if available, and fall back to IOKit otherwise.
if (screen)
{
if ([screen respondsToSelector:@selector(localizedName)])
{
NSString* name = [screen valueForKey:@"localizedName"];
if (name) {
return _glfw_strdup([name UTF8String]);
}
}
}
io_iterator_t it;
io_service_t service;
CFDictionaryRef info;
@@ -89,7 +103,7 @@ static char* getDisplayName(CGDirectDisplayID displayID)
if (!service)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Cocoa: Failed to find service port for display, cannot get its name, using Unknown");
"Cocoa: Failed to find service port for display");
return NULL;
}
@@ -314,11 +328,9 @@ void _glfwClearDisplayLinks() {
if (_glfw.ns.displayLinks.entries[i].displayLink) {
CVDisplayLinkStop(_glfw.ns.displayLinks.entries[i].displayLink);
CVDisplayLinkRelease(_glfw.ns.displayLinks.entries[i].displayLink);
_glfw.ns.displayLinks.entries[i].displayLink = nil;
_glfw.ns.displayLinks.entries[i].lastRenderFrameRequestedAt = 0;
_glfw.ns.displayLinks.entries[i].first_unserviced_render_frame_request_at = 0;
}
}
memset(_glfw.ns.displayLinks.entries, 0, sizeof(_GLFWDisplayLinkNS) * _glfw.ns.displayLinks.count);
_glfw.ns.displayLinks.count = 0;
}
@@ -340,16 +352,21 @@ _glfw_create_cv_display_link(_GLFWDisplayLinkNS *entry) {
CVDisplayLinkSetOutputCallback(entry->displayLink, &displayLinkCallback, (void*)(uintptr_t)entry->displayID);
}
static void
createDisplayLink(CGDirectDisplayID displayID) {
if (_glfw.ns.displayLinks.count >= sizeof(_glfw.ns.displayLinks.entries)/sizeof(_glfw.ns.displayLinks.entries[0]) - 1) return;
_GLFWDisplayLinkNS*
_glfw_create_display_link(CGDirectDisplayID displayID) {
if (_glfw.ns.displayLinks.count >= arraysz(_glfw.ns.displayLinks.entries) - 1) {
_glfwInputError(GLFW_PLATFORM_ERROR, "Too many monitors cannot create display link");
return NULL;
}
for (size_t i = 0; i < _glfw.ns.displayLinks.count; i++) {
if (_glfw.ns.displayLinks.entries[i].displayID == displayID) return;
// already created in this run
if (_glfw.ns.displayLinks.entries[i].displayID == displayID) return _glfw.ns.displayLinks.entries + i;
}
_GLFWDisplayLinkNS *entry = &_glfw.ns.displayLinks.entries[_glfw.ns.displayLinks.count++];
memset(entry, 0, sizeof(_GLFWDisplayLinkNS));
entry->displayID = displayID;
_glfw_create_cv_display_link(entry);
return entry;
}
// Poll for changes in the set of connected monitors
@@ -357,11 +374,13 @@ createDisplayLink(CGDirectDisplayID displayID) {
void _glfwPollMonitorsNS(void)
{
uint32_t displayCount;
CGGetOnlineDisplayList(0, NULL, &displayCount);
CGDirectDisplayID* displays = calloc(displayCount, sizeof(CGDirectDisplayID));
CGGetOnlineDisplayList(displayCount, displays, &displayCount);
_glfwClearDisplayLinks();
if (_glfw.hints.init.debugRendering) {
fprintf(stderr, "Polling for monitors: %u found\n", displayCount);
}
for (int i = 0; i < _glfw.monitorCount; i++)
_glfw.monitors[i]->ns.screen = nil;
@@ -378,32 +397,57 @@ void _glfwPollMonitorsNS(void)
for (uint32_t i = 0; i < displayCount; i++)
{
if (CGDisplayIsAsleep(displays[i]))
if (CGDisplayIsAsleep(displays[i])) {
if (_glfw.hints.init.debugRendering) fprintf(stderr, "Ignoring sleeping display: %u", displays[i]);
continue;
}
const uint32_t unitNumber = CGDisplayUnitNumber(displays[i]);
NSScreen* screen = nil;
for (screen in [NSScreen screens])
{
NSNumber* screenNumber = [screen deviceDescription][@"NSScreenNumber"];
// HACK: Compare unit numbers instead of display IDs to work around
// display replacement on machines with automatic graphics
// switching
if (CGDisplayUnitNumber([screenNumber unsignedIntValue]) == unitNumber)
break;
}
// HACK: Compare unit numbers instead of display IDs to work around
// display replacement on machines with automatic graphics
// switching
const uint32_t unitNumber = CGDisplayUnitNumber(displays[i]);
for (uint32_t j = 0; j < disconnectedCount; j++)
uint32_t j;
for (j = 0; j < disconnectedCount; j++)
{
if (disconnected[j] && disconnected[j]->ns.unitNumber == unitNumber)
{
disconnected[j]->ns.displayID = displays[i];
disconnected[j]->ns.screen = screen;
_glfw_create_display_link(displays[i]);
disconnected[j] = NULL;
break;
}
}
if (j < disconnectedCount)
continue;
const CGSize size = CGDisplayScreenSize(displays[i]);
char* name = getDisplayName(displays[i]);
if (!name)
name = _glfw_strdup("Unknown");
char* name = getDisplayName(displays[i], screen);
if (!name) {
_glfwInputError(GLFW_PLATFORM_ERROR,
"Failed to get name for display, using generic name");
name = _glfw_strdup("Display with no name");
}
_GLFWmonitor* monitor = _glfwAllocMonitor(name, (int)size.width, (int)size.height);
monitor->ns.displayID = displays[i];
monitor->ns.unitNumber = unitNumber;
createDisplayLink(monitor->ns.displayID);
monitor->ns.screen = screen;
_glfw_create_display_link(monitor->ns.displayID);
free(name);
@@ -554,15 +598,16 @@ GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count)
const GLFWvidmode mode =
vidmodeFromCGDisplayMode(dm, monitor->ns.fallbackRefreshRate);
CFIndex j;
for (CFIndex j = 0; j < *count; j++)
for (j = 0; j < *count; j++)
{
if (_glfwCompareVideoModes(result + j, &mode) == 0)
break;
}
// Skip duplicate modes
if (i < *count)
if (j < *count)
continue;
(*count)++;

View File

@@ -250,3 +250,4 @@ void _glfwDispatchRenderFrame(CGDirectDisplayID);
void _glfwShutdownCVDisplayLink(unsigned long long, void*);
void _glfwCocoaPostEmptyEvent(void);
void _glfw_create_cv_display_link(_GLFWDisplayLinkNS *entry);
_GLFWDisplayLinkNS* _glfw_create_display_link(CGDirectDisplayID);

View File

@@ -233,10 +233,10 @@ mac_ucode_to_functional(uint32_t key_code) { // {{{
}
} // }}}
static inline bool
static bool
is_surrogate(UniChar uc) { return (uc - 0xd800u) < 2048u; }
static inline uint32_t
static uint32_t
get_first_codepoint(UniChar *utf16, UniCharCount num) {
if (!num) return 0;
if (!is_surrogate(*utf16)) return *utf16;
@@ -244,7 +244,7 @@ get_first_codepoint(UniChar *utf16, UniCharCount num) {
return 0;
}
static inline bool
static bool
is_pua_char(uint32_t ch) {
return (0xE000 <= ch && ch <= 0xF8FF) || (0xF0000 <= ch && ch <= 0xFFFFF) || (0x100000 <= ch && ch <= 0x10FFFF);
}
@@ -321,7 +321,7 @@ _glfwShutdownCVDisplayLink(unsigned long long timer_id UNUSED, void *user_data U
}
}
static inline void
static void
requestRenderFrame(_GLFWwindow *w, GLFWcocoarenderframefun callback) {
if (!callback) {
w->ns.renderFrameRequested = false;
@@ -337,9 +337,12 @@ requestRenderFrame(_GLFWwindow *w, GLFWcocoarenderframefun callback) {
display_link_shutdown_timer = _glfwPlatformAddTimer(DISPLAY_LINK_SHUTDOWN_CHECK_INTERVAL, false, _glfwShutdownCVDisplayLink, NULL, NULL);
}
monotonic_t now = glfwGetTime();
bool found_display_link = false;
_GLFWDisplayLinkNS *dl = NULL;
for (size_t i = 0; i < _glfw.ns.displayLinks.count; i++) {
_GLFWDisplayLinkNS *dl = &_glfw.ns.displayLinks.entries[i];
dl = &_glfw.ns.displayLinks.entries[i];
if (dl->displayID == displayID) {
found_display_link = true;
dl->lastRenderFrameRequestedAt = now;
if (!dl->first_unserviced_render_frame_request_at) dl->first_unserviced_render_frame_request_at = now;
if (!CVDisplayLinkIsRunning(dl->displayLink)) CVDisplayLinkStart(dl->displayLink);
@@ -359,6 +362,14 @@ requestRenderFrame(_GLFWwindow *w, GLFWcocoarenderframefun callback) {
dl->first_unserviced_render_frame_request_at = 0;
}
}
if (!found_display_link) {
dl = _glfw_create_display_link(displayID);
if (dl) {
dl->lastRenderFrameRequestedAt = now;
dl->first_unserviced_render_frame_request_at = now;
if (!CVDisplayLinkIsRunning(dl->displayLink)) CVDisplayLinkStart(dl->displayLink);
}
}
}
void
@@ -494,7 +505,7 @@ translateFlags(NSUInteger flags)
#define debug_key(...) if (_glfw.hints.init.debugKeyboard) { fprintf(stderr, __VA_ARGS__); fflush(stderr); }
static inline const char*
static const char*
format_mods(int mods) {
static char buf[128];
char *p = buf, *s;
@@ -514,7 +525,7 @@ format_mods(int mods) {
return buf;
}
static inline const char*
static const char*
format_text(const char *src) {
static char buf[256];
char *p = buf;
@@ -1133,7 +1144,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 };
[super updateTrackingAreas];
}
static inline UInt32
static UInt32
convert_cocoa_to_carbon_modifiers(NSUInteger flags) {
UInt32 mods = 0;
if (flags & NSEventModifierFlagShift)
@@ -1150,7 +1161,7 @@ convert_cocoa_to_carbon_modifiers(NSUInteger flags) {
return (mods >> 8) & 0xFF;
}
static inline void
static void
convert_utf16_to_utf8(UniChar *src, UniCharCount src_length, char *dest, size_t dest_sz) {
CFStringRef string = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
src,
@@ -1163,12 +1174,12 @@ convert_utf16_to_utf8(UniChar *src, UniCharCount src_length, char *dest, size_t
CFRelease(string);
}
static inline bool
static bool
alternate_key_is_ok(uint32_t key, uint32_t akey) {
return akey > 31 && akey != key && !is_pua_char(akey);
}
static inline void
static void
add_alternate_keys(GLFWkeyevent *ev, NSEvent *event) {
ev->alternate_key = translateKey(ev->native_key, false);
if (!alternate_key_is_ok(ev->key, ev->alternate_key)) ev->alternate_key = 0;
@@ -1187,7 +1198,7 @@ add_alternate_keys(GLFWkeyevent *ev, NSEvent *event) {
}
}
static inline bool
static bool
is_ascii_control_char(char x) {
return x == 0 || (1 <= x && x <= 31) || x == 127;
}
@@ -1712,6 +1723,7 @@ int _glfwPlatformCreateWindow(_GLFWwindow* window,
if (!createNativeWindow(window, wndconfig, fbconfig))
return false;
[window->ns.object setColorSpace:[NSColorSpace sRGBColorSpace]];
if (ctxconfig->client != GLFW_NO_API)
{

4
glfw/dbus_glfw.c vendored
View File

@@ -31,7 +31,7 @@
#include <stdlib.h>
#include <string.h>
static inline void
static void
report_error(DBusError *err, const char *fmt, ...) {
static char buf[1024];
va_list args;
@@ -64,7 +64,7 @@ on_dbus_watch_ready(int fd UNUSED, int events, void *data) {
dbus_watch_handle(watch, flags);
}
static inline int
static int
events_for_watch(DBusWatch *watch) {
int events = 0;
unsigned int flags = dbus_watch_get_flags(watch);

View File

@@ -222,6 +222,7 @@ def generate_wrappers(glfw_header: str) -> None:
unsigned long long glfwDBusUserNotify(const char *app_name, const char* icon, const char *summary, const char *body, \
const char *action_text, int32_t timeout, GLFWDBusnotificationcreatedfun callback, void *data)
void glfwDBusSetUserNotificationHandler(GLFWDBusnotificationactivatedfun handler)
int glfwSetX11LaunchCommand(GLFWwindow *handle, char **argv, int argc)
'''.splitlines():
if line:
functions.append(Function(line.strip(), check_fail=False))

12
glfw/ibus_glfw.c vendored
View File

@@ -50,13 +50,13 @@ enum Capabilities {
};
static inline bool
static bool
test_env_var(const char *name, const char *val) {
const char *q = getenv(name);
return (q && strcmp(q, val) == 0) ? true : false;
}
static inline size_t
static size_t
GLFW_MIN(size_t a, size_t b) {
return a < b ? a : b;
}
@@ -106,7 +106,7 @@ get_ibus_text_from_message(DBusMessage *msg) {
return text;
}
static inline void
static void
send_text(const char *text, GLFWIMEState ime_state) {
_GLFWwindow *w = _glfwFocusedWindow();
if (w && w->callbacks.keyboard) {
@@ -147,7 +147,7 @@ message_handler(DBusConnection *conn UNUSED, DBusMessage *msg, void *user_data)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static inline const char*
static const char*
get_ibus_address_file_name(void) {
const char *addr;
static char ans[PATH_MAX];
@@ -196,7 +196,7 @@ get_ibus_address_file_name(void) {
}
static inline bool
static bool
read_ibus_address(_GLFWIBUSData *ibus) {
static char buf[1024];
struct stat s;
@@ -379,7 +379,7 @@ typedef enum
} IBusModifierType;
static inline uint32_t
static uint32_t
ibus_key_state(unsigned int glfw_modifiers, int action) {
uint32_t ans = action == GLFW_RELEASE ? IBUS_RELEASE_MASK : 0;
#define M(g, i) if(glfw_modifiers & GLFW_MOD_##g) ans |= i

4
glfw/memfd.h vendored
View File

@@ -10,8 +10,8 @@
#include <unistd.h>
#include <sys/syscall.h>
static inline int memfd_create(const char *name, unsigned int flags) {
return syscall(__NR_memfd_create, name, flags);
static inline int glfw_memfd_create(const char *name, unsigned int flags) {
return (int)syscall(__NR_memfd_create, name, flags);
}
#ifndef F_LINUX_SPECIFIC_BASE

3
glfw/wl_init.c vendored
View File

@@ -29,7 +29,6 @@
#define _GNU_SOURCE
#include "internal.h"
#include "backend_utils.h"
#include "wl_client_side_decorations.h"
#include "linux_desktop_settings.h"
#include "../kitty/monotonic.h"
@@ -55,7 +54,7 @@
#endif
static inline int min(int n1, int n2)
static int min(int n1, int n2)
{
return n1 < n2 ? n1 : n2;
}

View File

@@ -43,7 +43,7 @@ text_input_leave(void *data UNUSED, struct zwp_text_input_v3 *text_input UNUSED,
}
}
static inline void
static void
send_text(const char *text, GLFWIMEState ime_state) {
_GLFWwindow *w = _glfwFocusedWindow();
if (w && w->callbacks.keyboard) {

45
glfw/wl_window.c vendored
View File

@@ -254,15 +254,39 @@ dispatchChangesAfterConfigure(_GLFWwindow *window, int32_t width, int32_t height
_glfwInputWindowDamage(window);
}
static void
inform_compositor_of_window_geometry(_GLFWwindow *window, const char *event) {
#define geometry window->wl.decorations.geometry
debug("Setting window geometry in %s event: x=%d y=%d %dx%d\n", event, geometry.x, geometry.y, geometry.width, geometry.height);
xdg_surface_set_window_geometry(window->wl.xdg.surface, geometry.x, geometry.y, geometry.width, geometry.height);
#undef geometry
}
static void xdgDecorationHandleConfigure(void* data,
static void
xdgDecorationHandleConfigure(void* data,
struct zxdg_toplevel_decoration_v1* decoration UNUSED,
uint32_t mode)
{
_GLFWwindow* window = data;
window->wl.decorations.serverSide = (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
bool has_server_side_decorations = (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
debug("XDG decoration configure event received: has_server_side_decorations: %d\n", has_server_side_decorations);
if (has_server_side_decorations == window->wl.decorations.serverSide) return;
window->wl.decorations.serverSide = has_server_side_decorations;
int width = window->wl.width, height = window->wl.height;
if (window->wl.decorations.serverSide) {
free_csd_surfaces(window);
height += window->wl.decorations.metrics.visible_titlebar_height;
} else {
ensure_csd_resources(window);
}
set_csd_window_geometry(window, &width, &height);
dispatchChangesAfterConfigure(window, width, height);
ensure_csd_resources(window);
wl_surface_commit(window->wl.surface);
debug("final window content size: %dx%d\n", window->wl.width, window->wl.height);
inform_compositor_of_window_geometry(window, "configure-decorations");
}
static const struct zxdg_toplevel_decoration_v1_listener xdgDecorationListener = {
@@ -396,7 +420,8 @@ _glfwPlatformToggleFullscreen(_GLFWwindow *window, unsigned int flags UNUSED) {
return !already_fullscreen;
}
static void xdgToplevelHandleConfigure(void* data,
static void
xdgToplevelHandleConfigure(void* data,
struct xdg_toplevel* toplevel UNUSED,
int32_t width,
int32_t height,
@@ -452,10 +477,7 @@ static void xdgToplevelHandleConfigure(void* data,
_glfwInputWindowFocus(window, window->wl.toplevel_states & TOPLEVEL_STATE_ACTIVATED);
ensure_csd_resources(window);
wl_surface_commit(window->wl.surface);
#define geometry window->wl.decorations.geometry
debug("Setting window geometry: x=%d y=%d %dx%d\n", geometry.x, geometry.y, geometry.width, geometry.height);
xdg_surface_set_window_geometry(window->wl.xdg.surface, geometry.x, geometry.y, geometry.width, geometry.height);
#undef geometry
inform_compositor_of_window_geometry(window, "configure");
if (live_resize_done) _glfwInputLiveResize(window, false);
}
@@ -482,7 +504,8 @@ static const struct xdg_surface_listener xdgSurfaceListener = {
xdgSurfaceHandleConfigure
};
static void setXdgDecorations(_GLFWwindow* window)
static void
setXdgDecorations(_GLFWwindow* window)
{
if (_glfw.wl.decorationManager)
{
@@ -504,7 +527,8 @@ static void setXdgDecorations(_GLFWwindow* window)
}
}
static bool createXdgSurface(_GLFWwindow* window)
static bool
createXdgSurface(_GLFWwindow* window)
{
window->wl.xdg.surface = xdg_wm_base_get_xdg_surface(_glfw.wl.wmBase,
window->wl.surface);
@@ -872,6 +896,7 @@ void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
resizeFramebuffer(window);
ensure_csd_resources(window);
wl_surface_commit(window->wl.surface);
inform_compositor_of_window_geometry(window, "SetWindowSize");
}
}
@@ -1737,7 +1762,7 @@ void _glfwSetupWaylandPrimarySelectionDevice() {
if (_glfw.wl.primarySelectionDevice) zwp_primary_selection_device_v1_add_listener(_glfw.wl.primarySelectionDevice, &primary_selection_device_listener, NULL);
}
static inline bool _glfwEnsureDataDevice(void) {
static bool _glfwEnsureDataDevice(void) {
if (!_glfw.wl.dataDeviceManager)
{
_glfwInputError(GLFW_PLATFORM_ERROR,

13
glfw/x11_window.c vendored
View File

@@ -281,7 +281,7 @@ updateNormalHints(_GLFWwindow* window, int width, int height)
XFree(hints);
}
static inline bool
static bool
is_window_fullscreen(_GLFWwindow* window)
{
Atom* states;
@@ -310,7 +310,7 @@ is_window_fullscreen(_GLFWwindow* window)
return ans;
}
static inline void
static void
set_fullscreen(_GLFWwindow *window, bool on) {
if (_glfw.x11.NET_WM_STATE && _glfw.x11.NET_WM_STATE_FULLSCREEN) {
sendEventToWM(window,
@@ -2646,7 +2646,7 @@ void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity)
PropModeReplace, (unsigned char*) &value, 1);
}
static inline unsigned
static unsigned
dispatch_x11_queued_events(int num_events) {
unsigned dispatched = num_events > 0 ? num_events : 0;
while (num_events-- > 0) {
@@ -3122,3 +3122,10 @@ GLFWAPI unsigned long long glfwDBusUserNotify(const char *app_name, const char*
GLFWAPI void glfwDBusSetUserNotificationHandler(GLFWDBusnotificationactivatedfun handler) {
glfw_dbus_set_user_notification_activated_handler(handler);
}
GLFWAPI int glfwSetX11LaunchCommand(GLFWwindow *handle, char **argv, int argc)
{
_GLFW_REQUIRE_INIT_OR_RETURN(0);
_GLFWwindow* window = (_GLFWwindow*) handle;
return XSetCommand(_glfw.x11.display, window->x11.handle, argv, argc);
}

8
glfw/xkb_glfw.c vendored
View File

@@ -490,7 +490,7 @@ load_compose_tables(_GLFWXKBData *xkb) {
xkb_compose_table_unref(compose_table);
}
static inline xkb_mod_mask_t
static xkb_mod_mask_t
active_unknown_modifiers(_GLFWXKBData *xkb, struct xkb_state *state) {
size_t i = 0;
xkb_mod_mask_t ans = 0;
@@ -577,7 +577,7 @@ glfw_xkb_should_repeat(_GLFWXKBData *xkb, xkb_keycode_t keycode) {
}
static inline xkb_keysym_t
static xkb_keysym_t
compose_symbol(struct xkb_compose_state *composeState, xkb_keysym_t sym, int *compose_completed, char *key_text, int n) {
*compose_completed = 0;
if (sym == XKB_KEY_NoSymbol || !composeState) return sym;
@@ -610,7 +610,7 @@ glfw_xkb_keysym_from_name(const char *name, bool case_sensitive) {
return (int)xkb_keysym_from_name(name, case_sensitive ? XKB_KEYSYM_NO_FLAGS : XKB_KEYSYM_CASE_INSENSITIVE);
}
static inline const char*
static const char*
format_mods(unsigned int mods) {
static char buf[128];
char *p = buf, *s;
@@ -632,7 +632,7 @@ format_mods(unsigned int mods) {
return buf;
}
static inline const char*
static const char*
format_xkb_mods(_GLFWXKBData *xkb, const char* name, xkb_mod_mask_t mods) {
static char buf[512];
char *p = buf, *s;

View File

@@ -3,47 +3,14 @@
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys
from typing import Iterable, List, Union
from typing import List
from kitty.key_encoding import KeyEvent
from . import subseq_matcher
from ..tui.handler import Handler
from ..tui.loop import Loop
def match(
input_data: Union[str, bytes, Iterable[Union[str, bytes]]],
query: str,
threads: int = 0,
positions: bool = False,
level1: str = '/',
level2: str = '-_0123456789',
level3: str = '.',
limit: int = 0,
mark_before: str = '',
mark_after: str = '',
delimiter: str = '\n'
) -> List[str]:
if isinstance(input_data, str):
idata = [x.encode('utf-8') for x in input_data.split(delimiter)]
elif isinstance(input_data, bytes):
idata = input_data.split(delimiter.encode('utf-8'))
else:
idata = [x.encode('utf-8') if isinstance(x, str) else x for x in input_data]
query = query.lower()
level1 = level1.lower()
level2 = level2.lower()
level3 = level3.lower()
data = subseq_matcher.match(
idata, (level1, level2, level3), query,
positions, limit, threads,
mark_before, mark_after, delimiter)
if data is None:
return []
return list(filter(None, data.split(delimiter or '\n')))
class ChooseHandler(Handler):
def initialize(self) -> None:

39
kittens/choose/match.py Normal file
View File

@@ -0,0 +1,39 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Iterable, List, Union
from . import subseq_matcher
def match(
input_data: Union[str, bytes, Iterable[Union[str, bytes]]],
query: str,
threads: int = 0,
positions: bool = False,
level1: str = '/',
level2: str = '-_0123456789',
level3: str = '.',
limit: int = 0,
mark_before: str = '',
mark_after: str = '',
delimiter: str = '\n'
) -> List[str]:
if isinstance(input_data, str):
idata = [x.encode('utf-8') for x in input_data.split(delimiter)]
elif isinstance(input_data, bytes):
idata = input_data.split(delimiter.encode('utf-8'))
else:
idata = [x.encode('utf-8') if isinstance(x, str) else x for x in input_data]
query = query.lower()
level1 = level1.lower()
level2 = level2.lower()
level3 = level3.lower()
data = subseq_matcher.match(
idata, (level1, level2, level3), query,
positions, limit, threads,
mark_before, mark_after, delimiter)
if data is None:
return []
return list(filter(None, data.split(delimiter or '\n')))

View File

@@ -14,7 +14,7 @@
#ifdef ISWINDOWS
#include <io.h>
#define STDOUT_FILENO 1
static inline ssize_t ms_write(int fd, const void* buf, size_t count) { return _write(fd, buf, (unsigned int)count); }
static ssize_t ms_write(int fd, const void* buf, size_t count) { return _write(fd, buf, (unsigned int)count); }
#define write ms_write
#else
#include <unistd.h>
@@ -24,7 +24,7 @@ static inline ssize_t ms_write(int fd, const void* buf, size_t count) { return _
#define FIELD(x, which) (((Candidate*)(x))->which)
static inline bool
static bool
ensure_space(GlobalData *global, size_t sz) {
if (global->output_sz < sz + global->output_pos || !global->output) {
size_t before = global->output_sz;
@@ -38,7 +38,7 @@ ensure_space(GlobalData *global, size_t sz) {
return true;
}
static inline void
static void
output_text(GlobalData *global, const text_t *data, size_t sz) {
if (ensure_space(global, sz)) {
memcpy(global->output + global->output_pos, data, sizeof(text_t) * sz);
@@ -66,10 +66,10 @@ static void
output_positions(GlobalData *global, len_t *positions, len_t num) {
wchar_t buf[128];
for (len_t i = 0; i < num; i++) {
int num = swprintf(buf, sizeof(buf)/sizeof(buf[0]), L"%u", positions[i]);
if (num > 0 && ensure_space(global, num + 1)) {
for (int i = 0; i < num; i++) global->output[global->output_pos++] = buf[i];
global->output[global->output_pos++] = (i == num - 1) ? ',' : ':';
int pnum = swprintf(buf, arraysz(buf), L"%u", positions[i]);
if (pnum > 0 && ensure_space(global, pnum + 1)) {
for (int k = 0; k < pnum; k++) global->output[global->output_pos++] = buf[k];
global->output[global->output_pos++] = (i == num - 1) ? ':' : ',';
}
}
}

View File

@@ -59,7 +59,7 @@ free_workspace(void *v) {
return NULL;
}
static inline bool
static bool
has_char(text_t *text, len_t sz, text_t ch) {
for(len_t i = 0; i < sz; i++) {
if(text[i] == ch) return true;
@@ -67,7 +67,7 @@ has_char(text_t *text, len_t sz, text_t ch) {
return false;
}
static inline uint8_t
static uint8_t
level_factor_for(text_t current, text_t last, WorkSpace *w) {
text_t lch = LOWERCASE(last);
if (has_char(w->level1, w->level1_len, lch)) return 90;
@@ -101,7 +101,7 @@ init_workspace(WorkSpace *w, text_t *haystack, len_t haystack_len) {
}
static inline bool
static bool
has_atleast_one_match(WorkSpace *w) {
int p = -1;
bool found;
@@ -118,7 +118,7 @@ has_atleast_one_match(WorkSpace *w) {
#define POSITION(x) w->positions[x][w->address[x]]
static inline bool
static bool
increment_address(WorkSpace *w) {
len_t pos = w->needle_len - 1;
while(true) {
@@ -130,7 +130,7 @@ increment_address(WorkSpace *w) {
return false;
}
static inline bool
static bool
address_is_monotonic(WorkSpace *w) {
// Check if the character positions pointed to by the current address are monotonic
for (len_t i = 1; i < w->needle_len; i++) {
@@ -139,7 +139,7 @@ address_is_monotonic(WorkSpace *w) {
return true;
}
static inline double
static double
calc_score(WorkSpace *w) {
double ans = 0;
len_t distance, pos;

View File

@@ -19,6 +19,7 @@ class Clipboard(Handler):
self.args = args
self.clipboard_contents: Optional[str] = None
self.data_to_send = data_to_send
self.quit_on_write = False
def initialize(self) -> None:
if self.data_to_send is not None:
@@ -30,10 +31,14 @@ class Clipboard(Handler):
self.print('\x1bP+q544e\x1b\\', end='')
self.print('Waiting for completion...')
return
self.quit_loop(0)
self.quit_on_write = True
return
self.cmd.request_from_clipboard(self.args.use_primary)
def on_writing_finished(self) -> None:
if self.quit_on_write:
self.quit_loop(0)
def on_clipboard_response(self, text: str, from_primary: bool = False) -> None:
self.clipboard_contents = text
self.quit_loop(0)

View File

@@ -1 +1 @@
See https://sw.kovidgoyal.net/kitty/kittens/diff.html
See https://sw.kovidgoyal.net/kitty/kittens/diff/

View File

@@ -155,7 +155,7 @@ def sanitize(text: str) -> str:
@lru_cache(maxsize=1024)
def mime_type_for_path(path: str) -> str:
return guess_type(path) or 'application/octet-stream'
return guess_type(path, allow_filesystem_access=True) or 'application/octet-stream'
@lru_cache(maxsize=1024)

View File

@@ -72,8 +72,11 @@ class Options:
def __init__(self, options_dict: typing.Optional[typing.Dict[str, typing.Any]] = None) -> None:
if options_dict is not None:
null = object()
for key in option_names:
setattr(self, key, options_dict[key])
val = options_dict.get(key, null)
if val is not null:
setattr(self, key, val)
@property
def _fields(self) -> typing.Tuple[str, ...]:

View File

@@ -41,7 +41,7 @@ typedef struct {
static const Segment EMPTY_SEGMENT = { .current_pos = UINT_MAX };
static inline bool
static bool
convert_segment(PyObject *highlight, Segment *dest) {
PyObject *val = NULL;
#define I
@@ -62,7 +62,7 @@ convert_segment(PyObject *highlight, Segment *dest) {
return true;
}
static inline bool
static bool
next_segment(SegmentPointer *s, PyObject *highlights) {
if (s->pos < s->num) {
if (!convert_segment(PyList_GET_ITEM(highlights, s->pos), &s->sg)) return false;
@@ -71,28 +71,48 @@ next_segment(SegmentPointer *s, PyObject *highlights) {
return true;
}
static inline bool
insert_code(PyObject *code, Py_UCS4 *buf, size_t bufsz, unsigned int *buf_pos) {
unsigned int csz = PyUnicode_GET_LENGTH(code);
if (*buf_pos + csz >= bufsz) return false;
for (unsigned int s = 0; s < csz; s++) buf[(*buf_pos)++] = PyUnicode_READ(PyUnicode_KIND(code), PyUnicode_DATA(code), s);
typedef struct LineBuffer {
Py_UCS4 *buf;
size_t pos, capacity;
} LineBuffer;
static bool
ensure_space(LineBuffer *b, size_t num) {
if (b->pos + num >= b->capacity) {
size_t new_cap = MAX(b->capacity * 2, 4096u);
new_cap = MAX(b->pos + num + 1024u, new_cap);
b->buf = realloc(b->buf, new_cap * sizeof(b->buf[0]));
if (!b->buf) { PyErr_NoMemory(); return false; }
b->capacity = new_cap;
}
return true;
}
static inline bool
add_line(Segment *bg_segment, Segment *fg_segment, Py_UCS4 *buf, size_t bufsz, unsigned int *buf_pos, PyObject *ans) {
bool bg_is_active = bg_segment->current_pos == bg_segment->end_pos, fg_is_active = fg_segment->current_pos == fg_segment->end_pos;
if (bg_is_active) { if(!insert_code(bg_segment->end_code, buf, bufsz, buf_pos)) return false; }
if (fg_is_active) { if(!insert_code(fg_segment->end_code, buf, bufsz, buf_pos)) return false; }
PyObject *wl = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buf, *buf_pos);
if (!wl) return false;
int ret = PyList_Append(ans, wl); Py_DECREF(wl); if (ret != 0) return false;
*buf_pos = 0;
if (bg_is_active) { if(!insert_code(bg_segment->start_code, buf, bufsz, buf_pos)) return false; }
if (fg_is_active) { if(!insert_code(fg_segment->start_code, buf, bufsz, buf_pos)) return false; }
static bool
insert_code(PyObject *code, LineBuffer *b) {
unsigned int csz = PyUnicode_GET_LENGTH(code);
if (!ensure_space(b, csz)) return false;
for (unsigned int s = 0; s < csz; s++) b->buf[b->pos++] = PyUnicode_READ(PyUnicode_KIND(code), PyUnicode_DATA(code), s);
return true;
}
static bool
add_line(Segment *bg_segment, Segment *fg_segment, LineBuffer *b, PyObject *ans) {
bool bg_is_active = bg_segment->current_pos == bg_segment->end_pos, fg_is_active = fg_segment->current_pos == fg_segment->end_pos;
if (bg_is_active) { if(!insert_code(bg_segment->end_code, b)) return false; }
if (fg_is_active) { if(!insert_code(fg_segment->end_code, b)) return false; }
PyObject *wl = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, b->buf, b->pos);
if (!wl) return false;
int ret = PyList_Append(ans, wl); Py_DECREF(wl); if (ret != 0) return false;
b->pos = 0;
if (bg_is_active) { if(!insert_code(bg_segment->start_code, b)) return false; }
if (fg_is_active) { if(!insert_code(fg_segment->start_code, b)) return false; }
return true;
}
static LineBuffer b;
static PyObject*
split_with_highlights(PyObject *self UNUSED, PyObject *args) {
PyObject *line, *truncate_points_py, *fg_highlights, *bg_highlight;
@@ -106,19 +126,19 @@ split_with_highlights(PyObject *self UNUSED, PyObject *args) {
}
SegmentPointer fg_segment = { .sg = EMPTY_SEGMENT, .num = PyList_GET_SIZE(fg_highlights)}, bg_segment = { .sg = EMPTY_SEGMENT };
if (bg_highlight != Py_None) { if (!convert_segment(bg_highlight, &bg_segment.sg)) { Py_CLEAR(ans); return NULL; }; bg_segment.num = 1; }
#define CHECK_CALL(func, ...) if (!func(__VA_ARGS__)) { Py_CLEAR(ans); if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "line too long"); return NULL; }
#define CHECK_CALL(func, ...) if (!func(__VA_ARGS__)) { Py_CLEAR(ans); if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "unknown error while processing line"); return NULL; }
CHECK_CALL(next_segment, &fg_segment, fg_highlights);
#define NEXT_TRUNCATE_POINT truncate_point = (truncate_pos < num_truncate_pts) ? truncate_points[truncate_pos++] : UINT_MAX
NEXT_TRUNCATE_POINT;
#define INSERT_CODE(x) { CHECK_CALL(insert_code, x, buf, arraysz(buf), &buf_pos); }
#define INSERT_CODE(x) { CHECK_CALL(insert_code, x, &b); }
#define ADD_LINE CHECK_CALL(add_line, &bg_segment.sg, &fg_segment.sg, buf, arraysz(buf), &buf_pos, ans);
#define ADD_LINE CHECK_CALL(add_line, &bg_segment.sg, &fg_segment.sg, &b, ans);
#define ADD_CHAR(x) { \
buf[buf_pos++] = x; \
if (buf_pos >= arraysz(buf)) { Py_CLEAR(ans); PyErr_SetString(PyExc_ValueError, "line too long"); return NULL; } \
if (!ensure_space(&b, 1)) { Py_CLEAR(ans); return NULL; } \
b.buf[b.pos++] = x; \
}
#define CHECK_SEGMENT(sgp, is_fg) { \
if (i == sgp.sg.current_pos) { \
@@ -137,15 +157,15 @@ split_with_highlights(PyObject *self UNUSED, PyObject *args) {
}
const unsigned int line_sz = PyUnicode_GET_LENGTH(line);
static Py_UCS4 buf[4096];
unsigned int i = 0, buf_pos = 0;
b.pos = 0;
unsigned int i = 0;
for (; i < line_sz; i++) {
if (i == truncate_point) { ADD_LINE; NEXT_TRUNCATE_POINT; }
CHECK_SEGMENT(bg_segment, false);
CHECK_SEGMENT(fg_segment, true)
ADD_CHAR(PyUnicode_READ(PyUnicode_KIND(line), PyUnicode_DATA(line), i));
}
if (buf_pos) ADD_LINE;
if (b.pos) ADD_LINE;
return ans;
#undef INSERT_CODE
#undef CHECK_SEGMENT
@@ -155,6 +175,11 @@ split_with_highlights(PyObject *self UNUSED, PyObject *args) {
#undef NEXT_TRUNCATE_POINT
}
static void
free_resources(void) {
free(b.buf); b.buf = NULL; b.capacity = 0; b.pos = 0;
}
static PyMethodDef module_methods[] = {
{"changed_center", (PyCFunction)changed_center, METH_VARARGS, ""},
{"split_with_highlights", (PyCFunction)split_with_highlights, METH_VARARGS, ""},
@@ -175,5 +200,6 @@ PyInit_diff_speedup(void) {
m = PyModule_Create(&module);
if (m == NULL) return NULL;
Py_AtExit(free_resources);
return m;
}

View File

@@ -16,6 +16,7 @@ from typing import (
from kitty.cli import parse_args
from kitty.cli_stub import HintsCLIOptions
from kitty.constants import website_url
from kitty.fast_data_types import set_clipboard_string
from kitty.key_encoding import KeyEvent
from kitty.typing import BossType, KittyCommonOpts
@@ -94,6 +95,11 @@ def highlight_mark(m: Mark, text: str, current_input: str, alphabet: str, colors
)
def debug(*a: Any, **kw: Any) -> None:
from ..tui.loop import debug as d
d(*a, **kw)
def render(text: str, current_input: str, all_marks: Sequence[Mark], ignore_mark_indices: Set[int], alphabet: str, colors: Dict[str, str]) -> str:
for mark in reversed(all_marks):
if mark.index in ignore_mark_indices:
@@ -102,8 +108,7 @@ def render(text: str, current_input: str, all_marks: Sequence[Mark], ignore_mark
text = text[:mark.start] + mtext + text[mark.end:]
text = text.replace('\0', '')
return text.replace('\n', '\r\n').rstrip()
return re.sub('[\r\n]', '\r\n', text).rstrip()
class Hints(Handler):
@@ -306,7 +311,7 @@ def mark(pattern: str, post_processors: Iterable[PostprocessorFunc], text: str,
except InvalidMatch:
continue
mark_text = text[s:e].replace('\n', '').replace('\0', '')
mark_text = re.sub('[\r\n\0]', '', text[s:e])
yield Mark(idx, s, e, mark_text, groupdict)
@@ -342,12 +347,12 @@ def functions_for(args: HintsCLIOptions) -> Tuple[str, List[PostprocessorFunc]]:
)
post_processors.append(url)
elif args.type == 'path':
pattern = r'(?:\S*/\S+)|(?:\S+[.][a-zA-Z0-9]{2,7})'
pattern = r'(?:\S*?/[\r\S]+)|(?:\S[\r\S]*\.[a-zA-Z0-9\r]{2,7})'
post_processors.extend((brackets, quotes))
elif args.type == 'line':
pattern = '(?m)^\\s*(.+)[\\s\0]*$'
elif args.type == 'hash':
pattern = '[0-9a-f]{7,128}'
pattern = '[0-9a-f][0-9a-f\r]{6,127}'
elif args.type == 'ip':
pattern = (
# # IPv4 with no validation
@@ -370,16 +375,22 @@ def functions_for(args: HintsCLIOptions) -> Tuple[str, List[PostprocessorFunc]]:
def convert_text(text: str, cols: int) -> str:
lines: List[str] = []
empty_line = '\0' * cols
empty_line = '\0' * cols + '\n'
for full_line in text.split('\n'):
if full_line:
if not full_line.rstrip('\r'): # empty lines
lines.extend(repeat(empty_line, len(full_line)))
continue
appended = False
for line in full_line.split('\r'):
if line:
lines.append(line.ljust(cols, '\0'))
return '\n'.join(lines)
lines.append('\r')
appended = True
if appended:
lines[-1] = '\n'
rstripped = re.sub('[\r\n]+$', '', ''.join(lines))
return rstripped
def parse_input(text: str) -> str:
@@ -542,10 +553,12 @@ choices=self,window,tab,os_window,background
Where to perform the action on matched errors. :code:`self` means the current
window, :code:`window` a new kitty window, :code:`tab` a new tab,
:code:`os_window` a new OS window and :code:`background` run in the background.
The action to perform on the matched errors. The actual action is whatever
arguments are provided to the kitten, for example: :code:`kitty + kitten hints
--type=linenum --linenum-action=tab vim +{line} {path}` will open the matched
path at the matched line number in vim in a new kitty tab.
The actual action is whatever arguments are provided to the kitten, for
example:
:code:`kitty + kitten hints --type=linenum --linenum-action=tab vim +{line} {path}`
will open the matched path at the matched line number in vim in
a new kitty tab. Note that only when using :code:`self` are the special values for
:option:`kitty +kitten hints --program` to copy/paste the text respected.
--url-prefixes
@@ -630,7 +643,7 @@ The foreground color for text pointed to by the hints
--customize-processing
Name of a python file in the kitty config directory which will be imported to provide
custom implementations for pattern finding and performing actions
on selected matches. See https://sw.kovidgoyal.net/kitty/kittens/hints.html
on selected matches. See {hints_url}
for details. You can also specify absolute paths to load the script from elsewhere.
@@ -639,7 +652,8 @@ The window title for the hints window, default title is selected based on
the type of text being hinted.
'''.format(
default_regex=DEFAULT_REGEX,
line='{{line}}', path='{{path}}'
line='{{line}}', path='{{path}}',
hints_url=website_url('kittens/hints'),
).format
help_text = 'Select text from the screen using the keyboard. Defaults to searching for URLs.'
usage = ''
@@ -693,9 +707,19 @@ def linenum_handle_result(args: List[str], data: Dict[str, Any], target_window_i
if action == 'self':
if w is not None:
import shlex
text = ' '.join(shlex.quote(arg) for arg in cmd)
w.paste_bytes(text + '\r')
is_copy_action = cmd[0] in ('-', '@', '*')
if is_copy_action:
text = ' '.join(cmd[1:])
if cmd[0] == '-':
w.paste_bytes(text)
elif cmd[0] == '@':
set_clipboard_string(text)
elif cmd[0] == '*':
set_primary_selection(text)
else:
import shlex
text = ' '.join(shlex.quote(arg) for arg in cmd)
w.paste_bytes(text + '\r')
elif action == 'background':
import subprocess
subprocess.Popen(cmd, cwd=data['cwd'])

View File

@@ -1 +1,3 @@
url_delimiters = '\x00-\x09\x0b-\x20\x7f-\xa0\xad\u0600-\u0605\u061c\u06dd\u070f\u08e2\u1680\u180e\u2000-\u200f\u2028-\u202f\u205f-\u2064\u2066-\u206f\u3000\ud800-\uf8ff\ufeff\ufff9-\ufffb\U000110bd\U000110cd\U00013430-\U00013438\U0001bca0-\U0001bca3\U0001d173-\U0001d17a\U000e0001\U000e0020-\U000e007f\U000f0000-\U000ffffd\U00100000-\U0010fffd' # noqa
# generated by gen-wcwidth.py, do not edit
url_delimiters = '\x00-\x09\x0b-\x0c\x0e-\x20\x7f-\xa0\xad\u0600-\u0605\u061c\u06dd\u070f\u08e2\u1680\u180e\u2000-\u200f\u2028-\u202f\u205f-\u2064\u2066-\u206f\u3000\ud800-\uf8ff\ufeff\ufff9-\ufffb\U000110bd\U000110cd\U00013430-\U00013438\U0001bca0-\U0001bca3\U0001d173-\U0001d17a\U000e0001\U000e0020-\U000e007f\U000f0000-\U000ffffd\U00100000-\U0010fffd' # noqa

View File

@@ -29,7 +29,7 @@ def main() -> None:
write: Callable[[bytes], None] = cast(Callable[[bytes], None], sys.stdout.buffer.write)
sgr_pat = re.compile(br'\x1b\[.*?m')
osc_pat = re.compile(b'\x1b\\].*?\x1b\\\\')
num_pat = re.compile(b'^(\\d+):')
num_pat = re.compile(br'^(\d+)[:-]')
in_result: bytes = b''
hostname = socket.gethostname().encode('utf-8')
@@ -46,6 +46,8 @@ def main() -> None:
m = num_pat.match(clean_line)
if m is not None:
write_hyperlink(write, in_result, line, frag=m.group(1))
else:
write(line)
else:
if line.strip():
path = quote_from_bytes(os.path.abspath(clean_line)).encode('utf-8')
@@ -55,8 +57,9 @@ def main() -> None:
write(line)
except KeyboardInterrupt:
p.send_signal(signal.SIGINT)
p.stdout.close()
except EOFError:
pass
finally:
p.stdout.close()
raise SystemExit(p.wait())

View File

@@ -4,22 +4,27 @@
import re
import sys
from binascii import unhexlify, hexlify
from binascii import hexlify, unhexlify
from contextlib import suppress
from typing import Dict, Iterable, List, Type
from typing import Dict, Iterable, List, Type, Optional
from kitty.cli import parse_args
from kitty.cli_stub import QueryTerminalCLIOptions
from kitty.constants import appname
from kitty.utils import TTYIO
from kitty.constants import appname, str_version
from kitty.options.types import Options
from kitty.terminfo import names
from kitty.utils import TTYIO
class Query:
name: str = ''
ans: str = ''
query_name: str = ''
help_text: str = ''
override_query_name: str = ''
@property
def query_name(self) -> str:
return self.override_query_name or f'kitty-query-{self.name}'
def __init__(self) -> None:
self.encoded_query_name = hexlify(self.query_name.encode('utf-8')).decode('ascii')
@@ -45,6 +50,10 @@ class Query:
def output_line(self) -> str:
return self.ans
@staticmethod
def get_result(opts: Options) -> str:
raise NotImplementedError()
all_queries: Dict[str, Type[Query]] = {}
@@ -57,22 +66,108 @@ def query(cls: Type[Query]) -> Type[Query]:
@query
class TerminalName(Query):
name: str = 'name'
query_name: str = 'TN'
override_query_name: str = 'name'
help_text: str = f'Terminal name ({names[0]})'
@staticmethod
def get_result(opts: Options) -> str:
return appname
@query
class TerminalVersion(Query):
name: str = 'version'
query_name: str = 'kitty-query-version'
help_text: str = 'Terminal version, for e.g.: 0.19.2'
@staticmethod
def get_result(opts: Options) -> str:
return str_version
@query
class AllowHyperlinks(Query):
name: str = 'allow_hyperlinks'
query_name: str = 'kitty-query-allow_hyperlinks'
help_text: str = 'yes, no or ask'
help_text: str = 'The :opt:`setting <allow_hyperlinks>` for allowing hyperlinks can be yes, no or ask'
@staticmethod
def get_result(opts: Options) -> str:
return 'ask' if opts.allow_hyperlinks == 0b11 else ('yes' if opts.allow_hyperlinks else 'no')
@query
class FontFamily(Query):
name: str = 'font_family'
help_text: str = 'The current font\'s PostScript name'
@staticmethod
def get_result(opts: Options) -> str:
from kitty.fast_data_types import current_fonts
cf = current_fonts()
return str(cf['medium'].display_name())
@query
class BoldFont(Query):
name: str = 'bold_font'
help_text: str = 'The current bold font\'s PostScript name'
@staticmethod
def get_result(opts: Options) -> str:
from kitty.fast_data_types import current_fonts
cf = current_fonts()
return str(cf['bold'].display_name())
@query
class ItalicFont(Query):
name: str = 'italic_font'
help_text: str = 'The current italic font\'s PostScript name'
@staticmethod
def get_result(opts: Options) -> str:
from kitty.fast_data_types import current_fonts
cf = current_fonts()
return str(cf['italic'].display_name())
@query
class BiFont(Query):
name: str = 'bold_italic_font'
help_text: str = 'The current bold-italic font\'s PostScript name'
@staticmethod
def get_result(opts: Options) -> str:
from kitty.fast_data_types import current_fonts
cf = current_fonts()
return str(cf['bi'].display_name())
@query
class FontSize(Query):
name: str = 'font_size'
help_text: str = 'The current overall font size (individual windows can have different per window font sizes)'
@staticmethod
def get_result(opts: Options) -> str:
return f'{opts.font_size:g}'
@query
class ClipboardControl(Query):
name: str = 'clipboard_control'
help_text: str = 'The :opt:`setting <clipboard_control>` for allowing reads/writes to/from the clipboard'
@staticmethod
def get_result(opts: Options) -> str:
return ' '.join(opts.clipboard_control)
def get_result(name: str) -> Optional[str]:
from kitty.fast_data_types import get_options
q = all_queries.get(name)
if q is None:
return None
return q.get_result(get_options())
def do_queries(queries: Iterable, cli_opts: QueryTerminalCLIOptions) -> Dict[str, str]:
@@ -124,11 +219,12 @@ Note that when calling this from another program, be very
careful not to perform any I/O on the terminal device
until the kitten exits.
Available queries are::
Available queries are:
{}
'''.format(' ' + '\n '.join(
f'{name}: {c.help_text}' for name, c in all_queries.items()))
'''.format('\n'.join(
f'``{name}``\n {c.help_text}\n' for name, c in all_queries.items()))
usage = '[query1 query2 ...]'

View File

@@ -138,7 +138,6 @@ class ControlMaster:
).wait()
if self.tdir:
shutil.rmtree(self.tdir)
return True
@property
def is_alive(self) -> bool:
@@ -286,6 +285,7 @@ def handle_action(action: str, cli_opts: RemoteFileCLIOptions) -> Result:
show_error('Failed to copy file from remote machine')
elif action == 'edit':
print('Editing', cli_opts.path, 'from', cli_opts.hostname)
editor = get_editor()
with ControlMaster(conn_data, remote_path, cli_opts) as master:
if not master.check_hostname_matches():
return None
@@ -294,7 +294,6 @@ def handle_action(action: str, cli_opts: RemoteFileCLIOptions) -> Result:
return None
mtime = os.path.getmtime(master.dest)
print(reset_terminal(), end='', flush=True)
editor = get_editor()
editor_process = subprocess.Popen(editor + [master.dest])
while editor_process.poll() is None:
time.sleep(0.1)

View File

@@ -6,8 +6,9 @@
import importlib
import os
import sys
from contextlib import contextmanager
from functools import partial
from typing import Any, Dict, FrozenSet, List, TYPE_CHECKING, cast
from typing import TYPE_CHECKING, Any, Dict, FrozenSet, Generator, List, cast
from kitty.types import run_once
@@ -19,7 +20,10 @@ else:
def resolved_kitten(k: str) -> str:
return aliases.get(k, k).replace('-', '_')
ans = aliases.get(k, k)
head, tail = os.path.split(ans)
tail = tail.replace('-', '_')
return os.path.join(head, tail)
def path_to_custom_kitten(config_dir: str, kitten: str) -> str:
@@ -30,21 +34,29 @@ def path_to_custom_kitten(config_dir: str, kitten: str) -> str:
return path
@contextmanager
def preserve_sys_path() -> Generator[None, None, None]:
orig = sys.path[:]
try:
yield
finally:
if sys.path != orig:
del sys.path[:]
sys.path.extend(orig)
def import_kitten_main_module(config_dir: str, kitten: str) -> Dict[str, Any]:
if kitten.endswith('.py'):
path_modified = False
path = path_to_custom_kitten(config_dir, kitten)
if os.path.dirname(path):
sys.path.insert(0, os.path.dirname(path))
path_modified = True
with open(path) as f:
src = f.read()
code = compile(src, path, 'exec')
g = {'__name__': 'kitten'}
exec(code, g)
hr = g.get('handle_result', lambda *a, **kw: None)
if path_modified:
del sys.path[0]
with preserve_sys_path():
path = path_to_custom_kitten(config_dir, kitten)
if os.path.dirname(path):
sys.path.insert(0, os.path.dirname(path))
with open(path) as f:
src = f.read()
code = compile(src, path, 'exec')
g = {'__name__': 'kitten'}
exec(code, g)
hr = g.get('handle_result', lambda *a, **kw: None)
return {'start': g['main'], 'end': hr}
kitten = resolved_kitten(kitten)
@@ -75,14 +87,14 @@ def launch(args: List[str]) -> None:
del args[:2]
args = [kitten] + args
os.environ['KITTY_CONFIG_DIRECTORY'] = config_dir
from kittens.tui.operations import clear_screen, reset_mode
from kittens.tui.operations import clear_screen, reset_mode, Mode
set_debug(kitten)
m = import_kitten_main_module(config_dir, kitten)
try:
result = m['start'](args)
finally:
sys.stdin = sys.__stdin__
print(reset_mode('ALTERNATE_SCREEN') + clear_screen(), end='')
print(reset_mode(Mode.ALTERNATE_SCREEN) + clear_screen(), end='')
if result is not None:
import json
data = json.dumps(result)
@@ -155,6 +167,14 @@ def get_kitten_cli_docs(kitten: str) -> Any:
return ans
def get_kitten_completer(kitten: str) -> Any:
run_kitten(kitten, run_name='__completer__')
ans = getattr(sys, 'kitten_completer', None)
if ans is not None:
delattr(sys, 'kitten_completer')
return ans
def get_kitten_conf_docs(kitten: str) -> Definition:
setattr(sys, 'options_definition', None)
run_kitten(kitten, run_name='__conf__')

348
kittens/ssh/completion.py Normal file
View File

@@ -0,0 +1,348 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import subprocess
from typing import Callable, Dict, Iterable, Iterator, Sequence, Tuple
from kitty.complete import Completions, complete_files_and_dirs, debug
from kitty.types import run_once
debug
def lines_from_file(path: str) -> Iterator[str]:
try:
f = open(os.path.expanduser(path))
except OSError:
pass
else:
yield from f
def lines_from_command(*cmd: str) -> Iterator[str]:
try:
output = subprocess.check_output(cmd).decode('utf-8')
except Exception:
return
yield from output.splitlines()
def parts_yielder(lines: Iterable[str], pfilter: Callable[[str], Iterator[str]]) -> Iterator[str]:
for line in lines:
yield from pfilter(line)
def hosts_from_config_lines(line: str) -> Iterator[str]:
parts = line.strip().split()
if len(parts) > 1 and parts[0] == 'Host':
yield parts[1]
def hosts_from_known_hosts(line: str) -> Iterator[str]:
parts = line.strip().split()
if parts:
yield re.sub(r':\d+$', '', parts[0])
def hosts_from_hosts(line: str) -> Iterator[str]:
line = line.strip()
if not line.startswith('#'):
parts = line.split()
if parts:
yield parts[0]
if len(parts) > 1:
yield parts[1]
if len(parts) > 2:
yield parts[2]
def iter_known_hosts() -> Iterator[str]:
yield from parts_yielder(lines_from_file('~/.ssh/config'), hosts_from_config_lines)
yield from parts_yielder(lines_from_file('~/.ssh/known_hosts'), hosts_from_known_hosts)
yield from parts_yielder(lines_from_file('/etc/ssh/ssh_known_hosts'), hosts_from_known_hosts)
yield from parts_yielder(lines_from_file('/etc/hosts'), hosts_from_hosts)
yield from parts_yielder(lines_from_command('getent', 'hosts'), hosts_from_hosts)
@run_once
def known_hosts() -> Tuple[str, ...]:
return tuple(sorted(filter(lambda x: '*' not in x and '[' not in x, set(iter_known_hosts()))))
@run_once
def ssh_options() -> Dict[str, str]:
stderr = subprocess.Popen(['ssh'], stderr=subprocess.PIPE).stderr
assert stderr is not None
raw = stderr.read().decode('utf-8')
ans: Dict[str, str] = {}
pos = 0
while True:
pos = raw.find('[', pos)
if pos < 0:
break
num = 1
epos = pos
while num > 0:
epos += 1
if raw[epos] not in '[]':
continue
num += 1 if raw[epos] == '[' else -1
q = raw[pos+1:epos]
pos = epos
if len(q) < 2 or q[0] != '-':
continue
if ' ' in q:
opt, desc = q.split(' ', 1)
ans[opt[1:]] = desc
else:
ans.update(dict.fromkeys(q[1:], ''))
return ans
# option help {{{
@run_once
def option_help_map() -> Dict[str, str]:
ans: Dict[str, str] = {}
lines = '''
-4 -- force ssh to use IPv4 addresses only
-6 -- force ssh to use IPv6 addresses only
-a -- disable forwarding of authentication agent connection
-A -- enable forwarding of the authentication agent connection
-B -- bind to specified interface before attempting to connect
-b -- specify interface to transmit on
-C -- compress data
-c -- select encryption cipher
-D -- specify a dynamic port forwarding
-E -- append log output to file instead of stderr
-e -- set escape character
-f -- go to background
-F -- specify alternate config file
-g -- allow remote hosts to connect to local forwarded ports
-G -- output configuration and exit
-i -- select identity file
-I -- specify smartcard device
-J -- connect via a jump host
-k -- disable forwarding of GSSAPI credentials
-K -- enable GSSAPI-based authentication and forwarding
-L -- specify local port forwarding
-l -- specify login name
-M -- master mode for connection sharing
-m -- specify mac algorithms
-N -- don't execute a remote command
-n -- redirect stdin from /dev/null
-O -- control an active connection multiplexing master process
-o -- specify extra options
-p -- specify port on remote host
-P -- use non privileged port
-Q -- query parameters
-q -- quiet operation
-R -- specify remote port forwarding
-s -- invoke subsystem
-S -- specify location of control socket for connection sharing
-T -- disable pseudo-tty allocation
-t -- force pseudo-tty allocation
-V -- show version number
-v -- verbose mode (multiple increase verbosity, up to 3)
-W -- forward standard input and output to host
-w -- request tunnel device forwarding
-x -- disable X11 forwarding
-X -- enable (untrusted) X11 forwarding
-Y -- enable trusted X11 forwarding
-y -- send log info via syslog instead of stderr
'''.splitlines()
for line in lines:
line = line.strip()
if line:
parts = line.split(maxsplit=2)
ans[parts[0]] = parts[2]
return ans
# }}}
# option names {{{
@run_once
def option_names() -> Tuple[str, ...]:
return tuple(filter(None, (
line.strip() for line in '''
AddKeysToAgent
AddressFamily
BatchMode
BindAddress
CanonicalDomains
CanonicalizeFallbackLocal
CanonicalizeHostname
CanonicalizeMaxDots
CanonicalizePermittedCNAMEs
CASignatureAlgorithms
CertificateFile
ChallengeResponseAuthentication
CheckHostIP
Ciphers
ClearAllForwardings
Compression
ConnectionAttempts
ConnectTimeout
ControlMaster
ControlPath
ControlPersist
DynamicForward
EscapeChar
ExitOnForwardFailure
FingerprintHash
ForwardAgent
ForwardX11
ForwardX11Timeout
ForwardX11Trusted
GatewayPorts
GlobalKnownHostsFile
GSSAPIAuthentication
GSSAPIDelegateCredentials
HashKnownHosts
Host
HostbasedAcceptedAlgorithms
HostbasedAuthentication
HostKeyAlgorithms
HostKeyAlias
Hostname
IdentitiesOnly
IdentityAgent
IdentityFile
IPQoS
KbdInteractiveAuthentication
KbdInteractiveDevices
KexAlgorithms
KnownHostsCommand
LocalCommand
LocalForward
LogLevel
MACs
Match
NoHostAuthenticationForLocalhost
NumberOfPasswordPrompts
PasswordAuthentication
PermitLocalCommand
PermitRemoteOpen
PKCS11Provider
Port
PreferredAuthentications
ProxyCommand
ProxyJump
ProxyUseFdpass
PubkeyAcceptedAlgorithms
PubkeyAuthentication
RekeyLimit
RemoteCommand
RemoteForward
RequestTTY
SendEnv
ServerAliveInterval
ServerAliveCountMax
SetEnv
StreamLocalBindMask
StreamLocalBindUnlink
StrictHostKeyChecking
TCPKeepAlive
Tunnel
TunnelDevice
UpdateHostKeys
User
UserKnownHostsFile
VerifyHostKeyDNS
VisualHostKey
XAuthLocation
'''.splitlines())))
# }}}
def complete_choices(ans: Completions, prefix: str, title: str, choices: Iterable[str], comma_separated: bool = False) -> None:
matches: Dict[str, str] = {}
word_transforms = {}
effective_prefix = prefix
hidden_prefix = ''
if comma_separated:
effective_prefix = prefix.split(',')[-1]
hidden_prefix = ','.join(prefix.split(',')[:-1])
if hidden_prefix:
hidden_prefix += ','
for q in choices:
if q.startswith(effective_prefix):
if comma_separated:
tq = q
q = hidden_prefix + q + ','
word_transforms[q] = tq
matches[q] = ''
ans.add_match_group(title, matches, trailing_space=not comma_separated, word_transforms=word_transforms)
def complete_q_choices(ans: Completions, prefix: str, title: str, key: str, comma_separated: bool) -> None:
choices = (line.strip() for line in lines_from_command('ssh', '-Q', key))
complete_choices(ans, prefix, title, choices, comma_separated)
def complete_arg(ans: Completions, option_flag: str, prefix: str = '') -> None:
options = ssh_options()
option_name = options.get(option_flag[1:])
if option_name.endswith('file') or option_name.endswith('path'):
return complete_files_and_dirs(ans, prefix, option_name)
choices = {
'mac_spec': ('MAC algorithm', 'mac', True),
'cipher_spec': ('encryption cipher', 'cipher', True),
'query_option': ('query option', 'help', False),
}
if option_name in choices:
return complete_q_choices(ans, prefix, *choices[option_name])
if option_name == 'destination':
return complete_destination(ans, prefix)
if option_name == 'ctl_cmd':
return complete_choices(ans, prefix, 'control command', ('check', 'forward', 'cancel', 'exit'))
if option_name == 'option':
matches = (x+'=' for x in option_names() if x.startswith(prefix))
word_transforms = {x+'=': x for x in option_names()}
ans.add_match_group('configure file option', matches, trailing_space=False, word_transforms=word_transforms)
def complete_destination(ans: Completions, prefix: str = '') -> None:
result = (k for k in known_hosts() if k.startswith(prefix))
ans.add_match_group('remote host name', result)
def complete_option(ans: Completions, prefix: str = '-') -> None:
hm = option_help_map()
if len(prefix) <= 1:
result = {k: v for k, v in hm.items() if k.startswith(prefix)}
ans.add_match_group('option', result)
else:
ans.add_match_group('option', {prefix: ''})
def complete(ans: Completions, words: Sequence[str], new_word: bool) -> None:
options = ssh_options()
expecting_arg = False
types = ['' for i in range(len(words))]
for i, word in enumerate(words):
if expecting_arg:
types[i] = 'arg'
expecting_arg = False
continue
if word.startswith('-'):
types[i] = 'option'
if len(word) == 2 and options.get(word[1]):
expecting_arg = True
continue
types[i] = 'destination'
break
if new_word:
if words:
if expecting_arg:
return complete_arg(ans, words[-1])
return complete_destination(ans)
if words:
if types[-1] == 'arg' and len(words) > 1:
return complete_arg(ans, words[-2], words[-1])
if types[-1] == 'destination':
return complete_destination(ans, words[-1])
if types[-1] == 'option':
return complete_option(ans, words[-1])

View File

@@ -3,12 +3,12 @@
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import shlex
import subprocess
import sys
from contextlib import suppress
from typing import List, NoReturn, Optional, Set, Tuple
from .completion import ssh_options, complete
from kitty.utils import SSHConnectionData
@@ -21,27 +21,83 @@ cat >$tmp << 'TERMEOF'
TERMINFO
TERMEOF
tic_out=$(tic -x -o ~/.terminfo $tmp 2>&1)
tic_out=$(tic -x -o $HOME/.terminfo $tmp 2>&1)
rc=$?
rm $tmp
if [ "$rc" != "0" ]; then echo "$tic_out"; exit 1; fi
if [ -z "$USER" ]; then export USER=$(whoami); fi
shell_name=$(basename $0)
export TERMINFO="$HOME/.terminfo"
login_shell=""
python=""
login_shell_is_ok() {
if [ -z "$login_shell" ] || [ ! -x "$login_shell" ]; then return 1; fi
case "$login_shell" in
*sh) return 0;
esac
return 1;
}
detect_python() {
python=$(command -v python3)
if [ -z "$python" ]; then python=$(command -v python2); fi
if [ -z "$python" ]; then python=python; fi
}
using_getent() {
cmd=$(command -v getent)
if [ -z "$cmd" ]; then return; fi
output=$($cmd passwd $USER 2>/dev/null)
if [ $? = 0 ]; then login_shell=$(echo $output | cut -d: -f7); fi
}
using_id() {
cmd=$(command -v id)
if [ -z "$cmd" ]; then return; fi
output=$($cmd -P $USER 2>/dev/null)
if [ $? = 0 ]; then login_shell=$(echo $output | cut -d: -f7); fi
}
using_passwd() {
cmd=$(command -v grep)
if [ -z "$cmd" ]; then return; fi
output=$($cmd "^$USER:" /etc/passwd 2>/dev/null)
if [ $? = 0 ]; then login_shell=$(echo $output | cut -d: -f7); fi
}
using_python() {
detect_python
if [ ! -x "$python" ]; then return; fi
output=$($python -c "import pwd, os; print(pwd.getpwuid(os.geteuid()).pw_shell)")
if [ $? = 0 ]; then login_shell=$output; fi
}
execute_with_python() {
detect_python
exec $python -c "import os; os.execl('$login_shell', '-' '$shell_name')"
}
die() { echo "$*" 1>&2 ; exit 1; }
using_getent
if ! login_shell_is_ok; then using_id; fi
if ! login_shell_is_ok; then using_python; fi
if ! login_shell_is_ok; then using_passwd; fi
if ! login_shell_is_ok; then die "Could not detect login shell"; fi
# If a command was passed to SSH execute it here
EXEC_CMD
# We need to pass the first argument to the executed program with a leading -
# to make sure the shell executes as a login shell. Note that not all shells
# support exec -a so we use the below to try to detect such shells
case "dash" in
*$shell_name*)
python=$(command -v python3)
if [ -z "$python" ]; then python=$(command -v python2); fi
if [ -z "$python" ]; then python=python; fi
exec $python -c "import os; os.execlp('$0', '-' '$shell_name')"
;;
esac
exec -a "-$shell_name" "$0"
shell_name=$(basename $login_shell)
if [ -z "$PIPESTATUS" ]; then
# the dash shell does not support exec -a and also does not define PIPESTATUS
execute_with_python
fi
exec -a "-$shell_name" $login_shell
'''
@@ -73,20 +129,15 @@ os.execlp(shell_path, shell_name)
def get_ssh_cli() -> Tuple[Set[str], Set[str]]:
other_ssh_args: List[str] = []
boolean_ssh_args: List[str] = []
stderr = subprocess.Popen(['ssh'], stderr=subprocess.PIPE).stderr
assert stderr is not None
raw = stderr.read().decode('utf-8')
for m in re.finditer(r'\[(.+?)\]', raw):
q = m.group(1)
if len(q) < 2 or q[0] != '-':
continue
if ' ' in q:
other_ssh_args.append(q[1])
other_ssh_args: Set[str] = set()
boolean_ssh_args: Set[str] = set()
for k, v in ssh_options().items():
k = '-' + k
if v:
other_ssh_args.add(k)
else:
boolean_ssh_args.extend(q[1:])
return set('-' + x for x in boolean_ssh_args), set('-' + x for x in other_ssh_args)
boolean_ssh_args.add(k)
return boolean_ssh_args, other_ssh_args
def get_connection_data(args: List[str]) -> Optional[SSHConnectionData]:
@@ -95,15 +146,20 @@ def get_connection_data(args: List[str]) -> Optional[SSHConnectionData]:
port: Optional[int] = None
expecting_port = False
expecting_option_val = False
expecting_hostname = False
for i, arg in enumerate(args):
if not found_ssh:
if os.path.basename(arg).lower() in ('ssh', 'ssh.exe'):
found_ssh = arg
continue
if expecting_hostname:
return SSHConnectionData(found_ssh, arg, port)
if arg.startswith('-') and not expecting_option_val:
if arg in boolean_ssh_args:
continue
if arg == '--':
expecting_hostname = True
if arg.startswith('-p'):
if arg[2:].isdigit():
with suppress(Exception):
@@ -124,6 +180,18 @@ def get_connection_data(args: List[str]) -> Optional[SSHConnectionData]:
return SSHConnectionData(found_ssh, arg, port)
class InvalidSSHArgs(ValueError):
def __init__(self, msg: str = ''):
super().__init__(msg)
self.err_msg = msg
def system_exit(self) -> None:
if self.err_msg:
print(self.err_msg, file=sys.stderr)
os.execlp('ssh', 'ssh')
def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
boolean_ssh_args, other_ssh_args = get_ssh_cli()
passthrough_args = {'-' + x for x in 'Nnf'}
@@ -131,11 +199,16 @@ def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
server_args: List[str] = []
expecting_option_val = False
passthrough = False
stop_option_processing = False
for arg in args:
if len(server_args) > 1:
if len(server_args) > 1 or stop_option_processing:
server_args.append(arg)
continue
if arg.startswith('-') and not expecting_option_val:
if arg == '--':
stop_option_processing = True
continue
# could be a multi-character option
all_args = arg[1:]
for i, arg in enumerate(all_args):
arg = '-' + arg
@@ -152,7 +225,7 @@ def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
else:
expecting_option_val = True
break
raise SystemExit('Unknown option: {}'.format(arg))
raise InvalidSSHArgs('unknown option -- {}'.format(arg[1:]))
continue
if expecting_option_val:
ssh_args.append(arg)
@@ -160,7 +233,7 @@ def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
continue
server_args.append(arg)
if not server_args:
raise SystemExit('Must specify server to connect to')
raise InvalidSSHArgs()
return ssh_args, server_args, passthrough
@@ -184,9 +257,9 @@ def get_posix_cmd(terminfo: str, remote_args: List[str]) -> List[str]:
# line 1129 of ssh.c and on the remote side sshd.c runs the
# concatenated command as shell -c cmd
args = [c.replace("'", """'"'"'""") for c in remote_args]
command_to_execute = "exec $0 -c '{}'".format(' '.join(args))
command_to_execute = "exec $login_shell -c '{}'".format(' '.join(args))
sh_script = sh_script.replace('EXEC_CMD', command_to_execute)
return [sh_script] + remote_args
return [f'sh -c {shlex.quote(sh_script)}']
def get_python_cmd(terminfo: str, command_to_execute: List[str]) -> List[str]:
@@ -204,13 +277,19 @@ def main(args: List[str]) -> NoReturn:
if args and args[0] == 'use-python':
args = args[1:]
use_posix = False
ssh_args, server_args, passthrough = parse_ssh_args(args)
try:
ssh_args, server_args, passthrough = parse_ssh_args(args)
except InvalidSSHArgs as e:
e.system_exit()
cmd = ['ssh'] + ssh_args
if passthrough:
cmd += server_args
else:
hostname, remote_args = server_args[0], server_args[1:]
cmd += ['-t', hostname]
if not remote_args:
cmd.append('-t')
cmd.append('--')
cmd.append(hostname)
terminfo = subprocess.check_output(['infocmp', '-a']).decode('utf-8')
f = get_posix_cmd if use_posix else get_python_cmd
cmd += f(terminfo, remote_args)
@@ -219,3 +298,5 @@ def main(args: List[str]) -> NoReturn:
if __name__ == '__main__':
main(sys.argv)
elif __name__ == '__completer__':
setattr(sys, 'kitten_completer', complete)

View File

View File

@@ -0,0 +1,387 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import datetime
import http
import json
import os
import re
import shutil
import signal
import tempfile
import zipfile
from contextlib import suppress
from typing import Any, Callable, Dict, Iterator, Match, Optional, Tuple, Union, Type
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from kitty.config import atomic_save, parse_config
from kitty.constants import cache_dir, config_dir
from kitty.options.types import Options as KittyOptions
from kitty.rgb import Color
from kitty.utils import reload_conf_in_all_kitties
from ..choose.match import match
MARK_BEFORE = '\033[33m'
MARK_AFTER = '\033[39m'
def patch_conf(raw: str, theme_name: str) -> str:
addition = f'# BEGIN_KITTY_THEME\n# {theme_name}\ninclude current-theme.conf\n# END_KITTY_THEME'
nraw, num = re.subn(r'^# BEGIN_KITTY_THEME.+?# END_KITTY_THEME', addition, raw, flags=re.MULTILINE | re.DOTALL)
if not num:
if raw:
raw += '\n\n'
nraw = raw + addition
# comment out all existing color definitions
color_conf_items = [f'color{i}' for i in range(256)] + list(filter(None, '''
foreground
background
selection_foreground
selection_background
cursor
cursor_text_color
url_color
active_border_color
inactive_border_color
bell_border_color
wayland_titlebar_color
macos_titlebar_color
active_tab_foreground
active_tab_background
inactive_tab_foreground
inactive_tab_background
tab_bar_background
mark1_foreground
mark1_background
mark2_foreground
mark2_background
mark3_foreground
mark3_background
'''.splitlines()))
pat = fr'^\s*({"|".join(color_conf_items)})\b'
return re.sub(pat, r'# \1', nraw, flags=re.MULTILINE)
def set_comment_in_zip_file(path: str, data: str) -> None:
with zipfile.ZipFile(path, 'a') as zf:
zf.comment = data.encode('utf-8')
class NoCacheFound(ValueError):
pass
def fetch_themes(
name: str = 'kitty-themes',
url: str = 'https://codeload.github.com/kovidgoyal/kitty-themes/zip/master',
cache_age: float = 1,
) -> str:
now = datetime.datetime.now(datetime.timezone.utc)
cache_age_delta = datetime.timedelta(days=cache_age)
class Metadata:
def __init__(self) -> None:
self.etag = ''
self.timestamp = now
def __str__(self) -> str:
return json.dumps({'etag': self.etag, 'timestamp': self.timestamp.isoformat()})
dest_path = os.path.join(cache_dir(), f'{name}.zip')
m = Metadata()
with suppress(Exception), zipfile.ZipFile(dest_path, 'r') as zf:
q = json.loads(zf.comment)
m.etag = str(q.get('etag') or '')
m.timestamp = datetime.datetime.fromisoformat(q['timestamp'])
if cache_age < 0 or (now - m.timestamp) < cache_age_delta:
return dest_path
if cache_age < 0:
raise NoCacheFound('No local themes cache found and negative cache age specified, aborting')
rq = Request(url)
m.timestamp = now
if m.etag:
rq.add_header('If-None-Match', m.etag)
try:
res = urlopen(rq, timeout=30)
except HTTPError as e:
if m.etag and e.code == http.HTTPStatus.NOT_MODIFIED:
set_comment_in_zip_file(dest_path, str(m))
return dest_path
raise
m.etag = res.headers.get('etag') or ''
needs_delete = False
try:
with tempfile.NamedTemporaryFile(suffix='-' + os.path.basename(dest_path), dir=os.path.dirname(dest_path), delete=False) as f:
needs_delete = True
shutil.copyfileobj(res, f)
f.flush()
set_comment_in_zip_file(f.name, str(m))
os.replace(f.name, dest_path)
needs_delete = False
finally:
if needs_delete:
os.unlink(f.name)
return dest_path
def zip_file_loader(path_to_zip: str, theme_file_name: str, file_name: str) -> Callable[[], str]:
name = os.path.join(os.path.dirname(theme_file_name), file_name)
def zip_loader() -> str:
with zipfile.ZipFile(path_to_zip, 'r') as zf, zf.open(name) as f:
return f.read().decode('utf-8')
return zip_loader
def theme_name_from_file_name(fname: str) -> str:
ans = fname.rsplit('.', 1)[0]
ans = ans.replace('_', ' ')
def camel_case(m: Match) -> str:
return str(m.group(1) + ' ' + m.group(2))
ans = re.sub(r'([a-z])([A-Z])', camel_case, ans)
return ' '.join(x.capitalize() for x in filter(None, ans.split()))
class LineParser:
def __init__(self) -> None:
self.in_metadata = False
self.in_blurb = False
self.keep_going = True
def __call__(self, line: str, ans: Dict[str, Any]) -> None:
is_block = line.startswith('## ')
if self.in_metadata and not is_block:
self.keep_going = False
return
if not self.in_metadata and is_block:
self.in_metadata = True
if not self.in_metadata:
return
line = line[3:]
if self.in_blurb:
ans['blurb'] += ' ' + line
return
try:
key, val = line.split(':', 1)
except Exception:
self.keep_going = False
return
key = key.strip().lower()
val = val.strip()
if val:
ans[key] = val
if key == 'blurb':
self.in_blurb = True
def parse_theme(fname: str, raw: str, exc_class: Type[BaseException] = SystemExit) -> Dict[str, Any]:
lines = raw.splitlines()
conf = parse_config(lines)
bg = conf.get('background', Color())
is_dark = max(bg) < 115
ans: Dict[str, Any] = {'name': theme_name_from_file_name(fname)}
parser = LineParser()
for i, line in enumerate(raw.splitlines()):
line = line.strip()
if not line:
continue
try:
parser(line, ans)
except Exception as e:
raise exc_class(
f'Failed to parse {fname} line {i+1} with error: {e}')
if not parser.keep_going:
break
if is_dark:
ans['is_dark'] = True
ans['num_settings'] = len(conf) - len(parse_config(()))
if ans['num_settings'] < 1 and fname != 'default.conf':
raise exc_class(f'The theme {fname} has no settings')
return ans
def update_theme_file(path: str) -> bool:
with open(path) as f:
raw = f.read()
td = parse_theme(os.path.basename(path), raw, exc_class=ValueError)
if 'upstream' not in td:
return False
nraw = urlopen(td['upstream']).read().decode('utf-8')
if raw == nraw:
return False
atomic_save(nraw.encode('utf-8'), path)
return True
class Theme:
name: str = ''
author: str = ''
license: str = ''
is_dark: bool = False
blurb: str = ''
num_settings: int = 0
def apply_dict(self, d: Dict[str, Any]) -> None:
self.name = str(d['name'])
for x in ('author', 'license', 'blurb'):
a = d.get(x)
if isinstance(a, str):
setattr(self, x, a)
for x in ('is_dark', 'num_settings'):
a = d.get(x)
if isinstance(a, int):
setattr(self, x, a)
def __init__(self, loader: Callable[[], str]):
self._loader = loader
self._raw: Optional[str] = None
self._opts: Optional[KittyOptions] = None
@property
def raw(self) -> str:
if self._raw is None:
self._raw = self._loader()
return self._raw
@property
def kitty_opts(self) -> KittyOptions:
if self._opts is None:
self._opts = KittyOptions(options_dict=parse_config(self.raw.splitlines()))
return self._opts
def save_in_dir(self, dirpath: str) -> None:
atomic_save(self.raw.encode('utf-8'), os.path.join(dirpath, f'{self.name}.conf'))
def save_in_conf(self, confdir: str, reload_in: str) -> None:
atomic_save(self.raw.encode('utf-8'), os.path.join(confdir, 'current-theme.conf'))
confpath = os.path.realpath(os.path.join(confdir, 'kitty.conf'))
try:
with open(confpath) as f:
raw = f.read()
except FileNotFoundError:
raw = ''
nraw = patch_conf(raw, self.name)
if raw:
with open(confpath + '.bak', 'w') as f:
f.write(raw)
atomic_save(nraw.encode('utf-8'), confpath)
if reload_in == 'parent':
if 'KITTY_PID' in os.environ:
os.kill(int(os.environ['KITTY_PID']), signal.SIGUSR1)
elif reload_in == 'all':
reload_conf_in_all_kitties()
class Themes:
def __init__(self) -> None:
self.themes: Dict[str, Theme] = {}
self.index_map: Tuple[str, ...] = ()
def __len__(self) -> int:
return len(self.themes)
def __iter__(self) -> Iterator[Theme]:
return iter(self.themes.values())
def __getitem__(self, key: Union[int, str]) -> Theme:
if isinstance(key, str):
return self.themes[key]
if key < 0:
key += len(self.index_map)
return self.themes[self.index_map[key]]
def load_from_zip(self, path_to_zip: str) -> None:
with zipfile.ZipFile(path_to_zip, 'r') as zf:
for name in zf.namelist():
if os.path.basename(name) == 'themes.json':
theme_file_name = name
with zf.open(theme_file_name) as f:
items = json.loads(f.read())
break
else:
raise ValueError(f'No themes.json found in {path_to_zip}')
for item in items:
t = Theme(zip_file_loader(path_to_zip, theme_file_name, item['file']))
t.apply_dict(item)
if t.name:
self.themes[t.name] = t
def load_from_dir(self, path: str) -> None:
if not os.path.isdir(path):
return
for name in os.listdir(path):
if name.endswith('.conf'):
with open(os.path.join(path, name), 'rb') as f:
raw = f.read().decode()
try:
d = parse_theme(name, raw)
except (Exception, SystemExit):
continue
t = Theme(raw.__str__)
t.apply_dict(d)
if t.name:
self.themes[t.name] = t
def filtered(self, is_ok: Callable[[Theme], bool]) -> 'Themes':
ans = Themes()
def sort_key(k: Tuple[str, Theme]) -> str:
return k[1].name.lower()
ans.themes = {k: v for k, v in sorted(self.themes.items(), key=sort_key) if is_ok(v)}
ans.index_map = tuple(ans.themes)
return ans
def copy(self) -> 'Themes':
ans = Themes()
ans.themes = self.themes.copy()
ans.index_map = self.index_map
return ans
def apply_search(
self, expression: str, mark_before: str = MARK_BEFORE, mark_after: str = MARK_AFTER
) -> Iterator[str]:
raw = '\n'.join(self.themes)
results = match(raw, expression, positions=True, level1=' ')
themes: Dict[str, Theme] = {}
for r in results:
pos, k = r.split(':', 1)
positions = tuple(map(int, pos.split(',')))
text = k
for p in reversed(positions):
text = text[:p] + mark_before + text[p] + mark_after + text[p+1:]
themes[k] = self.themes[k]
yield text
self.themes = themes
self.index_map = tuple(self.themes)
def load_themes(cache_age: float = 1., ignore_no_cache: bool = False) -> Themes:
ans = Themes()
try:
fetched = fetch_themes(cache_age=cache_age)
except NoCacheFound:
if not ignore_no_cache:
raise
ans.load_from_zip(fetched)
ans.load_from_dir(os.path.join(config_dir, 'themes'))
ans.index_map = tuple(ans.themes)
return ans

Some files were not shown because too many files have changed in this diff Show More