Compare commits

...

92 Commits

Author SHA1 Message Date
Hiltjo Posthuma fa253f077f bump version to 0.8.4 2020-06-19 11:27:17 +02:00
Hiltjo Posthuma b27a383a3a config.mk: use PKG_CONFIG in commented OpenBSD section 2020-06-17 23:49:40 +02:00
Hiltjo Posthuma 81067c65ea LICENSE: bump years 2020-06-17 23:49:40 +02:00
Hiltjo Posthuma f74a9df6e1 remove sixel stub code
Remove stub code that was used for an experiment of adding sixel code to st
from the commit f7398434.
2020-06-17 23:49:22 +02:00
Hiltjo Posthuma 818ec746f4 fix unicode glitch in DCS strings, patch by Tim Allen
Reported on the mailinglist:

"
I discovered recently that if an application running inside st tries to
send a DCS string, subsequent Unicode characters get messed up. For
example, consider the following test-case:

    printf '\303\277\033P\033\\\303\277'

...where:

  - \303\277 is the UTF-8 encoding of U+00FF LATIN SMALL LETTER Y WITH
    DIAERESIS (ÿ).
  - \033P is ESC P, the token that begins a DCS string.
  - \033\\ is ESC \, a token that ends a DCS string.
  - \303\277 is the same ÿ character again.

If I run the above command in a VTE-based terminal, or xterm, or
QTerminal, or pterm (PuTTY), I get the output:

    ÿÿ

...which is to say, the empty DCS string is ignored. However, if I run
that command inside st (as of commit 9ba7ecf), I get:

    ÿÿ

...where those last two characters are \303\277 interpreted as ISO8859-1
characters, instead of UTF-8.

I spent some time tracing through the state machines in st.c, and so far
as I can tell, this is how it works currently:

  - ESC P sets the "ESC_DCS" and "ESC_STR" flags, indicating that
    incoming bytes should be collected into the strescseq buffer, rather
    than being interpreted.
  - ESC \ sets the "ESC_STR_END" flag (when ESC is received), and then
    calls strhandle() (when \ is received) to interpret the collected
    bytes.
  - If the collected bytes begin with 'P' (i.e. if this was a DCS
    string) strhandle() sets the "ESC_DCS" flag again, confusing the
    state machine.

If my understanding is correct, fixing the problem should be as easy as
removing the line that sets ESC_DCS from strhandle():

diff --git a/st.c b/st.c
index ef8abd5..b5b805a 100644
--- a/st.c
+++ b/st.c
@@ -1897,7 +1897,6 @@ strhandle(void)
		xsettitle(strescseq.args[0]);
		return;
	case 'P': /* DCS -- Device Control String */
-		term.mode |= ESC_DCS;
	case '_': /* APC -- Application Program Command */
	case '^': /* PM -- Privacy Message */
		return;

I've tried the above patch and it fixes my problem, but I don't know if
it introduces any others.
"
2020-06-17 21:35:39 +02:00
Hiltjo Posthuma 9ba7ecf7b1 FAQ: fix single-buffer patch
rebase against master
2020-06-01 14:09:46 +02:00
Hiltjo Posthuma a2a704492b config.def.h: add an option allowwindowops, by default off (secure)
Similar to the xterm AllowWindowOps option, this is an option to allow or
disallow certain (non-interactive) operations that can be insecure or
exploited.

NOTE: xsettitle() is not guarded by this because st does not support printing
the window title. Else this could be exploitable (arbitrary code execution).
Similar problems have been found in the past in other terminal emulators.

The sequence for base64-encoded clipboard copy is now guarded because it allows
a sequence written to the terminal to manipulate the clipboard of the running
user non-interactively, for example:

printf '\x1b]52;0;ZWNobyBoaQ0=\a'
2020-05-30 22:06:15 +02:00
Hiltjo Posthuma 0f8b40652b FAQ: add some details about the w3m img hack
... and an example patch to switch from double-buffering to a single buffer.
2020-05-30 22:05:17 +02:00
Hiltjo Posthuma e6e2c6199f tiny style fix 2020-05-30 22:05:17 +02:00
Hiltjo Posthuma 94b8ec0021 Partially add back in "support REP (repeat) escape sequence"
Add the functionality back in for xterm compatibility, but do not expose the
capability in st.info (yet).

Some notes:

It was reverted because it caused some issues with ncurses in some
configurations, namely when using BSD padding (--enable-bsdpad, BSD_TPUTS) in
ncurses it caused issues with repeating digits.

A fix has been upstreamed in ncurses since snapshot 20200523. The fix is also
backported to OpenBSD -current.
2020-05-30 22:04:28 +02:00
Steve Ward dec6b530a4 Call xsetcursor to set win.cursor in main
In xsetcursor, remove "DEFAULT(cursor, 1)" because 0 is a valid value.
Increase max allowed value of cursor from 6 to 7 (st extension).
2020-05-24 13:45:42 +02:00
Hiltjo Posthuma 475a0a36cb Revert "support REP (repeat) escape sequence"
This reverts commit e8392b282c.

There is currently a bug in older ncurses versions (like on OpenBSD) where a
fix for a bug with REP is not backported yet. Most likely in tty/tty_update.c:

Noticed while using lynx (which uses ncurses/curses).
To reproduce using lynx: echo "Z0000000" | lynx -stdin

or using the program:

int
main(void)
{
	WINDOW *win;
	win = initscr();

	printw("Z0000000");

	refresh();

	sleep(5);

	return 0;
}

This prints "ZZZZZZZ" (incorrectly).
2020-05-16 21:06:13 +02:00
Avi Halachmi (:avih) e8392b282c support REP (repeat) escape sequence
The sequence \e[Nb prints the last printed char N (more) times if it's
printable, and it's ignored after newline or other control chars.

This is Ecma-048/ANSI-X3.6 sequence and not DEC VT. It's supported by
xterm, and ncurses uses it when possible, e.g. when TERM is xterm* (and
with this commit also st*).

xterm supports only codepoints<=255, possibly due to internal limits.
We support any value/codepoint which was placed in a cell.

To test:
- tput rep 65 4 -> prints 'AAAA'
- printf "\342\225\246\033[4b" -> prints U+2566 1+4 times.
2020-05-16 14:08:10 +02:00
Roberto E. Vargas f8afebdfa0 Add rin terminfo capability
Tianlin Qu discovered that st is missing rin (scroll back #1 lines).
2020-05-16 14:07:31 +02:00
k0ga bda9c9ffa6 Make shift+wheel behaves as shift+Prev/Next
St uses a very good hack where mouse wheel genereates ^Y and ^E,
that are the same keys that less and vi uses for backward and
fordward scrolling. Scroll, as many terminal emulators, use
shift+Prev/Next for scrolling, but it is also using ^E and ^Y
for scroling, characters that are reserved in the POSIX shell
in emacs mode for end of line and yanking, making scroll unsable
in st.

This patch adds a new hack, making shift+wheel returning the
same sequences than shift+Prev/Next, meaning that scroll or
any other similar program will not be able to differentiate
between them.
2020-05-16 12:37:14 +02:00
Jakub Leszczak 045a0fab4f Fix selection: selscroll 2020-05-12 15:38:17 +02:00
Jakub Leszczak 9c30066e73 Fix selection: ignore ATTR_WRAP when rectangular selection in getsel 2020-05-12 15:38:02 +02:00
Jakub Leszczak 8304d4f059 Fix selection: selclear in tputc 2020-05-12 15:37:59 +02:00
Hiltjo Posthuma 914fb825df code-style: add fallthrough comment
Patch by Steve Ward, thanks.
2020-05-09 14:43:31 +02:00
Hiltjo Posthuma cde480c693 optimize column width calculation and utf-8 encode for ASCII
In particular on OpenBSD and on glibc wcwidth() is quite expensive.
On musl there is little difference.
2020-05-09 14:11:25 +02:00
Hiltjo Posthuma 8211e36d28 fix for incorrect (partial) written sequences when libc wcwidth() == -1
Fix an issue with incorrect (partial) written sequences when libc wcwidth() ==
-1. The sequence is updated to on wcwidth(u) == -1:

	c = "\357\277\275"

but len isn't.

A way to reproduce in practise:

* st -o dump.txt
* In the terminal: printf '\xcd\xb8'
- This is codepoint 888, on OpenBSD it reports wcwidth() == -1.
- Quit the terminal.
- Look in dump.txt (partial written sequence of "UTF_INVALID").

This was introduced in:

"	commit 11625c7166
	Author: czarkoff@gmail.com <czarkoff@gmail.com>
	Date:   Tue Oct 28 12:55:28 2014 +0100

	    Replace character with U+FFFD if wcwidth() is -1

	    Helpful when new Unicode codepoints are not recognized by libc."

Change:

Remove setting the sequence. If this happens to break something, another
solution could be setting len = 3 for the sequence.
2020-05-09 14:07:52 +02:00
Hiltjo Posthuma 87545c612e tiny code-style and typo-fix in comment 2020-05-09 14:05:04 +02:00
Avi Halachmi (:avih) 1d59091065 auto-sync: draw on idle to avoid flicker/tearing
st could easily tear/flicker with animation or other unattended
output. This commit eliminates most of the tear/flicker.

Before this commit, the display timing had two "modes":

- Interactively, st was waiting fixed `1000/xfps` ms after forwarding
  the kb/mouse event to the application and before drawing.

- Unattended, and specifically with animations, the draw frequency was
  throttled to `actionfps`. Animation at a higher rate would throttle
  and likely tear, and at lower rates it was tearing big frames
  (specifically, when one `read` didn't get a full "frame").

The interactive behavior was decent, but it was impossible to get good
unattended-draw behavior even with carefully chosen configuration.

This commit changes the behavior such that it draws on idle instead of
using fixed latency/frequency. This means that it tries to draw only
when it's very likely that the application has completed its output
(or after some duration without idle), so it mostly succeeds to avoid
tear, flicker, and partial drawing.

The config values minlatency/maxlatency replace xfps/actionfps and
define the range which the algorithm is allowed to wait from the
initial draw-trigger until the actual draw. The range enables the
flexibility to choose when to draw - when least likely to flicker.

It also unifies the interactive and unattended behavior and config
values, which makes the code simpler as well - without sacrificing
latency during interactive use, because typically interactively idle
arrives very quickly, so the wait is typically minlatency.

While it only slighly improves interactive behavior, for animations
and other unattended-drawing it improves greatly, as it effectively
adapts to any [animation] output rate without tearing, throttling,
redundant drawing, or unnecessary delays (sounds impossible, but it
works).
2020-05-09 13:53:50 +02:00
Jan Klemkow d6ea0a1a61 replace exit(3) by _exit(2) in signal handler sigchld()
exit(3) is not async-signal-safe but, _exit(2) is.
This change prevents st to crash and dump core.
2020-04-30 01:21:21 +02:00
Hiltjo Posthuma 43a395ae91 bump version to 0.8.3 2020-04-27 13:56:25 +02:00
Ivan Tham 72e3f6c7c0 Update XIM cursor position only if changed
Updating XIM cursor position is expensive, so only update it when cursor
position changed.
2020-04-19 19:39:48 +02:00
Hiltjo Posthuma 33a9a45664 just remove the EOF message 2020-04-11 15:45:06 +02:00
Roberto E. Vargas Caballero 771bc401f7 Add st-mono terminfo entry
This entry is intended for monocolor display and it is very
helpful for color haters.
2020-04-11 15:23:23 +02:00
Hiltjo Posthuma d66bd405c0 config.def.h: add a comment for the scroll variable 2020-04-11 15:23:23 +02:00
Hiltjo Posthuma e997303502 Fix small typos 2020-04-11 15:23:23 +02:00
Quentin Rameau c1145268f6 Launch scroll program with the default shell 2020-04-11 15:23:23 +02:00
Roberto E. Vargas Caballero 0b73612c0d Update FAQ with the last modifications 2020-04-11 15:23:23 +02:00
Roberto E. Vargas Caballero 019449a7e6 Add terminfo entries for backspace mode
St used to use backspace as BS until the commit 230d0c8, but due
to general lack of knowledge of lusers, we moved to the most common
configuration in linux to avoid answering the same question 3 times
per month. With the most common configuration we have a backspace
that returns a DEL, and we have a Delete key that doesn't return a
DEL character neither a BS.

When dealing with devices connected using a serial line (or even
with Plan9) it is more common Backspace as BS and Delete as DEL. For
this reason, st is not always the best tool when you talk with a
serial device.

This patch adds new terminfo entries for Backspace as BS and Delete
as DEL. A patch for confg.h is also added, to make easier switch
between both configurations.
2020-04-11 15:23:23 +02:00
Roberto E. Vargas Caballero fbae700a3f Fix style issue 2020-04-11 15:23:23 +02:00
Roberto E. Vargas Caballero e52319cc7d ttyread: test for EOF while reading tty
When a read operation returns 0 then it means that we arrived to the end of the
file, and new reads will return 0 unless you do some other operation such as
lseek(). This case happens with USB-232 adapters when they are unplugged.
2020-04-11 15:23:23 +02:00
Roberto E. Vargas Caballero 21e0d6e8b8 Add support for scroll(1)
Scroll is a program that stores all the lines of its child and be used in st as
a way of implementing scrollback.

This solution is much better than implementing the scrollback in st itself
because having a different program allows to use it in any other program
without doing modifications to those programs.
2020-04-11 15:23:20 +02:00
Hiltjo Posthuma 5703aa0390 make argv0 not static, fixes a warning with tcc
Reported by Aajonus, thanks!
2020-04-10 12:12:43 +02:00
Avi Halachmi (:avih) 28ad288399 mouseshortcuts: fix custom modifier on release
This line didn't work at mshortcuts at config.h:

  /*  mask       button   function  arg       release */
    { ShiftMask, Button2, selpaste, {.i = 0}, 1 },

and now it does work.

The issue was that XButtonEvent.state is "the logical state ... just prior
to the event", which means that on release the state has the Button2Mask
bit set because button2 was down just before it was released.

The issue didn't manifest with the default shift + middle-click on release
(to override mouse mode) because its specified modifier is XK_ANY_MOD, at
which case match(...) ignores any specific bits and simply returns true.

The issue also doesn't manifest on press, because prior to the event
Button<N> was not down and its mask bit is not set.

Fix by filtering out the mask of the button which we're currently matching.

We could have said "well, that's how button events behave, you should
use ShiftMask|Button2Mask for release", but this both not obvious to
figure out, and specifically here always filtering does not prevent
configuring any useful modifiers combination. So it's a win-win.
2020-04-02 14:41:03 +02:00
Ivan Tham 51e19ea11d Remove explicit XNFocusWindow
XCreateIC ICValues default XNFocusWindow to XNClientWindow if not
specified, it can be omitted since it is the same.

From the documentation
https://www.x.org/releases/current/doc/libX11/libX11/libX11.html

> Focus Window
>
> The XNFocusWindow argument specifies the focus window. The primary
> purpose of the XNFocusWindow is to identify the window that will receive
> the key event when input is composed.
>
> When this XIC value is left unspecified, the input method will use the
> client window as the default focus window.
2020-02-19 00:46:20 +01:00
Quentin Rameau 26cdfebf31 x: fix XIM handling
Do not try to set specific IM method, let the user specify it with
XMODIFIERS.

If the requested method is not available or opening fails, fallback to
the default input handler and register a handler on the new IM server
availability signal.

Do the same when the input server is closed and (re)started.
2020-02-02 22:56:51 +01:00
Quentin Rameau cd785755f2 x: check we still have an XIC context before accessing it 2020-02-02 22:56:51 +01:00
Quentin Rameau 2cb539142b x: do not instantiate a new nested list on each cursor move 2020-02-02 22:56:51 +01:00
Quentin Rameau 99de333951 x: move IME variables into XWindow ime embedded struct 2020-02-02 22:56:51 +01:00
Ivan Tham 895e5b50a8 Increase XmbLookupString buffer
Current buffer is too short to input medium to long sentences from IME.
Input with longer text will show the wrong input, taking 64 instead of
32 bytes should be enough for most of the cases. Broken cases before,

Chinese (taken from song 也可以)
可不可以轻轻的松开自己

Japanese (taken from bootleggers rom quote)
あなたは家のように感じる
2020-01-18 14:21:50 +01:00
Hiltjo Posthuma 384830110b update FAQ
- add common question about the w3m image drawing hack.
- remove some bad advise about $TERM.
- change some links to https.
2019-11-17 20:04:52 +01:00
Avi Halachmi (:avih) 2e54a21b5a OSC 52 - copy to clipboard: don't limit to 382 bytes
Strings which an application sends to the terminal in OSC, DCS, etc
are typically small (title, colors, etc) but one exception is OSC 52
which copies text to the clipboard, and is used for instance by tmux.

Previously st cropped these strings at 512 bytes, which for OSC 52
limited the copied text to 382 bytes (remaining buffer space before
base64). This made it less useful than it can be.

Now it's a dynamic growing buffer. It remains allocated after use,
resets to 512 when a new string starts, or leaked on exit.

Resetting/deallocating the buffer right after use (at strhandle) is
possible with some more code, however, it doesn't always end up used,
and to cover those cases too will require even more code, so resetting
only on new string is good enough for now.
2019-11-10 22:45:54 +01:00
Hiltjo Posthuma 289c52b7aa CSIEscape, STREscape: use size_t for buffer length 2019-11-10 22:45:54 +01:00
Avi Halachmi (:avih) 7ceb3d1f72 STREscape: don't trim prematurely
STRescape holds strings in escape sequences such as OSC and DCS, and
its buffer is 512 bytes.

If the input is too big then trailing chars are ignored, but the test
was off-by-1 such that it took 510 chars instead of 511 (before a
terminating NULL is added).

Now the full size can be utilized.
2019-11-10 22:45:54 +01:00
Avi Halachmi (:avih) ea4d933ed9 base64dec: don't read out of bounds
Previously, base64dec checked terminating input '\0' every 4 calls to
base64dec_getc, where the latter progressed one or more chars on each
call, and could read past '\0' in the way it was used.

The input to base64dec currently comes only from OSC 52 escape seq
(copy to clipboard), and reading past '\0' or even past the buffer
boundary was easy to trigger.

Also, even if we could trust external input to be valid base64, there
are different base64 standards, and not all of them require padding
to 4 bytes blocks (using trailing '=' chars).

It didn't affect short OSC 52 strings because the buffer is initialized
to 0's, so typically it did stop within the buffer, but if the string
was trimmed to fit (the buffer is 512 bytes) then it did also read past
the end of the buffer, and the decoded suffix ended up arbitrary.

This patch makes base64dec_getc not progress past '\0', and instead
produce fake trailing padding of '='.

Additionally, at base64dec, if padding is detected at the first or
second byte of a quartet, then we identify it as invalid and abort
(a valid quartet has at least two leading non-padding bytes).
2019-11-10 22:45:54 +01:00
Sebastian J. Bronner 83866428de Fix tmux terminfo extensions Se and Ss
The tmux terminfo extensions Ss and Se are currently specified as
booleans in `st.info`. They should be strings. See
eeedb43ae8/tty-term.c
lines 254 and 265.

I have used the values from
https://invisible-island.net/ncurses/terminfo.src.html#toc-_S_I_M_P_L_E_T_E_R_M
for this patch.
2019-11-05 19:51:35 +01:00
Ingo Lohmar 1f09f0b0bb apply hints before initial mapping (ICCCM)
For WM_CLASS this is mentioned in the ICCCM docs
https://tronche.com/gui/x/icccm/sec-4.html#s-4.1.2.5
(third sentence).

When changing the WM_CLASS from the command line, this is necessary for
window managers to pick it up before applying class-based rules.
2019-10-26 11:47:24 +02:00
Avi Halachmi (:avih) a2c479c4c8 mouse shortcuts: allow using forcemousemod (e.g. shift)
The recent mouse shurtcuts commits allow customization, but ignore
forcemousemod mask (default: shift) as a modifier, for no good reason
other than following the behavior of the KB shortcuts.

Allow using forcemousemod too, which now can be used to invoke
different shortcuts, though the automatic effect of forcemousemod will
be lost for buttons which use mask with forcemousemod.

E.g. the default is:

static uint forcemousemod = ShiftMask;
...
{ XK_ANY_MOD,           Button4, ttysend,        {.s = "\031"} },
...

where ttysend will be invoked for button4 with any mod when not in mouse
mode, and with shift when in mouse mode.

Now it's possible to do this:
{ ShiftMask,            Button4, ttysend,        {.s = "foo"} },
{ XK_ANY_MOD,           Button4, ttysend,        {.s = "\031"} },

Which will invoke ttysend("foo") while shift is held and ttysend("\031")
otherwise. Shift still overrides mouse mode, but will now send "foo".

Previously with this setup the second binding was always invoked
because the forceousemod mask was always removed from the event.

Buttons which don't use forcemousemod behave the same as before.

This is useful e.g. for the scrollback mouse patch, which wants to
configure shift+wheel for scrollback, while keeping the normal behavior
without shift.
2019-10-24 15:34:25 +02:00
Avi Halachmi (:avih) d2b75db8d7 mouse shortcuts: don't hardcode selpaste
Because selpaste is activated on release, a release flag was added to
mouse shortcuts which controls whether activation is on press/release,
and selpaste binding to button2 was moved to config.h .

button1 remains the only hardcoded mouse button - for selection + copy.
2019-10-13 21:46:31 +02:00
Avi Halachmi (:avih) b6d280de6d mouse shortcuts: allow override for all shortcuts
Allow forceselmod to override all mouse shortcuts rather than only
selection, and rename it to forcemousemod as it's now more appropriate.

This will affect mouse shortcuts which use mask other than XK_ANY_MOD.

This does not affect the default behavior because the default mouse
shortcuts (wheel) use XK_ANY_MOD, where forceselmod already activated
the override also before this change.

Previously, if a mouse shortcut was configured with a specific mod and
forceselmod was held, then the shortcut did not execute unless the
configured mod included forceselmod.
2019-10-13 21:46:31 +02:00
Avi Halachmi (:avih) ba7f4d69af mouse shortcuts: allow same functions as kb shortcuts
Previously mouse shortcuts supported only ttywrite.

This required adding an "Arg" function ttysend - which does what the
original mouse shortcuts did.
2019-10-13 21:46:31 +02:00
Hiltjo Posthuma 2b8333f553 config.def.h: remove crlf value section
this is not used anymore.

patch sent as an ed script using RFC2549 by k0ga.
2019-08-26 17:58:47 +02:00
Hiltjo Posthuma caa1d8fbea FAQ: add entry about color emoji Xft bug
This has been asked many times on IRC and the mailinglist. Make it easier to
find information about this particular Xft issue by adding it to the FAQ.
2019-05-17 13:00:10 +02:00
Avi Halachmi (:avih) f1546cf9c1 selection: fix view to match actual selection on first cell 2019-04-14 13:50:20 +02:00
Hiltjo Posthuma 21367a040f revert part of commit add0211522
"use iswspace()/iswpunct() to find word delimiters

    this inverts the configuration logic: you no longer provide a list of
    delimiters -- all space and punctuation characters are considered
    delimiters, unless listed in extrawordchars."

Feedback from IRC and personal preference.
2019-03-15 20:40:16 +01:00
Hiltjo Posthuma b650256044 dont print color warning on color reset OSC 104 without parameter
also print explicitly "(null)" when printf "%s" p=NULL.

noticed when exiting mutt: printf '\x1b]104\x07'
2019-03-15 14:47:08 +01:00
Hiltjo Posthuma 9acec468fb minor code-style, initialize var at the top of function 2019-03-15 14:42:50 +01:00
Hiltjo Posthuma 927621f6da config.def.h: tweak extra worddelimiters
This changes the selection more like xterm.
To test try: "find /" and select a path.
2019-03-15 12:31:54 +01:00
Lauri Tirkkonen add0211522 use iswspace()/iswpunct() to find word delimiters
this inverts the configuration logic: you no longer provide a list of
delimiters -- all space and punctuation characters are considered
delimiters, unless listed in extrawordchars.
2019-03-15 12:25:13 +01:00
Lauri Tirkkonen d5efd256aa replace utf8strchr with wcschr 2019-03-15 12:24:13 +01:00
Lauri Tirkkonen 75b4ba4b4b be silent about explicitly unhandled mouse modes 2019-03-13 17:51:58 +01:00
Hiltjo Posthuma ed68fe7dce simplify (greedy) font caching allocating a bit
POSIX says:
"If ptr is a null pointer, realloc() shall be equivalent to malloc() for the
 specified size."
2019-03-03 11:29:43 +01:00
Hiltjo Posthuma 4e0135afec style: remove double empty newlines 2019-03-03 11:23:54 +01:00
magras a8cb8e9454 fix use after free in font caching algorithm
Current font caching algorithm contains a use after free error. A font
removed from `frc` might be still listed in `wx.specbuf`. It will lead
to a crash inside `XftDrawGlyphFontSpec()`.

Steps to reproduce:
$ st -f 'Misc Tamsyn:scalable=false'
$ curl https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt

Of course, result depends on fonts installed on a system and fontconfig.
In my case, I'm getting consistent segfaults with different fonts.

I replaced a fixed array with a simple unbounded buffer with a constant
growth rate. Cache starts with a capacity of 0, gets increments by 16,
and never shrinks. On my machine after `cat UTF-8-demo.txt` buffer
reaches a capacity of 192. During casual use capacity stays at 0.
2019-03-03 11:18:31 +01:00
Ivan Tham e85b6b6466 better Input Method Editor (IME) support
Features:

- Allow input methods swap with hotkey (E.g. left ctrl + left shift).
- Over-the-spot pre-editing style, pre-edit data placed over insertion point.
- Restart IME without segmentation fault.

TODO:

- Automatically pickup IME if st started before IME
2019-02-12 18:45:15 +01:00
Hiltjo Posthuma 75f92eb348 bump version to 0.8.2 2019-02-09 12:48:39 +01:00
Hiltjo Posthuma 3be4cf11d7 config: add Shift+Insert as selpaste() again
This was changed before in:
commit 20f713548d on Wed Jan 25 19:17:38 2017
2019-01-10 18:16:17 +01:00
Paride Legovini 16d98738e7 Let the user specify CPPFLAGS
This complements the work done in d4928ed, allowing the user to specify
the preprocessor flags with the CPPFLAGS environment variable. This is
useful for example to specify preprocessor macros with -D.

CFLAGS could be used instead, but CPPFLAGS is more correct and is expected
to be honored in some cases. For example, the helper scripts to build
Debian packages make use of CPPFLAGS, but the variable is currently
being ignored unless manually appended to CFLAGS.
2019-01-10 18:13:13 +01:00
Paride Legovini e23acb9188 Set the path of pkg-config in a variable instead of hardcoding it
In this way the path of pkg-config can be overridden from the command
line. This is useful for example when cross-compiling.
2019-01-04 16:00:54 +01:00
Hiltjo Posthuma 7e19e11676 Makefile: fix dependencies on config.h
patch by Younes Khoudli (changed slightly). Thanks
2019-01-04 12:33:01 +01:00
Lauri Tirkkonen 096b125db7 output child WEXITSTATUS/WTERMSIG on abnormal termination 2018-12-11 18:36:02 +01:00
Hiltjo Posthuma d7bf023b2f fix memory leak in xloadcols()
reported by Avi Halachmi (:avih)" <avihpit@yahoo.com>

patch slightly changed by me.
2018-11-04 14:35:07 +01:00
Hiltjo Posthuma b4d68d4daa st: small typofix in comment 2018-11-04 14:30:56 +01:00
Hiltjo Posthuma 30ec9a3dc3 small code-style fix 2018-09-11 19:06:35 +02:00
Quentin Rameau 67d0cb65d0 Remove the ISO 14755 feature
And move it to the patches section.
Keeping it would force to add an exec pledge on OpenBSD, and some
people think it's bloated, so bye!
2018-09-11 19:05:55 +02:00
Hiltjo Posthuma 4f4bccd162 Revert "Simplify cursor color handling"
This reverts commit 1911c9274d.
2018-07-17 20:01:58 +02:00
Hiltjo Posthuma 8ed7a4b3b7 Revert "Make cursor follow text color"
This reverts commit b51bcd5553.
2018-07-17 20:01:57 +02:00
Hiltjo Posthuma 732be223ee Revert "Fix crash when cursor color is truecolor"
This reverts commit 5535c1f04c.
2018-07-17 20:01:54 +02:00
Jules Maselbas 5535c1f04c Fix crash when cursor color is truecolor
Reported-by: Ivan Tham <pickfire@riseup.net>
2018-07-15 18:16:52 +02:00
Jules Maselbas b51bcd5553 Make cursor follow text color 2018-07-14 12:49:37 +02:00
Jules Maselbas 1911c9274d Simplify cursor color handling 2018-07-14 12:49:35 +02:00
Jules Maselbas 29f341da7c Fix crash on resize
Prevent to realloc xw.specbuc with a negative number of col.
Add proper hints for the minimal size, for one character.
2018-06-30 20:51:46 +02:00
Hiltjo Posthuma dc3b5babf1 config.mk: remove extra newline before EOF 2018-06-02 17:11:14 +02:00
Hiltjo Posthuma 235a783e03 code-style for pledge(2)
feedback from Klemens, thanks
2018-05-25 13:04:09 +02:00
Hiltjo Posthuma 30ce2cc002 Pledge on OpenBSD 2018-05-25 11:59:28 +02:00
Hiltjo Posthuma 041912a791 error message style and use strerror in a few places 2018-03-29 18:30:05 +02:00
Hiltjo Posthuma bd3f7fd842 st -v: remove years and copyright text 2018-03-29 18:18:30 +02:00
Daniel Tameling 74cff67bd7 set sel.alt in selstart instead of selextend 2018-03-29 18:15:29 +02:00
11 changed files with 539 additions and 346 deletions

107
FAQ
View File

@ -1,6 +1,7 @@
## Why does st not handle utmp entries?
Use the excellent tool of [utmp](http://git.suckless.org/utmp/) for this task.
Use the excellent tool of [utmp](https://git.suckless.org/utmp/) for this task.
## Some _random program_ complains that st is unknown/not recognised/unsupported/whatever!
@ -8,6 +9,7 @@ It means that st doesnt have any terminfo entry on your system. Chances are
you did not `make install`. If you just want to test it without installing it,
you can manually run `tic -sx st.info`.
## Nothing works, and nothing is said about an unknown terminal!
* Some programs just assume theyre running in xterm i.e. they dont rely on
@ -15,19 +17,21 @@ you can manually run `tic -sx st.info`.
* Some programs dont complain about the lacking st description and default to
another terminal. In that case see the question about terminfo.
## I get some weird glitches/visual bug on _random program_!
Try launching it with a different TERM: $ TERM=xterm myapp. toe(1) will give
you a list of available terminals, but youll most likely switch between xterm,
st or st-256color. The default value for TERM can be changed in config.h
(TNAME).
## How do I scroll back up?
Using a terminal multiplexer.
* Using a terminal multiplexer.
* `st -e tmux` using C-b [
* `st -e screen` using C-a ESC
* Using the excellent tool of [scroll](https://git.suckless.org/scroll/).
* Using the scrollback [patch](https://st.suckless.org/patches/scrollback/).
## I would like to have utmp and/or scroll functionality by default
You can add the absolute patch of both programs in your config.h
file. You only have to modify the value of utmp and scroll variables.
* `st -e tmux` using C-b [
* `st -e screen` using C-a ESC
## Why doesn't the Del key work in some programs?
@ -84,12 +88,14 @@ If you are using zsh, then read the zsh FAQ
Putting these lines into your .zshrc will fix the problems.
## How can I use meta in 8bit mode?
St supports meta in 8bit mode, but the default terminfo entry doesn't
use this capability. If you want it, you have to use the 'st-meta' value
in TERM.
## I cannot compile st in OpenBSD
OpenBSD lacks librt, despite it being mandatory in POSIX
@ -98,13 +104,14 @@ If you want to compile st for OpenBSD you have to remove -lrt from config.mk, an
st will compile without any loss of functionality, because all the functions are
included in libc on this platform.
## The Backspace Case
St is emulating the Linux way of handling backspace being delete and delete being
backspace.
This is an issue that was discussed in suckless mailing list
<http://lists.suckless.org/dev/1404/20697.html>. Here is why some old grumpy
<https://lists.suckless.org/dev/1404/20697.html>. Here is why some old grumpy
terminal users wants its backspace to be how he feels it:
Well, I am going to comment why I want to change the behaviour
@ -159,9 +166,85 @@ terminal users wants its backspace to be how he feels it:
[1] http://www.ibb.net/~anne/keyboard.html
[2] http://www.tldp.org/HOWTO/Keyboard-and-Console-HOWTO-5.html
## But I really want the old grumpy behaviour of my terminal
Apply [1].
[1] http://st.suckless.org/patches/delkey
[1] https://st.suckless.org/patches/delkey
## Why do images not work in st using the w3m image hack?
w3mimg uses a hack that draws an image on top of the terminal emulator Drawable
window. The hack relies on the terminal to use a single buffer to draw its
contents directly.
st uses double-buffered drawing so the image is quickly replaced and may show a
short flicker effect.
Below is a patch example to change st double-buffering to a single Drawable
buffer.
diff --git a/x.c b/x.c
--- a/x.c
+++ b/x.c
@@ -732,10 +732,6 @@ xresize(int col, int row)
win.tw = col * win.cw;
win.th = row * win.ch;
- XFreePixmap(xw.dpy, xw.buf);
- xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
- DefaultDepth(xw.dpy, xw.scr));
- XftDrawChange(xw.draw, xw.buf);
xclear(0, 0, win.w, win.h);
/* resize to new width */
@@ -1148,8 +1144,7 @@ xinit(int cols, int rows)
gcvalues.graphics_exposures = False;
dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
&gcvalues);
- xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
- DefaultDepth(xw.dpy, xw.scr));
+ xw.buf = xw.win;
XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
@@ -1632,8 +1627,6 @@ xdrawline(Line line, int x1, int y1, int x2)
void
xfinishdraw(void)
{
- XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
- win.h, 0, 0);
XSetForeground(xw.dpy, dc.gc,
dc.col[IS_SET(MODE_REVERSE)?
defaultfg : defaultbg].pixel);
## BadLength X error in Xft when trying to render emoji
Xft makes st crash when rendering color emojis with the following error:
"X Error of failed request: BadLength (poly request too large or internal Xlib length error)"
Major opcode of failed request: 139 (RENDER)
Minor opcode of failed request: 20 (RenderAddGlyphs)
Serial number of failed request: 1595
Current serial number in output stream: 1818"
This is a known bug in Xft (not st) which happens on some platforms and
combination of particular fonts and fontconfig settings.
See also:
https://gitlab.freedesktop.org/xorg/lib/libxft/issues/6
https://bugs.freedesktop.org/show_bug.cgi?id=107534
https://bugzilla.redhat.com/show_bug.cgi?id=1498269
The solution is to remove color emoji fonts or disable this in the fontconfig
XML configuration. As an ugly workaround (which may work only on newer
fontconfig versions (FC_COLOR)), the following code can be used to mask color
fonts:
FcPatternAddBool(fcpattern, FC_COLOR, FcFalse);
Please don't bother reporting this bug to st, but notify the upstream Xft
developers about fixing this bug.

View File

@ -1,6 +1,6 @@
MIT/X Consortium License
© 2014-2018 Hiltjo Posthuma <hiltjo at codemadness dot org>
© 2014-2020 Hiltjo Posthuma <hiltjo at codemadness dot org>
© 2018 Devin J. Pohly <djpohly at gmail dot com>
© 2014-2017 Quentin Rameau <quinq at fifth dot space>
© 2009-2012 Aurélien APTEL <aurelien dot aptel at gmail dot com>

View File

@ -22,7 +22,7 @@ config.h:
$(CC) $(STCFLAGS) -c $<
st.o: config.h st.h win.h
x.o: arg.h st.h win.h
x.o: arg.h config.h st.h win.h
$(OBJ): config.h config.mk

View File

@ -11,13 +11,15 @@ static int borderpx = 2;
/*
* What program is execed by st depends of these precedence rules:
* 1: program passed with -e
* 2: utmp option
* 2: scroll and/or utmp
* 3: SHELL environment variable
* 4: value of shell in /etc/passwd
* 5: value of shell in config.h
*/
static char *shell = "/bin/sh";
char *utmp = NULL;
/* scroll program: to enable use a string like "scroll" */
char *scroll = NULL;
char *stty_args = "stty raw pass8 nl -echo -iexten -cstopb 38400";
/* identification sequence returned in DA and DECID */
@ -30,9 +32,9 @@ static float chscale = 1.0;
/*
* word delimiter string
*
* More advanced example: " `'\"()[]{}"
* More advanced example: L" `'\"()[]{}"
*/
char *worddelimiters = " ";
wchar_t *worddelimiters = L" ";
/* selection timeouts (in milliseconds) */
static unsigned int doubleclicktimeout = 300;
@ -41,9 +43,18 @@ static unsigned int tripleclicktimeout = 600;
/* alt screens */
int allowaltscreen = 1;
/* frames per second st should at maximum draw to the screen */
static unsigned int xfps = 120;
static unsigned int actionfps = 30;
/* allow certain non-interactive (insecure) window operations such as:
setting the clipboard text */
int allowwindowops = 0;
/*
* draw latency range in ms - from new content/keypress/etc until drawing.
* within this range, st draws when content stops arriving (idle). mostly it's
* near minlatency, but it waits longer for slow updates to avoid partial draw.
* low minlatency will tear/flicker more, as it can "detect" idle too early.
*/
static double minlatency = 8;
static double maxlatency = 33;
/*
* blinking timeout (set to 0 to disable blinking) for the terminal blinking
@ -150,14 +161,24 @@ static unsigned int mousebg = 0;
*/
static unsigned int defaultattr = 11;
/*
* Force mouse select/shortcuts while mask is active (when MODE_MOUSE is set).
* Note that if you want to use ShiftMask with selmasks, set this to an other
* modifier, set to 0 to not use it.
*/
static uint forcemousemod = ShiftMask;
/*
* Internal mouse shortcuts.
* Beware that overloading Button1 will disable the selection.
*/
static MouseShortcut mshortcuts[] = {
/* button mask string */
{ Button4, XK_ANY_MOD, "\031" },
{ Button5, XK_ANY_MOD, "\005" },
/* mask button function argument release */
{ XK_ANY_MOD, Button2, selpaste, {.i = 0}, 1 },
{ ShiftMask, Button4, ttysend, {.s = "\033[5;2~"} },
{ XK_ANY_MOD, Button4, ttysend, {.s = "\031"} },
{ ShiftMask, Button5, ttysend, {.s = "\033[6;2~"} },
{ XK_ANY_MOD, Button5, ttysend, {.s = "\005"} },
};
/* Internal keyboard shortcuts. */
@ -176,8 +197,8 @@ static Shortcut shortcuts[] = {
{ TERMMOD, XK_C, clipcopy, {.i = 0} },
{ TERMMOD, XK_V, clippaste, {.i = 0} },
{ TERMMOD, XK_Y, selpaste, {.i = 0} },
{ ShiftMask, XK_Insert, selpaste, {.i = 0} },
{ TERMMOD, XK_Num_Lock, numlock, {.i = 0} },
{ TERMMOD, XK_I, iso14755, {.i = 0} },
};
/*
@ -195,10 +216,6 @@ static Shortcut shortcuts[] = {
* * 0: no value
* * > 0: cursor application mode enabled
* * < 0: cursor application mode disabled
* crlf value
* * 0: no value
* * > 0: crlf mode is enabled
* * < 0: crlf mode is disabled
*
* Be careful with the order of the definitions because st searches in
* this table sequentially, so any XK_ANY_MOD must be in the last
@ -217,13 +234,6 @@ static KeySym mappedkeys[] = { -1 };
*/
static uint ignoremod = Mod2Mask|XK_SWITCH_MOD;
/*
* Override mouse-select while mask is active (when MODE_MOUSE is set).
* Note that if you want to use ShiftMask with selmasks, set this to an other
* modifier, set to 0 to not use it.
*/
static uint forceselmod = ShiftMask;
/*
* This is the huge key array which defines all compatibility to the Linux
* world. Please decide about changes wisely.

View File

@ -1,5 +1,5 @@
# st version
VERSION = 0.8.1
VERSION = 0.8.4
# Customize below to fit your system
@ -10,19 +10,26 @@ MANPREFIX = $(PREFIX)/share/man
X11INC = /usr/X11R6/include
X11LIB = /usr/X11R6/lib
PKG_CONFIG = pkg-config
# includes and libs
INCS = -I$(X11INC) \
`pkg-config --cflags fontconfig` \
`pkg-config --cflags freetype2`
`$(PKG_CONFIG) --cflags fontconfig` \
`$(PKG_CONFIG) --cflags freetype2`
LIBS = -L$(X11LIB) -lm -lrt -lX11 -lutil -lXft \
`pkg-config --libs fontconfig` \
`pkg-config --libs freetype2`
`$(PKG_CONFIG) --libs fontconfig` \
`$(PKG_CONFIG) --libs freetype2`
# flags
CPPFLAGS = -DVERSION=\"$(VERSION)\" -D_XOPEN_SOURCE=600
STCFLAGS = $(INCS) $(CPPFLAGS) $(CFLAGS)
STCPPFLAGS = -DVERSION=\"$(VERSION)\" -D_XOPEN_SOURCE=600
STCFLAGS = $(INCS) $(STCPPFLAGS) $(CPPFLAGS) $(CFLAGS)
STLDFLAGS = $(LIBS) $(LDFLAGS)
# OpenBSD:
#CPPFLAGS = -DVERSION=\"$(VERSION)\" -D_XOPEN_SOURCE=600 -D_BSD_SOURCE
#LIBS = -L$(X11LIB) -lm -lX11 -lutil -lXft \
# `$(PKG_CONFIG) --libs fontconfig` \
# `$(PKG_CONFIG) --libs freetype2`
# compiler and linker
# CC = c99

7
st.1
View File

@ -159,10 +159,6 @@ Copy the selected text to the clipboard selection.
.TP
.B Ctrl-Shift-v
Paste from the clipboard selection.
.TP
.B Ctrl-Shift-i
Launch dmenu to enter a unicode codepoint and send the corresponding glyph
to st.
.SH CUSTOMIZATION
.B st
can be customized by creating a custom config.h and (re)compiling the source
@ -174,7 +170,8 @@ See the LICENSE file for the terms of redistribution.
.SH SEE ALSO
.BR tabbed (1),
.BR utmp (1),
.BR stty (1)
.BR stty (1),
.BR scroll (1)
.SH BUGS
See the TODO file in the distribution.

267
st.c
View File

@ -38,14 +38,10 @@
/* macros */
#define IS_SET(flag) ((term.mode & (flag)) != 0)
#define NUMMAXLEN(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
#define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
#define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == 0x7f)
#define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
#define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
#define ISDELIM(u) (utf8strchr(worddelimiters, u) != NULL)
/* constants */
#define ISO14755CMD "dmenu -w \"$WINDOWID\" -p codepoint: </dev/null"
#define ISDELIM(u) (u && wcschr(worddelimiters, u))
enum term_mode {
MODE_WRAP = 1 << 0,
@ -55,7 +51,6 @@ enum term_mode {
MODE_ECHO = 1 << 4,
MODE_PRINT = 1 << 5,
MODE_UTF8 = 1 << 6,
MODE_SIXEL = 1 << 7,
};
enum cursor_movement {
@ -82,12 +77,11 @@ enum charset {
enum escape_state {
ESC_START = 1,
ESC_CSI = 2,
ESC_STR = 4, /* OSC, PM, APC */
ESC_STR = 4, /* DCS, OSC, PM, APC */
ESC_ALTCHARSET = 8,
ESC_STR_END = 16, /* a final string was encountered */
ESC_TEST = 32, /* Enter in test mode */
ESC_UTF8 = 64,
ESC_DCS =128,
};
typedef struct {
@ -133,13 +127,14 @@ typedef struct {
int charset; /* current charset */
int icharset; /* selected charset for sequence */
int *tabs;
Rune lastc; /* last printed char outside of sequence, 0 if control */
} Term;
/* CSI Escape sequence structs */
/* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
typedef struct {
char buf[ESC_BUF_SIZ]; /* raw string */
int len; /* raw string length */
size_t len; /* raw string length */
char priv;
int arg[ESC_ARG_SIZ];
int narg; /* nb of args */
@ -150,8 +145,9 @@ typedef struct {
/* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
typedef struct {
char type; /* ESC type ... */
char buf[STR_BUF_SIZ]; /* raw string */
int len; /* raw string length */
char *buf; /* allocated raw string */
size_t siz; /* allocation size */
size_t len; /* raw string length */
char *args[STR_ARG_SIZ];
int narg; /* nb of args */
} STREscape;
@ -214,7 +210,6 @@ static void selsnap(int *, int *, int);
static size_t utf8decode(const char *, Rune *, size_t);
static Rune utf8decodebyte(char, size_t *);
static char utf8encodebyte(Rune, size_t);
static char *utf8strchr(char *, Rune);
static size_t utf8validate(Rune *, size_t);
static char *base64dec(const char *);
@ -256,10 +251,10 @@ xwrite(int fd, const char *s, size_t len)
void *
xmalloc(size_t len)
{
void *p = malloc(len);
void *p;
if (!p)
die("Out of memory\n");
if (!(p = malloc(len)))
die("malloc: %s\n", strerror(errno));
return p;
}
@ -268,7 +263,7 @@ void *
xrealloc(void *p, size_t len)
{
if ((p = realloc(p, len)) == NULL)
die("Out of memory\n");
die("realloc: %s\n", strerror(errno));
return p;
}
@ -277,7 +272,7 @@ char *
xstrdup(char *s)
{
if ((s = strdup(s)) == NULL)
die("Out of memory\n");
die("strdup: %s\n", strerror(errno));
return s;
}
@ -341,23 +336,6 @@ utf8encodebyte(Rune u, size_t i)
return utfbyte[i] | (u & ~utfmask[i]);
}
char *
utf8strchr(char *s, Rune u)
{
Rune r;
size_t i, j, len;
len = strlen(s);
for (i = 0, j = 0; i < len; i += j) {
if (!(j = utf8decode(&s[i], &r, len - i)))
break;
if (r == u)
return &(s[i]);
}
return NULL;
}
size_t
utf8validate(Rune *u, size_t i)
{
@ -387,8 +365,9 @@ static const char base64_digits[] = {
char
base64dec_getc(const char **src)
{
while (**src && !isprint(**src)) (*src)++;
return *((*src)++);
while (**src && !isprint(**src))
(*src)++;
return **src ? *((*src)++) : '='; /* emulate padding if string ends */
}
char *
@ -406,6 +385,10 @@ base64dec(const char *src)
int c = base64_digits[(unsigned char) base64dec_getc(&src)];
int d = base64_digits[(unsigned char) base64dec_getc(&src)];
/* invalid input. 'a' can be -1, e.g. if src is "\n" (c-str) */
if (a == -1 || b == -1)
break;
*dst++ = (a << 2) | ((b & 0x30) >> 4);
if (c == -1)
break;
@ -446,6 +429,7 @@ selstart(int col, int row, int snap)
selclear();
sel.mode = SEL_EMPTY;
sel.type = SEL_REGULAR;
sel.alt = IS_SET(MODE_ALTSCREEN);
sel.snap = snap;
sel.oe.x = sel.ob.x = col;
sel.oe.y = sel.ob.y = row;
@ -474,13 +458,12 @@ selextend(int col, int row, int type, int done)
oldsey = sel.ne.y;
oldtype = sel.type;
sel.alt = IS_SET(MODE_ALTSCREEN);
sel.oe.x = col;
sel.oe.y = row;
selnormalize();
sel.type = type;
if (oldey != sel.oe.y || oldex != sel.oe.x || oldtype != sel.type)
if (oldey != sel.oe.y || oldex != sel.oe.x || oldtype != sel.type || sel.mode == SEL_EMPTY)
tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
sel.mode = done ? SEL_IDLE : SEL_READY;
@ -650,7 +633,8 @@ getsel(void)
* st.
* FIXME: Fix the computer world.
*/
if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
if ((y < sel.ne.y || lastx >= linelen) &&
(!(last->mode & ATTR_WRAP) || sel.type == SEL_RECTANGULAR))
*ptr++ = '\n';
}
*ptr = 0;
@ -681,13 +665,13 @@ die(const char *errstr, ...)
void
execsh(char *cmd, char **args)
{
char *sh, *prog;
char *sh, *prog, *arg;
const struct passwd *pw;
errno = 0;
if ((pw = getpwuid(getuid())) == NULL) {
if (errno)
die("getpwuid:%s\n", strerror(errno));
die("getpwuid: %s\n", strerror(errno));
else
die("who are you?\n");
}
@ -695,13 +679,20 @@ execsh(char *cmd, char **args)
if ((sh = getenv("SHELL")) == NULL)
sh = (pw->pw_shell[0]) ? pw->pw_shell : cmd;
if (args)
if (args) {
prog = args[0];
else if (utmp)
arg = NULL;
} else if (scroll) {
prog = scroll;
arg = utmp ? utmp : sh;
} else if (utmp) {
prog = utmp;
else
arg = NULL;
} else {
prog = sh;
DEFAULT(args, ((char *[]) {prog, NULL}));
arg = NULL;
}
DEFAULT(args, ((char *[]) {prog, arg, NULL}));
unsetenv("COLUMNS");
unsetenv("LINES");
@ -730,14 +721,16 @@ sigchld(int a)
pid_t p;
if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
die("waiting for pid %hd failed: %s\n", pid, strerror(errno));
if (pid != p)
return;
if (!WIFEXITED(stat) || WEXITSTATUS(stat))
die("child finished with error '%d'\n", stat);
exit(0);
if (WIFEXITED(stat) && WEXITSTATUS(stat))
die("child exited with status %d\n", WEXITSTATUS(stat));
else if (WIFSIGNALED(stat))
die("child terminated due to signal %d\n", WTERMSIG(stat));
_exit(0);
}
void
@ -781,7 +774,8 @@ ttynew(char *line, char *cmd, char *out, char **args)
if (line) {
if ((cmdfd = open(line, O_RDWR)) < 0)
die("open line failed: %s\n", strerror(errno));
die("open line '%s' failed: %s\n",
line, strerror(errno));
dup2(cmdfd, 0);
stty(args);
return cmdfd;
@ -793,7 +787,7 @@ ttynew(char *line, char *cmd, char *out, char **args)
switch (pid = fork()) {
case -1:
die("fork failed\n");
die("fork failed: %s\n", strerror(errno));
break;
case 0:
close(iofd);
@ -805,9 +799,17 @@ ttynew(char *line, char *cmd, char *out, char **args)
die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
close(s);
close(m);
#ifdef __OpenBSD__
if (pledge("stdio getpw proc exec", NULL) == -1)
die("pledge\n");
#endif
execsh(cmd, args);
break;
default:
#ifdef __OpenBSD__
if (pledge("stdio rpath tty proc", NULL) == -1)
die("pledge\n");
#endif
close(s);
cmdfd = m;
signal(SIGCHLD, sigchld);
@ -821,21 +823,25 @@ ttyread(void)
{
static char buf[BUFSIZ];
static int buflen = 0;
int written;
int ret;
int ret, written;
/* append read bytes to unprocessed bytes */
if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
die("Couldn't read from shell: %s\n", strerror(errno));
buflen += ret;
ret = read(cmdfd, buf+buflen, LEN(buf)-buflen);
written = twrite(buf, buflen, 0);
buflen -= written;
/* keep any uncomplete utf8 char for the next call */
if (buflen > 0)
memmove(buf, buf + written, buflen);
return ret;
switch (ret) {
case 0:
exit(0);
case -1:
die("couldn't read from shell: %s\n", strerror(errno));
default:
buflen += ret;
written = twrite(buf, buflen, 0);
buflen -= written;
/* keep any incomplete UTF-8 byte sequence for the next call */
if (buflen > 0)
memmove(buf, buf + written, buflen);
return ret;
}
}
void
@ -1098,27 +1104,17 @@ selscroll(int orig, int n)
if (sel.ob.x == -1)
return;
if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
if (BETWEEN(sel.nb.y, orig, term.bot) != BETWEEN(sel.ne.y, orig, term.bot)) {
selclear();
} else if (BETWEEN(sel.nb.y, orig, term.bot)) {
sel.ob.y += n;
sel.oe.y += n;
if (sel.ob.y < term.top || sel.ob.y > term.bot ||
sel.oe.y < term.top || sel.oe.y > term.bot) {
selclear();
return;
}
if (sel.type == SEL_RECTANGULAR) {
if (sel.ob.y < term.top)
sel.ob.y = term.top;
if (sel.oe.y > term.bot)
sel.oe.y = term.bot;
} else {
if (sel.ob.y < term.top) {
sel.ob.y = term.top;
sel.ob.x = 0;
}
if (sel.oe.y > term.bot) {
sel.oe.y = term.bot;
sel.oe.x = term.col;
}
selnormalize();
}
selnormalize();
}
}
@ -1447,7 +1443,8 @@ tsetattr(int *attr, int l)
} else {
fprintf(stderr,
"erresc(default): gfx attr %d unknown\n",
attr[i]), csidump();
attr[i]);
csidump();
}
break;
}
@ -1567,6 +1564,7 @@ tsetmode(int priv, int set, int *args, int narg)
case 1015: /* urxvt mangled mouse mode; incompatible
and can be mistaken for other control
codes. */
break;
default:
fprintf(stderr,
"erresc: unknown private set/reset mode %d\n",
@ -1648,6 +1646,12 @@ csihandle(void)
if (csiescseq.arg[0] == 0)
ttywrite(vtiden, strlen(vtiden), 0);
break;
case 'b': /* REP -- if last char is printable print it <n> more times */
DEFAULT(csiescseq.arg[0], 1);
if (term.lastc)
while (csiescseq.arg[0]-- > 0)
tputc(term.lastc);
break;
case 'C': /* CUF -- Cursor <n> Forward */
case 'a': /* HPR -- Cursor <n> Forward */
DEFAULT(csiescseq.arg[0], 1);
@ -1771,7 +1775,7 @@ csihandle(void)
break;
case 'n': /* DSR Device Status Report (cursor position) */
if (csiescseq.arg[0] == 6) {
len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
len = snprintf(buf, sizeof(buf), "\033[%i;%iR",
term.c.y+1, term.c.x+1);
ttywrite(buf, len, 0);
}
@ -1808,7 +1812,7 @@ csihandle(void)
void
csidump(void)
{
int i;
size_t i;
uint c;
fprintf(stderr, "ESC[");
@ -1838,7 +1842,7 @@ csireset(void)
void
strhandle(void)
{
char *p = NULL;
char *p = NULL, *dec;
int j, narg, par;
term.esc &= ~(ESC_STR_END|ESC_STR);
@ -1855,9 +1859,7 @@ strhandle(void)
xsettitle(strescseq.args[1]);
return;
case 52:
if (narg > 2) {
char *dec;
if (narg > 2 && allowwindowops) {
dec = base64dec(strescseq.args[2]);
if (dec) {
xsetsel(dec);
@ -1875,7 +1877,10 @@ strhandle(void)
case 104: /* color reset, here p = NULL */
j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
if (xsetcolorname(j, p)) {
fprintf(stderr, "erresc: invalid color %s\n", p);
if (par == 104 && narg <= 1)
return; /* color reset without parameter */
fprintf(stderr, "erresc: invalid color j=%d, p=%s\n",
j, p ? p : "(null)");
} else {
/*
* TODO if defaultbg color is changed, borders
@ -1890,7 +1895,6 @@ strhandle(void)
xsettitle(strescseq.args[0]);
return;
case 'P': /* DCS -- Device Control String */
term.mode |= ESC_DCS;
case '_': /* APC -- Application Program Command */
case '^': /* PM -- Privacy Message */
return;
@ -1925,7 +1929,7 @@ strparse(void)
void
strdump(void)
{
int i;
size_t i;
uint c;
fprintf(stderr, "ESC%c", strescseq.type);
@ -1952,7 +1956,10 @@ strdump(void)
void
strreset(void)
{
memset(&strescseq, 0, sizeof(strescseq));
strescseq = (STREscape){
.buf = xrealloc(strescseq.buf, STR_BUF_SIZ),
.siz = STR_BUF_SIZ,
};
}
void
@ -1972,28 +1979,6 @@ tprinter(char *s, size_t len)
}
}
void
iso14755(const Arg *arg)
{
FILE *p;
char *us, *e, codepoint[9], uc[UTF_SIZ];
unsigned long utf32;
if (!(p = popen(ISO14755CMD, "r")))
return;
us = fgets(codepoint, sizeof(codepoint), p);
pclose(p);
if (!us || *us == '\0' || *us == '-' || strlen(us) > 7)
return;
if ((utf32 = strtoul(us, &e, 16)) == ULONG_MAX ||
(*e != '\n' && *e != '\0'))
return;
ttywrite(uc, utf8encode(utf32, uc), 1);
}
void
toggleprinter(const Arg *arg)
{
@ -2032,7 +2017,7 @@ tdumpline(int n)
bp = &term.line[n][0];
end = &bp[MIN(tlinelen(n), term.col) - 1];
if (bp != end || bp->u != ' ') {
for ( ;bp <= end; ++bp)
for ( ; bp <= end; ++bp)
tprinter(buf, utf8encode(bp->u, buf));
}
tprinter("\n", 1);
@ -2103,12 +2088,9 @@ tdectest(char c)
void
tstrsequence(uchar c)
{
strreset();
switch (c) {
case 0x90: /* DCS -- Device Control String */
c = 'P';
term.esc |= ESC_DCS;
break;
case 0x9f: /* APC -- Application Program Command */
c = '_';
@ -2120,6 +2102,7 @@ tstrsequence(uchar c)
c = ']';
break;
}
strreset();
strescseq.type = c;
term.esc |= ESC_STR;
}
@ -2162,6 +2145,7 @@ tcontrolcode(uchar ascii)
return;
case '\032': /* SUB */
tsetchar('?', &term.c.attr, term.c.x, term.c.y);
/* FALLTHROUGH */
case '\030': /* CAN */
csireset();
break;
@ -2278,7 +2262,7 @@ eschandle(uchar ascii)
case 'Z': /* DECID -- Identify Terminal */
ttywrite(vtiden, strlen(vtiden), 0);
break;
case 'c': /* RIS -- Reset to inital state */
case 'c': /* RIS -- Reset to initial state */
treset();
resettitle();
xloadcols();
@ -2316,15 +2300,13 @@ tputc(Rune u)
Glyph *gp;
control = ISCONTROL(u);
if (!IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
if (u < 127 || !IS_SET(MODE_UTF8)) {
c[0] = u;
width = len = 1;
} else {
len = utf8encode(u, c);
if (!control && (width = wcwidth(u)) == -1) {
memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
if (!control && (width = wcwidth(u)) == -1)
width = 1;
}
}
if (IS_SET(MODE_PRINT))
@ -2339,25 +2321,12 @@ tputc(Rune u)
if (term.esc & ESC_STR) {
if (u == '\a' || u == 030 || u == 032 || u == 033 ||
ISCONTROLC1(u)) {
term.esc &= ~(ESC_START|ESC_STR|ESC_DCS);
if (IS_SET(MODE_SIXEL)) {
/* TODO: render sixel */;
term.mode &= ~MODE_SIXEL;
return;
}
term.esc &= ~(ESC_START|ESC_STR);
term.esc |= ESC_STR_END;
goto check_control_code;
}
if (IS_SET(MODE_SIXEL)) {
/* TODO: implement sixel mode */
return;
}
if (term.esc&ESC_DCS && strescseq.len == 0 && u == 'q')
term.mode |= MODE_SIXEL;
if (strescseq.len+len >= sizeof(strescseq.buf)-1) {
if (strescseq.len+len >= strescseq.siz) {
/*
* Here is a bug in terminals. If the user never sends
* some code to stop the str or esc command, then st
@ -2371,7 +2340,10 @@ tputc(Rune u)
* term.esc = 0;
* strhandle();
*/
return;
if (strescseq.siz > (SIZE_MAX - UTF_SIZ) / 2)
return;
strescseq.siz *= 2;
strescseq.buf = xrealloc(strescseq.buf, strescseq.siz);
}
memmove(&strescseq.buf[strescseq.len], c, len);
@ -2390,6 +2362,8 @@ check_control_code:
/*
* control codes are not shown ever
*/
if (!term.esc)
term.lastc = 0;
return;
} else if (term.esc & ESC_START) {
if (term.esc & ESC_CSI) {
@ -2420,7 +2394,7 @@ check_control_code:
*/
return;
}
if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
if (selected(term.c.x, term.c.y))
selclear();
gp = &term.line[term.c.y][term.c.x];
@ -2439,6 +2413,7 @@ check_control_code:
}
tsetchar(u, &term.c.attr, term.c.x, term.c.y);
term.lastc = u;
if (width == 2) {
gp->mode |= ATTR_WIDE;
@ -2462,7 +2437,7 @@ twrite(const char *buf, int buflen, int show_ctrl)
int n;
for (n = 0; n < buflen; n += charsize) {
if (IS_SET(MODE_UTF8) && !IS_SET(MODE_SIXEL)) {
if (IS_SET(MODE_UTF8)) {
/* process a complete utf8 char */
charsize = utf8decode(buf + n, &u, buflen - n);
if (charsize == 0)
@ -2578,6 +2553,7 @@ void
drawregion(int x1, int y1, int x2, int y2)
{
int y;
for (y = y1; y < y2; y++) {
if (!term.dirty[y])
continue;
@ -2590,7 +2566,7 @@ drawregion(int x1, int y1, int x2, int y2)
void
draw(void)
{
int cx = term.c.x;
int cx = term.c.x, ocx = term.ocx, ocy = term.ocy;
if (!xstartdraw())
return;
@ -2606,8 +2582,11 @@ draw(void)
drawregion(0, 0, term.col, term.row);
xdrawcursor(cx, term.c.y, term.line[term.c.y][cx],
term.ocx, term.ocy, term.line[term.ocy][term.ocx]);
term.ocx = cx, term.ocy = term.c.y;
term.ocx = cx;
term.ocy = term.c.y;
xfinishdraw();
if (ocx != term.ocx || ocy != term.ocy)
xximspot(term.ocx, term.ocy);
}
void

6
st.h
View File

@ -74,13 +74,13 @@ typedef union {
uint ui;
float f;
const void *v;
const char *s;
} Arg;
void die(const char *, ...);
void redraw(void);
void draw(void);
void iso14755(const Arg *);
void printscreen(const Arg *);
void printsel(const Arg *);
void sendbreak(const Arg *);
@ -113,10 +113,12 @@ char *xstrdup(char *);
/* config.h globals */
extern char *utmp;
extern char *scroll;
extern char *stty_args;
extern char *vtiden;
extern char *worddelimiters;
extern wchar_t *worddelimiters;
extern int allowaltscreen;
extern int allowwindowops;
extern char *termname;
extern unsigned int tabspaces;
extern unsigned int defaultfg;

37
st.info
View File

@ -1,4 +1,4 @@
st| simpleterm,
st-mono| simpleterm monocolor,
acsc=+C\,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,
am,
bce,
@ -10,7 +10,7 @@ st| simpleterm,
civis=\E[?25l,
clear=\E[H\E[2J,
cnorm=\E[?12l\E[?25h,
colors#8,
colors#2,
cols#80,
cr=^M,
csr=\E[%i%p1%d;%p2%dr,
@ -158,6 +158,7 @@ st| simpleterm,
rc=\E8,
rev=\E[7m,
ri=\EM,
rin=\E[%p1%dT,
ritm=\E[23m,
rmacs=\E(B,
rmcup=\E[?1049l,
@ -168,13 +169,8 @@ st| simpleterm,
rs1=\Ec,
rs2=\E[4l\E>\E[?1034l,
sc=\E7,
setab=\E[4%p1%dm,
setaf=\E[3%p1%dm,
setb=\E[4%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m,
setf=\E[3%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m,
sgr0=\E[0m,
sgr=%?%p9%t\E(0%e\E(B%;\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p1%p3%|%t;7%;%?%p4%t;5%;%?%p7%t;8%;m,
sitm=\E[3m,
sgr0=\E[0m,
smacs=\E(0,
smcup=\E[?1049h,
smir=\E[4h,
@ -188,11 +184,22 @@ st| simpleterm,
# XTerm extensions
rmxx=\E[29m,
smxx=\E[9m,
# disabled rep for now: causes some issues with older ncurses versions.
# rep=%p1%c\E[%p2%{1}%-%db,
# tmux extensions, see TERMINFO EXTENSIONS in tmux(1)
Se,
Ss,
Tc,
Ms=\E]52;%p1%s;%p2%s\007,
Se=\E[2 q,
Ss=\E[%p1%d q,
st| simpleterm,
use=st-mono,
colors#8,
setab=\E[4%p1%dm,
setaf=\E[3%p1%dm,
setb=\E[4%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m,
setf=\E[3%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m,
sgr=%?%p9%t\E(0%e\E(B%;\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p1%p3%|%t;7%;%?%p4%t;5%;%?%p7%t;8%;m,
st-256color| simpleterm with 256 colors,
use=st,
@ -220,3 +227,13 @@ st-meta-256color| simpleterm with meta key and 256 colors,
smm=\E[?1034h,
rs2=\E[4l\E>\E[?1034h,
is2=\E[4l\E>\E[?1034h,
st-bs| simpleterm with backspace as backspace,
use=st,
kbs=\010,
kdch1=\177,
st-bs-256color| simpleterm with backspace as backspace and 256colors,
use=st-256color,
kbs=\010,
kdch1=\177,

1
win.h
View File

@ -36,3 +36,4 @@ void xsetmode(int, unsigned int);
void xsetpointermotion(int);
void xsetsel(char *);
int xstartdraw(void);
void xximspot(int, int);

381
x.c
View File

@ -15,7 +15,7 @@
#include <X11/Xft/Xft.h>
#include <X11/XKBlib.h>
static char *argv0;
char *argv0;
#include "arg.h"
#include "st.h"
#include "win.h"
@ -29,9 +29,11 @@ typedef struct {
} Shortcut;
typedef struct {
uint b;
uint mask;
char *s;
uint mod;
uint button;
void (*func)(const Arg *);
const Arg arg;
uint release;
} MouseShortcut;
typedef struct {
@ -56,6 +58,7 @@ static void selpaste(const Arg *);
static void zoom(const Arg *);
static void zoomabs(const Arg *);
static void zoomreset(const Arg *);
static void ttysend(const Arg *);
/* config.h for applying patches and the configuration. */
#include "config.h"
@ -91,8 +94,12 @@ typedef struct {
Drawable buf;
GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
Atom xembed, wmdeletewin, netwmname, netwmpid;
XIM xim;
XIC xic;
struct {
XIM xim;
XIC xic;
XPoint spot;
XVaNestedList spotlist;
} ime;
Draw draw;
Visual *vis;
XSetWindowAttributes attrs;
@ -139,6 +146,10 @@ static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
static void xdrawglyph(Glyph, int, int);
static void xclear(int, int, int, int);
static int xgeommasktogravity(int);
static int ximopen(Display *);
static void ximinstantiate(Display *, XPointer, XPointer);
static void ximdestroy(XIM, XPointer, XPointer);
static int xicdestroy(XIC, XPointer, XPointer);
static void xinit(int, int);
static void cresize(int, int);
static void xresize(int, int);
@ -160,6 +171,8 @@ static void kpress(XEvent *);
static void cmessage(XEvent *);
static void resize(XEvent *);
static void focus(XEvent *);
static uint buttonmask(uint);
static int mouseaction(XEvent *, uint);
static void brelease(XEvent *);
static void bpress(XEvent *);
static void bmotion(XEvent *);
@ -223,8 +236,9 @@ typedef struct {
} Fontcache;
/* Fontcache is an array now. A new font will be appended to the array. */
static Fontcache frc[16];
static Fontcache *frc = NULL;
static int frclen = 0;
static int frccap = 0;
static char *usedfont = NULL;
static double usedfontsize = 0;
static double defaultfontsize = 0;
@ -308,6 +322,12 @@ zoomreset(const Arg *arg)
}
}
void
ttysend(const Arg *arg)
{
ttywrite(arg->s, strlen(arg->s), 1);
}
int
evcol(XEvent *e)
{
@ -328,7 +348,7 @@ void
mousesel(XEvent *e, int done)
{
int type, seltype = SEL_REGULAR;
uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
for (type = 1; type < LEN(selmasks); ++type) {
if (match(selmasks[type], state)) {
@ -404,25 +424,51 @@ mousereport(XEvent *e)
ttywrite(buf, len, 0);
}
uint
buttonmask(uint button)
{
return button == Button1 ? Button1Mask
: button == Button2 ? Button2Mask
: button == Button3 ? Button3Mask
: button == Button4 ? Button4Mask
: button == Button5 ? Button5Mask
: 0;
}
int
mouseaction(XEvent *e, uint release)
{
MouseShortcut *ms;
/* ignore Button<N>mask for Button<N> - it's set on release */
uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
if (ms->release == release &&
ms->button == e->xbutton.button &&
(match(ms->mod, state) || /* exact or forced */
match(ms->mod, state & ~forcemousemod))) {
ms->func(&(ms->arg));
return 1;
}
}
return 0;
}
void
bpress(XEvent *e)
{
struct timespec now;
MouseShortcut *ms;
int snap;
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
if (e->xbutton.button == ms->b
&& match(ms->mask, e->xbutton.state)) {
ttywrite(ms->s, strlen(ms->s), 1);
return;
}
}
if (mouseaction(e, 0))
return;
if (e->xbutton.button == Button1) {
/*
@ -638,21 +684,21 @@ xsetsel(char *str)
void
brelease(XEvent *e)
{
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
if (e->xbutton.button == Button2)
selpaste(NULL);
else if (e->xbutton.button == Button1)
if (mouseaction(e, 1))
return;
if (e->xbutton.button == Button1)
mousesel(e, 1);
}
void
bmotion(XEvent *e)
{
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
@ -672,6 +718,8 @@ cresize(int width, int height)
col = (win.w - 2 * borderpx) / win.cw;
row = (win.h - 2 * borderpx) / win.ch;
col = MAX(1, col);
row = MAX(1, row);
tresize(col, row);
xresize(col, row);
@ -681,8 +729,8 @@ cresize(int width, int height)
void
xresize(int col, int row)
{
win.tw = MAX(1, col * win.cw);
win.th = MAX(1, row * win.ch);
win.tw = col * win.cw;
win.th = row * win.ch;
XFreePixmap(xw.dpy, xw.buf);
xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
@ -731,20 +779,20 @@ xloadcols(void)
static int loaded;
Color *cp;
dc.collen = MAX(LEN(colorname), 256);
dc.col = xmalloc(dc.collen * sizeof(Color));
if (loaded) {
for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
} else {
dc.collen = MAX(LEN(colorname), 256);
dc.col = xmalloc(dc.collen * sizeof(Color));
}
for (i = 0; i < dc.collen; i++)
if (!xloadcolor(i, NULL, &dc.col[i])) {
if (colorname[i])
die("Could not allocate color '%s'\n", colorname[i]);
die("could not allocate color '%s'\n", colorname[i]);
else
die("Could not allocate color %d\n", i);
die("could not allocate color %d\n", i);
}
loaded = 1;
}
@ -757,7 +805,6 @@ xsetcolorname(int x, const char *name)
if (!BETWEEN(x, 0, dc.collen))
return 1;
if (!xloadcolor(x, name, &ncolor))
return 1;
@ -788,15 +835,17 @@ xhints(void)
sizeh = XAllocSizeHints();
sizeh->flags = PSize | PResizeInc | PBaseSize;
sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
sizeh->height = win.h;
sizeh->width = win.w;
sizeh->height_inc = win.ch;
sizeh->width_inc = win.cw;
sizeh->base_height = 2 * borderpx;
sizeh->base_width = 2 * borderpx;
sizeh->min_height = win.ch + 2 * borderpx;
sizeh->min_width = win.cw + 2 * borderpx;
if (xw.isfixed) {
sizeh->flags |= PMaxSize | PMinSize;
sizeh->flags |= PMaxSize;
sizeh->min_width = sizeh->max_width = win.w;
sizeh->min_height = sizeh->max_height = win.h;
}
@ -869,7 +918,7 @@ xloadfont(Font *f, FcPattern *pattern)
if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
&haveattr) != XftResultMatch) || haveattr < wantattr) {
f->badslant = 1;
fputs("st: font slant does not match\n", stderr);
fputs("font slant does not match\n", stderr);
}
}
@ -878,7 +927,7 @@ xloadfont(Font *f, FcPattern *pattern)
if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
&haveattr) != XftResultMatch) || haveattr != wantattr) {
f->badweight = 1;
fputs("st: font weight does not match\n", stderr);
fputs("font weight does not match\n", stderr);
}
}
@ -906,14 +955,13 @@ xloadfonts(char *fontstr, double fontsize)
FcPattern *pattern;
double fontval;
if (fontstr[0] == '-') {
if (fontstr[0] == '-')
pattern = XftXlfdParse(fontstr, False, False);
} else {
else
pattern = FcNameParse((FcChar8 *)fontstr);
}
if (!pattern)
die("st: can't open font %s\n", fontstr);
die("can't open font %s\n", fontstr);
if (fontsize > 1) {
FcPatternDel(pattern, FC_PIXEL_SIZE);
@ -939,7 +987,7 @@ xloadfonts(char *fontstr, double fontsize)
}
if (xloadfont(&dc.font, pattern))
die("st: can't open font %s\n", fontstr);
die("can't open font %s\n", fontstr);
if (usedfontsize < 0) {
FcPatternGetDouble(dc.font.match->pattern,
@ -956,17 +1004,17 @@ xloadfonts(char *fontstr, double fontsize)
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
if (xloadfont(&dc.ifont, pattern))
die("st: can't open font %s\n", fontstr);
die("can't open font %s\n", fontstr);
FcPatternDel(pattern, FC_WEIGHT);
FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
if (xloadfont(&dc.ibfont, pattern))
die("st: can't open font %s\n", fontstr);
die("can't open font %s\n", fontstr);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
if (xloadfont(&dc.bfont, pattern))
die("st: can't open font %s\n", fontstr);
die("can't open font %s\n", fontstr);
FcPatternDestroy(pattern);
}
@ -993,6 +1041,60 @@ xunloadfonts(void)
xunloadfont(&dc.ibfont);
}
int
ximopen(Display *dpy)
{
XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
if (xw.ime.xim == NULL)
return 0;
if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
fprintf(stderr, "XSetIMValues: "
"Could not set XNDestroyCallback.\n");
xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
NULL);
if (xw.ime.xic == NULL) {
xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, xw.win,
XNDestroyCallback, &icdestroy,
NULL);
}
if (xw.ime.xic == NULL)
fprintf(stderr, "XCreateIC: Could not create input context.\n");
return 1;
}
void
ximinstantiate(Display *dpy, XPointer client, XPointer call)
{
if (ximopen(dpy))
XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
}
void
ximdestroy(XIM xim, XPointer client, XPointer call)
{
xw.ime.xim = NULL;
XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
XFree(xw.ime.spotlist);
}
int
xicdestroy(XIC xim, XPointer client, XPointer call)
{
xw.ime.xic = NULL;
return 1;
}
void
xinit(int cols, int rows)
{
@ -1003,13 +1105,13 @@ xinit(int cols, int rows)
XColor xmousefg, xmousebg;
if (!(xw.dpy = XOpenDisplay(NULL)))
die("Can't open display\n");
die("can't open display\n");
xw.scr = XDefaultScreen(xw.dpy);
xw.vis = XDefaultVisual(xw.dpy, xw.scr);
/* font */
if (!FcInit())
die("Could not init fontconfig.\n");
die("could not init fontconfig.\n");
usedfont = (opt_font == NULL)? font : opt_font;
xloadfonts(usedfont, 0);
@ -1030,7 +1132,7 @@ xinit(int cols, int rows)
xw.attrs.background_pixel = dc.col[defaultbg].pixel;
xw.attrs.border_pixel = dc.col[defaultbg].pixel;
xw.attrs.bit_gravity = NorthWestGravity;
xw.attrs.event_mask = FocusChangeMask | KeyPressMask
xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
| ExposureMask | VisibilityChangeMask | StructureNotifyMask
| ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
xw.attrs.colormap = xw.cmap;
@ -1058,22 +1160,10 @@ xinit(int cols, int rows)
xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
/* input methods */
if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
XSetLocaleModifiers("@im=local");
if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
XSetLocaleModifiers("@im=");
if ((xw.xim = XOpenIM(xw.dpy,
NULL, NULL, NULL)) == NULL) {
die("XOpenIM failed. Could not open input"
" device.\n");
}
}
if (!ximopen(xw.dpy)) {
XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
}
xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
| XIMStatusNothing, XNClientWindow, xw.win,
XNFocusWindow, xw.win, NULL);
if (xw.xic == NULL)
die("XCreateIC failed. Could not obtain input method.\n");
/* white cursor, black outline */
cursor = XCreateFontCursor(xw.dpy, mouseshape);
@ -1104,8 +1194,8 @@ xinit(int cols, int rows)
win.mode = MODE_NUMLOCK;
resettitle();
XMapWindow(xw.dpy, xw.win);
xhints();
XMapWindow(xw.dpy, xw.win);
XSync(xw.dpy, False);
clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
@ -1215,13 +1305,10 @@ xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x
fontpattern = FcFontSetMatch(0, fcsets, 1,
fcpattern, &fcres);
/*
* Overwrite or create the new cache entry.
*/
if (frclen >= LEN(frc)) {
frclen = LEN(frc) - 1;
XftFontClose(xw.dpy, frc[frclen].font);
frc[frclen].unicodep = 0;
/* Allocate memory for the new cache entry. */
if (frclen >= frccap) {
frccap += 16;
frc = xrealloc(frc, frccap * sizeof(Fontcache));
}
frc[frclen].font = XftFontOpenPattern(xw.dpy,
@ -1439,8 +1526,9 @@ xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
/* draw the new one */
if (IS_SET(MODE_FOCUSED)) {
switch (win.cursor) {
case 7: /* st extension: snowman (U+2603) */
g.u = 0x2603;
case 7: /* st extension */
g.u = 0x2603; /* snowman (U+2603) */
/* FALLTHROUGH */
case 0: /* Blinking Block */
case 1: /* Blinking Block (Default) */
case 2: /* Steady Block */
@ -1551,6 +1639,18 @@ xfinishdraw(void)
defaultfg : defaultbg].pixel);
}
void
xximspot(int x, int y)
{
if (xw.ime.xic == NULL)
return;
xw.ime.spot.x = borderpx + x * win.cw;
xw.ime.spot.y = borderpx + (y + 1) * win.ch;
XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
}
void
expose(XEvent *ev)
{
@ -1590,8 +1690,7 @@ xsetmode(int set, unsigned int flags)
int
xsetcursor(int cursor)
{
DEFAULT(cursor, 1);
if (!BETWEEN(cursor, 0, 6))
if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */
return 1;
win.cursor = cursor;
return 0;
@ -1625,13 +1724,15 @@ focus(XEvent *ev)
return;
if (ev->type == FocusIn) {
XSetICFocus(xw.xic);
if (xw.ime.xic)
XSetICFocus(xw.ime.xic);
win.mode |= MODE_FOCUSED;
xseturgency(0);
if (IS_SET(MODE_FOCUS))
ttywrite("\033[I", 3, 0);
} else {
XUnsetICFocus(xw.xic);
if (xw.ime.xic)
XUnsetICFocus(xw.ime.xic);
win.mode &= ~MODE_FOCUSED;
if (IS_SET(MODE_FOCUS))
ttywrite("\033[O", 3, 0);
@ -1686,7 +1787,7 @@ kpress(XEvent *ev)
{
XKeyEvent *e = &ev->xkey;
KeySym ksym;
char buf[32], *customkey;
char buf[64], *customkey;
int len;
Rune c;
Status status;
@ -1695,7 +1796,10 @@ kpress(XEvent *ev)
if (IS_SET(MODE_KBDLOCK))
return;
len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
if (xw.ime.xic)
len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
else
len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
/* 1. shortcuts */
for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
if (ksym == bp->keysym && match(bp->mod, e->state)) {
@ -1728,7 +1832,6 @@ kpress(XEvent *ev)
ttywrite(buf, len, 1);
}
void
cmessage(XEvent *e)
{
@ -1764,10 +1867,9 @@ run(void)
XEvent ev;
int w = win.w, h = win.h;
fd_set rfd;
int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
int ttyfd;
struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
long deltatime;
int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
struct timespec seltv, *tv, now, lastblink, trigger;
double timeout;
/* Waiting for window mapping */
do {
@ -1788,82 +1890,77 @@ run(void)
ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
cresize(w, h);
clock_gettime(CLOCK_MONOTONIC, &last);
lastblink = last;
for (xev = actionfps;;) {
for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
FD_ZERO(&rfd);
FD_SET(ttyfd, &rfd);
FD_SET(xfd, &rfd);
if (XPending(xw.dpy))
timeout = 0; /* existing events might not set xfd */
seltv.tv_sec = timeout / 1E3;
seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
tv = timeout >= 0 ? &seltv : NULL;
if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
if (errno == EINTR)
continue;
die("select failed: %s\n", strerror(errno));
}
if (FD_ISSET(ttyfd, &rfd)) {
ttyread();
if (blinktimeout) {
blinkset = tattrset(ATTR_BLINK);
if (!blinkset)
MODBIT(win.mode, 0, MODE_BLINK);
}
}
if (FD_ISSET(xfd, &rfd))
xev = actionfps;
clock_gettime(CLOCK_MONOTONIC, &now);
drawtimeout.tv_sec = 0;
drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
tv = &drawtimeout;
dodraw = 0;
if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
tsetdirtattr(ATTR_BLINK);
win.mode ^= MODE_BLINK;
lastblink = now;
dodraw = 1;
}
deltatime = TIMEDIFF(now, last);
if (deltatime > 1000 / (xev ? xfps : actionfps)) {
dodraw = 1;
last = now;
if (FD_ISSET(ttyfd, &rfd))
ttyread();
xev = 0;
while (XPending(xw.dpy)) {
xev = 1;
XNextEvent(xw.dpy, &ev);
if (XFilterEvent(&ev, None))
continue;
if (handler[ev.type])
(handler[ev.type])(&ev);
}
if (dodraw) {
while (XPending(xw.dpy)) {
XNextEvent(xw.dpy, &ev);
if (XFilterEvent(&ev, None))
continue;
if (handler[ev.type])
(handler[ev.type])(&ev);
/*
* To reduce flicker and tearing, when new content or event
* triggers drawing, we first wait a bit to ensure we got
* everything, and if nothing new arrives - we draw.
* We start with trying to wait minlatency ms. If more content
* arrives sooner, we retry with shorter and shorter periods,
* and eventually draw even without idle after maxlatency ms.
* Typically this results in low latency while interacting,
* maximum latency intervals during `cat huge.txt`, and perfect
* sync with periodic updates from animations/key-repeats/etc.
*/
if (FD_ISSET(ttyfd, &rfd) || xev) {
if (!drawing) {
trigger = now;
drawing = 1;
}
timeout = (maxlatency - TIMEDIFF(now, trigger)) \
/ maxlatency * minlatency;
if (timeout > 0)
continue; /* we have time, try to find idle */
}
draw();
XFlush(xw.dpy);
if (xev && !FD_ISSET(xfd, &rfd))
xev--;
if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
if (blinkset) {
if (TIMEDIFF(now, lastblink) \
> blinktimeout) {
drawtimeout.tv_nsec = 1000;
} else {
drawtimeout.tv_nsec = (1E6 * \
(blinktimeout - \
TIMEDIFF(now,
lastblink)));
}
drawtimeout.tv_sec = \
drawtimeout.tv_nsec / 1E9;
drawtimeout.tv_nsec %= (long)1E9;
} else {
tv = NULL;
}
/* idle detected or maxlatency exhausted -> draw */
timeout = -1;
if (blinktimeout && tattrset(ATTR_BLINK)) {
timeout = blinktimeout - TIMEDIFF(now, lastblink);
if (timeout <= 0) {
if (-timeout > blinktimeout) /* start visible */
win.mode |= MODE_BLINK;
win.mode ^= MODE_BLINK;
tsetdirtattr(ATTR_BLINK);
lastblink = now;
timeout = blinktimeout;
}
}
draw();
XFlush(xw.dpy);
drawing = 0;
}
}
@ -1885,7 +1982,7 @@ main(int argc, char *argv[])
{
xw.l = xw.t = 0;
xw.isfixed = False;
win.cursor = cursorshape;
xsetcursor(cursorshape);
ARGBEGIN {
case 'a':
@ -1925,7 +2022,7 @@ main(int argc, char *argv[])
opt_embed = EARGF(usage());
break;
case 'v':
die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
die("%s " VERSION "\n", argv0);
break;
default:
usage();