#!/usr/bin/env dub
/+ dub.sdl:
name "platform_ui_color_scheme_probe"
targetPath "build"
platforms "posix"
dependency "sparkles:base" path="../../../../.."
dflags "-preview=in" "-preview=dip1000"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/**
* Asking the *terminal* what color scheme it is using.
*
* A terminal application has no window-system connection and no desktop
* session to consult — the only peer that knows what the text will look like is
* the emulator on the other end of the pty. Two escape sequences ask it, and
* this program runs both against whatever terminal it is launched in:
*
* 1. **`CSI ? 996 n`** — the DEC mode 2031 status query. The terminal replies
* `CSI ? 997 ; 1 n` for dark or `CSI ? 997 ; 2 n` for light. This is a
* *semantic* answer: the terminal has already decided, usually by following
* the OS, and no luminance guessing is involved.
* 2. **`OSC 11 ; ? ST`** — the background-color query, answered as
* `OSC 11 ; rgb:RRRR/GGGG/BBBB ST` with 16-bit-per-channel values. The
* caller must classify it itself, which is where the threshold disagreement
* that [../../color-derivation/index.md](../../color-derivation/index.md)
* measures comes from.
*
* It also demonstrates the two hazards the deep-dive documents: the query
* **must** be timed out (a terminal that does not implement a sequence simply
* says nothing, and a blocking read hangs forever), and under `tmux` the
* sequence needs DCS passthrough or it is swallowed.
*
* Companion to docs/research/platform-ui-guidelines/terminal/index.md
* § "DEC mode 2031" and § "Hazards".
*
* Run with: dub run --single color-scheme-probe.d
*
* Portability: POSIX only (termios raw mode). When stdin/stdout is not a tty —
* which is how CI runs it — it prints a `SKIP:` line and exits 0. A terminal
* that answers neither query is reported as such, not as a failure.
*/
module (module) platform_ui_color_scheme_probeAsking the terminal what color scheme it is using.
A terminal application has no window-system connection and no desktop
session to consult — the only peer that knows what the text will look like is
the emulator on the other end of the pty. Two escape sequences ask it, and
this program runs both against whatever terminal it is launched in:
CSI ? 996 n — the DEC mode 2031 status query. The terminal replies
CSI ? 997 ; 1 n for dark or CSI ? 997 ; 2 n for light. This is a
semantic answer: the terminal has already decided, usually by following
the OS, and no luminance guessing is involved.
OSC 11 ; ? ST — the background-color query, answered as
OSC 11 ; rgb:RRRR/GGGG/BBBB ST with 16-bit-per-channel values. The
caller must classify it itself, which is where the threshold disagreement
that ../../color-derivation/index.md
measures comes from.
It also demonstrates the two hazards the deep-dive documents: the query
must be timed out (a terminal that does not implement a sequence simply
says nothing, and a blocking read hangs forever), and under tmux the
sequence needs DCS passthrough or it is swallowed.
Companion to docs/research/platform-ui-guidelines/terminal/index.md
§ "DEC mode 2031" and § "Hazards".
Run with: dub run --single color-scheme-probe.d
Portability
POSIX only (termios raw mode). When stdin/stdout is not a tty —
which is how CI runs it — it prints a SKIP: line and exits 0. A terminal
that answers neither query is reported as such, not as a failure.
platform_ui_color_scheme_probe;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.pollD header file for POSIX.
poll : (alias) platform_ui_color_scheme_probe.poll = int core.sys.posix.poll.poll(core.sys.posix.poll.pollfd*, ulong, int) nothrow @nogcpoll, (struct) core.sys.posix.poll.pollfdpollfd, (alias enum value) platform_ui_color_scheme_probe.POLLIN = core.sys.posix.poll.POLLIN = 1POLLIN;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.termiosD header file for POSIX.
termios : (alias constant) platform_ui_color_scheme_probe.ECHO = int core.sys.posix.termios.ECHO = 8ECHO, (alias constant) platform_ui_color_scheme_probe.ICANON = int core.sys.posix.termios.ICANON = 2ICANON, (alias constant) platform_ui_color_scheme_probe.ISIG = int core.sys.posix.termios.ISIG = 1ISIG, (alias constant) platform_ui_color_scheme_probe.TCSAFLUSH = int core.sys.posix.termios.TCSAFLUSH = 2TCSAFLUSH, (alias constant) platform_ui_color_scheme_probe.TCSANOW = int core.sys.posix.termios.TCSANOW = 0TCSANOW,
(alias) platform_ui_color_scheme_probe.tcgetattr = int core.sys.posix.termios.tcgetattr(int, core.sys.posix.termios.termios*) nothrow @nogctcgetattr, (alias) platform_ui_color_scheme_probe.tcsetattr = int core.sys.posix.termios.tcsetattr(int, int, scope const(core.sys.posix.termios.termios*)) nothrow @nogctcsetattr, (struct) core.sys.posix.termios.termiostermios, (alias constant) platform_ui_color_scheme_probe.VMIN = int core.sys.posix.termios.VMIN = 6VMIN, (alias constant) platform_ui_color_scheme_probe.VTIME = int core.sys.posix.termios.VTIME = 5VTIME;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.unistdD header file for POSIX.
unistd : (alias) platform_ui_color_scheme_probe.read = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread, (alias constant) platform_ui_color_scheme_probe.STDIN_FILENO = int core.sys.posix.unistd.STDIN_FILENO = 0STDIN_FILENO, (alias constant) platform_ui_color_scheme_probe.STDOUT_FILENO = int core.sys.posix.unistd.STDOUT_FILENO = 1STDOUT_FILENO, (alias) platform_ui_color_scheme_probe.write = long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) platform_ui_color_scheme_probe.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to writef(fmt, args, '\n').
writefln, (alias template) platform_ui_color_scheme_probe.writeln = std.stdio.writeln(T...)(T args)Equivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln;
import (package) sparklessparkles.(package) sparkles.basebase.(module) sparkles.base.term_capsTerminal capability probing: the synchronous size query (terminalSize),
tty and color detection (detectTermCaps), and resize notifications
(setTermWindowSizeHandler).
This is the single place the "what can this terminal do" decision is made;
renderers stay pure producers that take explicit widths/flags. It lives in
sparkles:base rather than a UI package because it is an environment query,
not a presentation concern — a logger, a CLI tool and a full-screen UI all need
it, and none of them should pull in a UI stack to ask.
TermSize is deliberately a plain POD rather than a
Vector specialization: base sits below
sparkles:math, and a capability snapshot never does vector arithmetic. The
terminal's geometry types — positions you add offsets to — live in
sparkles:tui (TermPosition), which is free to specialize Vector.
term_caps : (alias) platform_ui_color_scheme_probe.isTerminal = bool sparkles.base.term_caps.isTerminal(sparkles.base.term_caps.StdStream stream = StdStream.stdout) nothrow @nogc @trustedIs stream attached to a terminal? POSIX: isatty; Windows: GetConsoleMode
succeeds (it fails when the handle is redirected — the non-tty check).
isTerminal, (enum) sparkles.base.term_caps.StdStreamA standard stream, for tty queries.
StdStream;
/// How long to wait for a reply before concluding the terminal does not
/// implement the sequence. The deep-dive's recommendation is 100–200 ms: long
/// enough for an ssh round trip, short enough that a non-implementing terminal
/// does not visibly stall startup.
enum (constant) int platform_ui_color_scheme_probe.replyTimeoutMs = 200How long to wait for a reply before concluding the terminal does not
implement the sequence. The deep-dive's recommendation is 100–200 ms: long
enough for an ssh round trip, short enough that a non-implementing terminal
does not visibly stall startup.
replyTimeoutMs = 200;
/// Raw-mode guard: a terminal reply arrives on stdin as ordinary input, so
/// canonical mode (which waits for a newline) and echo (which would paint the
/// reply into the user's scrollback) both have to go.
struct (struct) platform_ui_color_scheme_probe.RawModeRaw-mode guard: a terminal reply arrives on stdin as ordinary input, so
canonical mode (which waits for a newline) and echo (which would paint the
reply into the user's scrollback) both have to go.
RawMode
{
private (struct) core.sys.posix.termios.termiostermios (field) core.sys.posix.termios.termios platform_ui_color_scheme_probe.RawMode.originaloriginal;
private bool (field) bool platform_ui_color_scheme_probe.RawMode.activeactive;
static (struct) platform_ui_color_scheme_probe.RawModeRaw-mode guard: a terminal reply arrives on stdin as ordinary input, so
canonical mode (which waits for a newline) and echo (which would paint the
reply into the user's scrollback) both have to go.
RawMode platform_ui_color_scheme_probe.RawMode platform_ui_color_scheme_probe.RawMode.enter() nothrow @nogc @trustedenter() @trusted nothrow @nogc
{
(struct) platform_ui_color_scheme_probe.RawModeRaw-mode guard: a terminal reply arrives on stdin as ordinary input, so
canonical mode (which waits for a newline) and echo (which would paint the
reply into the user's scrollback) both have to go.
RawMode (local variable) platform_ui_color_scheme_probe.RawMode mm;
if (int core.sys.posix.termios.tcgetattr(int, core.sys.posix.termios.termios*) nothrow @nogctcgetattr((constant) int core.sys.posix.unistd.STDIN_FILENO = 0STDIN_FILENO, &(local variable) platform_ui_color_scheme_probe.RawMode mm.(field) core.sys.posix.termios.termios platform_ui_color_scheme_probe.RawMode.originaloriginal) != 0)
return (local variable) platform_ui_color_scheme_probe.RawMode mm;
(struct) core.sys.posix.termios.termiostermios (local variable) core.sys.posix.termios.termios rawraw = (local variable) platform_ui_color_scheme_probe.RawMode mm.(field) core.sys.posix.termios.termios platform_ui_color_scheme_probe.RawMode.originaloriginal;
(local variable) core.sys.posix.termios.termios rawraw.(field) uint core.sys.posix.termios.termios.c_lflagc_lflag &= ~((constant) int core.sys.posix.termios.ICANON = 2ICANON | (constant) int core.sys.posix.termios.ECHO = 8ECHO);
(local variable) core.sys.posix.termios.termios rawraw.(field) ubyte[32] core.sys.posix.termios.termios.c_ccc_cc[(constant) int core.sys.posix.termios.VMIN = 6VMIN] = 0;
(local variable) core.sys.posix.termios.termios rawraw.(field) ubyte[32] core.sys.posix.termios.termios.c_ccc_cc[(constant) int core.sys.posix.termios.VTIME = 5VTIME] = 0;
if (int core.sys.posix.termios.tcsetattr(int, int, scope const(core.sys.posix.termios.termios*)) nothrow @nogctcsetattr((constant) int core.sys.posix.unistd.STDIN_FILENO = 0STDIN_FILENO, (constant) int core.sys.posix.termios.TCSAFLUSH = 2TCSAFLUSH, &(local variable) core.sys.posix.termios.termios rawraw) == 0)
(local variable) platform_ui_color_scheme_probe.RawMode mm.(field) bool platform_ui_color_scheme_probe.RawMode.activeactive = true;
return (local variable) platform_ui_color_scheme_probe.RawMode mm;
}
~this() @trusted nothrow @nogc
{
if ((field) bool platform_ui_color_scheme_probe.RawMode.activeactive)
int core.sys.posix.termios.tcsetattr(int, int, scope const(core.sys.posix.termios.termios*)) nothrow @nogctcsetattr((constant) int core.sys.posix.unistd.STDIN_FILENO = 0STDIN_FILENO, (constant) int core.sys.posix.termios.TCSANOW = 0TCSANOW, &(field) core.sys.posix.termios.termios platform_ui_color_scheme_probe.RawMode.originaloriginal);
}
}
void void platform_ui_color_scheme_probe.emit(scope const(char)[] bytes) nothrow @nogc @trustedemit(scope const(char)[] (parameter) const(char)[] bytesbytes) @trusted nothrow @nogc
{
long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite((constant) int core.sys.posix.unistd.STDOUT_FILENO = 1STDOUT_FILENO, (parameter) const(char)[] bytesbytes.(field) const(char)* const(char)[].ptrptr, (parameter) const(char)[] bytesbytes.(field) ulong const(char)[].lengthlength);
}
/// Read whatever arrives within `replyTimeoutMs` of *the last* byte seen, so a
/// reply split across packets is still collected whole. Returns the bytes read.
char[] char[] platform_ui_color_scheme_probe.drain(return scope char[] buf) nothrow @nogc @trustedRead whatever arrives within replyTimeoutMs of the last byte seen, so a
reply split across packets is still collected whole. Returns the bytes read.
drain(return scope char[] (parameter) char[] bufbuf) @trusted nothrow @nogc
{
(alias) object.size_t = ulongsize_t (local variable) ulong nn;
while ((local variable) ulong nn < (parameter) char[] bufbuf.(field) ulong char[].lengthlength)
{
(struct) core.sys.posix.poll.pollfdpollfd (local variable) core.sys.posix.poll.pollfd pfdpfd;
(local variable) core.sys.posix.poll.pollfd pfdpfd.(field) int core.sys.posix.poll.pollfd.fdfd = (constant) int core.sys.posix.unistd.STDIN_FILENO = 0STDIN_FILENO;
(local variable) core.sys.posix.poll.pollfd pfdpfd.(field) short core.sys.posix.poll.pollfd.eventsevents = (enum value) core.sys.posix.poll.POLLIN = 1POLLIN;
// First byte gets the full budget; subsequent bytes a short one, since
// the reply is already in flight.
if (int core.sys.posix.poll.poll(core.sys.posix.poll.pollfd*, ulong, int) nothrow @nogcpoll(&(local variable) core.sys.posix.poll.pollfd pfdpfd, 1, (local variable) ulong nn == 0 ? (constant) int platform_ui_color_scheme_probe.replyTimeoutMs = 200How long to wait for a reply before concluding the terminal does not
implement the sequence. The deep-dive's recommendation is 100–200 ms: long
enough for an ssh round trip, short enough that a non-implementing terminal
does not visibly stall startup.
replyTimeoutMs : 20) <= 0)
break;
const (local variable) const(long) gotgot = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread((constant) int core.sys.posix.unistd.STDIN_FILENO = 0STDIN_FILENO, (parameter) char[] bufbuf.(field) char* char[].ptrptr + (local variable) ulong nn, (parameter) char[] bufbuf.(field) ulong char[].lengthlength - (local variable) ulong nn);
if ((local variable) const(long) gotgot <= 0)
break;
(local variable) ulong nn += (local variable) const(long) gotgot;
}
return (parameter) char[] bufbuf[0 .. (local variable) ulong nn];
}
/// `tmux` does not forward an unknown query to the outer terminal and does not
/// answer it either, so a bare probe times out. Wrapping it in DCS passthrough
/// (`ESC P tmux; <escaped> ESC \`, with every ESC doubled) hands it through.
/// See the deep-dive § "Hazards — multiplexers".
(alias) object.string = stringstring string platform_ui_color_scheme_probe.wrapForMultiplexer(string seq) @safetmux does not forward an unknown query to the outer terminal and does not
answer it either, so a bare probe times out. Wrapping it in DCS passthrough
(ESC P tmux; <escaped> ESC \, with every ESC doubled) hands it through.
See the deep-dive § "Hazards — multiplexers".
wrapForMultiplexer((alias) object.string = stringstring (parameter) string seqseq) @safe
{
if ((class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("TMUX") is null)
return (parameter) string seqseq;
(alias) object.string = stringstring (local variable) string escapedescaped;
foreach ((parameter) immutable(char) chch; (parameter) string seqseq)
(local variable) string escapedescaped ~= (local variable) immutable(char) chch == '\x1b' ? "\x1b\x1b" : [(local variable) immutable(char) chch];
return "\x1bPtmux;" ~ (local variable) string escapedescaped ~ "\x1b\\";
}
/// Render a byte string with escapes visible, so the report is copy-pasteable.
(alias) object.string = stringstring string platform_ui_color_scheme_probe.visible(scope const(char)[] s) @safeRender a byte string with escapes visible, so the report is copy-pasteable.
visible(scope const(char)[] (parameter) const(char)[] ss) @safe
{
import (package) stdstd.(module) std.formatThis package provides string formatting functionality using
printf style format strings.
Submodule Function Name Description package format Converts its arguments according to a format string into a string.
| package |
sformat |
Converts its arguments according to a format string into a buffer. |
| package |
FormatException |
Signals a problem while formatting. |
| write |
formattedWrite |
Converts its arguments according to a format string and writes
the result to an output range. |
| write |
formatValue |
Formats a value of any type according to a format specifier and
writes the result to an output range. |
| read |
formattedRead |
Reads an input range according to a format string and stores the read
values into its arguments. |
| read |
unformatValue |
Reads a value from the given input range and converts it according to
a format specifier. |
| spec |
FormatSpec |
A general handler for format strings. |
| spec |
singleSpec |
Helper function that returns a FormatSpec for a single format specifier. |
Limitation
This package does not support localization, but
adheres to the rounding mode of the floating point unit, if
available.
Format Strings
The functions contained in this package use format strings. A
format string describes the layout of another string for reading or
writing purposes. A format string is composed of normal text
interspersed with format specifiers. A format specifier starts
with a percentage sign '%', optionally followed by one or more
parameters and ends with a format indicator. A format
indicator may be a simple format character or a compound
indicator.
Format strings are composed according to the following grammar:
FormatString:
FormatStringItem FormatString
FormatStringItem:
Character
FormatSpecifier
FormatSpecifier:
'%' Parameters FormatIndicator
FormatIndicator:
FormatCharacter
CompoundIndicator
FormatCharacter:
see remark below
CompoundIndicator:
'(' FormatString '%)'
'(' FormatString '%|' Delimiter '%)'
Delimiter
empty
Character Delimiter
Parameters:
Position Flags Width Precision Separator
Position:
empty
Integer '$'**
*Integer* **':'** *Integer* **'$'
Integer ':' '$'**
*Flags*:
*empty*
*Flag* *Flags*
*Flag*:
**'-'**|**'+'**|**' '**|**'0'**|**'#'**|**'='**
*Width*:
*OptionalPositionalInteger*
*Precision*:
*empty*
**'.'** *OptionalPositionalInteger*
*Separator*:
*empty*
**','** *OptionalInteger*
**','** *OptionalInteger* **'?'**
*OptionalInteger*:
*empty*
*Integer*
**'*'**
*OptionalPositionalInteger*:
*OptionalInteger*
**'*'** *Integer* **'$'
Character
'%%'
AnyCharacterExceptPercent
Integer:
NonZeroDigit Digits
Digits:
empty
Digit Digits
NonZeroDigit:
'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Digit:
'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Note
FormatCharacter is unspecified. It can be any character
that has no other purpose in this grammar, but it is
recommended to assign (lower- and uppercase) letters.
Note
The Parameters of a CompoundIndicator are currently
limited to a '-' flag.
Format Indicator
The format indicator can either be a single character or an
expression surrounded by '%(' and '%)'. It specifies the
basic manner in which a value will be formatted and is the minimum
requirement to format a value.
The following characters can be used as format characters:
FormatCharacter Semantics 's' To be formatted in a human readable format. Can be used with all types. 'c' To be formatted as a character. 'd' To be formatted as a signed decimal integer. 'u' To be formatted as a decimal image of the underlying bit representation. 'b' To be formatted as a binary image of the underlying bit representation. 'o' To be formatted as an octal image of the underlying bit representation. 'x' / 'X' To be formatted as a hexadecimal image of the underlying bit representation. 'e' / 'E' To be formatted as a real number in decimal scientific notation. 'f' / 'F' To be formatted as a real number in decimal natural notation. 'g' / 'G' To be formatted as a real number in decimal short notation. Depending on the number, a scientific notation or a natural notation is used. 'a' / 'A' To be formatted as a real number in hexadecimal scientific notation. 'r' To be formatted as raw bytes. The output may not be printable and depends on endianness.
The compound indicator can be used to describe compound types
like arrays or structs in more detail. A compound type is enclosed
within '%(' and '%)'. The enclosed sub-format string is
applied to individual elements. The trailing portion of the
sub-format string following the specifier for the element is
interpreted as the delimiter, and is therefore omitted following the
last element. The '%|' specifier may be used to explicitly
indicate the start of the delimiter, so that the preceding portion of
the string will be included following the last element.
The format string inside of the compound indicator should
contain exactly one format specifier (two in case of associative
arrays), which specifies the formatting mode of the elements of the
compound type. This format specifier can be a compound
indicator itself.
Note
Inside a compound indicator, strings and characters are
escaped automatically. To avoid this behavior, use "%-("
instead of "%(".
Flags
There are several flags that affect the outcome of the formatting.
Flag Semantics '-' When the formatted result is shorter than the value given by the width parameter, the output is left justified. Without the '-' flag, the output remains right justified.
There are two exceptions where the '-' flag has a
different meaning: (1) with 'r' it denotes to use little
endian and (2) in case of a compound indicator it means that
no special handling of the members is applied. |
| '=' |
When the formatted result is shorter than the value
given by the width parameter, the output is centered.
If the central position is not possible it is moved slightly
to the right. In this case, if '-' flag is present in
addition to the '=' flag, it is moved slightly to the left. |
| '+' / *' '* |
Applies to numerical values. By default, positive numbers are not
formatted to include the + sign. With one of these two flags present,
positive numbers are preceded by a plus sign or a space.
When both flags are present, a plus sign is used.
In case of 'r', a big endian format is used. |
| '0' |
Is applied to numerical values that are printed right justified.
If the zero flag is present, the space left to the number is
filled with zeros instead of spaces. |
| '#' |
Denotes that an alternative output must be used. This depends on the type
to be formatted and the format character used. See the
sections below for more information. |
Width, Precision and Separator
The width parameter specifies the minimum width of the result.
The meaning of precision depends on the format indicator. For
integers it denotes the minimum number of digits printed, for
real numbers it denotes the number of fractional digits and for
strings and compound types it denotes the maximum number of elements
that are included in the output.
A separator is used for formatting numbers. If it is specified,
the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by
providing a number or a ''* after the ','.
In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of
digits. If the argument is a negative number, the precision and
separator parameters are considered unspecified. For width,
the absolute value is used and the '-' flag is set.
The separator can also be followed by a '?'. In that case,
an additional argument is used to specify the symbol that should be
used to separate the chunks.
Position
By default, the arguments are processed in the provided order. With
the position parameter it is possible to address arguments
directly. It is also possible to denote a series of arguments with
two numbers separated by ':', that are all processed in the same
way. The second number can be omitted. In that case the series ends
with the last argument.
It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.
Types
This section describes the result of combining types with format
characters. It is organized in 2 subsections: a list of general
information regarding the formatting of types in the presence of
format characters and a table that contains details for every
available combination of type and format character.
When formatting types, the following rules apply:
If the format character is upper case, the resulting string will
be formatted using upper case letters.
The default precision for floating point numbers is 6 digits.
Rounding of floating point numbers adheres to the rounding mode
of the floating point unit, if available.
The floating point values NaN and Infinity are formatted as
nan and inf, possibly preceded by '+' or '-' sign.
Formatting reals is only supported for 64 bit reals and 80 bit reals.
All other reals are cast to double before they are formatted. This will
cause the result to be inf for very large numbers.
Characters and strings formatted with the 's' format character
inside of compound types are surrounded by single and double quotes
and unprintable characters are escaped. To avoid this, a '-'
flag can be specified for the compound specifier
(e.g. "%-(%s%)" instead of "%(%s%)" ).
Structs, unions, classes and interfaces are formatted by calling a
toString method if available.
See module std.format.write for more
details.
Only part of these combinations can be used for reading. See
module std.format.read for more
detailed information.
This table contains descriptions for every possible combination of
type and format character:
<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as... <td rowspan="1">null</td> 's' null
|<td rowspan="3">bool</td> 's' |
false or true |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integrals 0 or 1 with the same format character.
Please note, that 'o' and 'x' with '#' flag
might produce unexpected results due to special handling of
the value 0. |
| 'r' |
\0 or \1 |
|<td rowspan="4">Integral</td> 's', 'd' |
A signed decimal number. The '#' flag is ignored. |
| 'b', 'o', 'u', 'x', 'X' |
An unsigned binary, decimal, octal or hexadecimal number.
In case of 'o' and 'x', the '#' flag
denotes that the number must be preceded by 0 and 0x, with
the exception of the value 0, where this does not apply. For
'b' and 'u' the '#' flag has no effect. |
| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' |
As a floating point value with the same specifier.
Default precision is large enough to add all digits
of the integral value.
In case of 'a' and 'A', the integral digit can be
any hexadecimal digit.
|
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="5">Floating Point</td> 'e', 'E' |
Scientific notation: Exactly one integral digit followed by a dot
and fractional digits, followed by the exponent.
The exponent is formatted as 'e' followed by
a '+' or '-' sign, followed by at least
two digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'f', 'F' |
Natural notation: Integral digits followed by a dot and
fractional digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted.
Please note: the difference between 'f' and 'F'
is only visible for NaN and Infinity. |
| 's', 'g', 'G' |
Short notation: If the absolute value is larger than 10 ^^ precision
or smaller than 0.0001, the scientific notation is used.
If not, the natural notation is applied.
In both cases precision denotes the count of all digits, including
the integral digits. Trailing zeros (including a trailing dot) are removed.
If '#' flag is present, trailing zeros are not removed. |
| 'a', 'A' |
Hexadecimal scientific notation: 0x followed by 1
(or 0 in case of value zero or denormalized number)
followed by a dot, fractional digits in hexadecimal
notation and an exponent. The exponent is build by p,
followed by a sign and the exponent in decimal notation.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">Character</td> 's', 'c' |
As the character.
Inside of a compound indicator 's' is treated differently: The
character is surrounded by single quotes and non printable
characters are escaped. This can be avoided by preceding
the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integral that represents the character. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">String</td> 's' |
The sequence of characters that form the string.
Inside of a compound indicator the string is surrounded by double quotes
and non printable characters are escaped. This can be avoided
by preceding the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'r' |
The sequence of characters, each formatted with 'r'. |
| compound |
As an array of characters. |
|<td rowspan="3">Array</td> 's' |
When the elements are characters, the array is formatted as
a string. In all other cases the array is surrounded by square brackets
and the elements are separated by a comma and a space. If the elements
are strings, they are surrounded by double quotes and non
printable characters are escaped. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="2">Associative Array</td> 's' |
As a sequence of the elements in unpredictable order. The output is
surrounded by square brackets. The elements are separated by a
comma and a space. The elements are formatted as key:value. |
| compound |
As a sequence of the elements in unpredictable order. Each element
is formatted according to the specifications given inside of the
compound specifier. The first specifier is used for formatting
the key and the second specifier is used for formatting the value.
The order can be changed with positional arguments. For example
"%(%2$s (%1$s), %)" will write the value, followed by the key in
parenthesis. |
|<td rowspan="2">Enum</td> 's' |
The name of the value. If the name is not available, the base value
is used, preceeded by a cast. |
| All, but 's' |
Enums can be formatted with all format characters that can be used
with the base value. In that case they are formatted like the base value. |
|<td rowspan="3">Input Range</td> 's' |
When the elements of the range are characters, they are written like a string.
In all other cases, the elements are enclosed by square brackets and separated
by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Struct</td> 's' |
When the struct has neither an applicable toString
nor is an input range, it is formatted as follows:
StructType(field1, field2, ...). |
|<td rowspan="1">Class</td> 's' |
When the class has neither an applicable toString
nor is an input range, it is formatted as the
fully qualified name of the class. |
|<td rowspan="1">Union</td> 's' |
When the union has neither an applicable toString
nor is an input range, it is formatted as its base name. |
|<td rowspan="2">Pointer</td> 's' |
A null pointer is formatted as 'null'. All other pointers are
formatted as hexadecimal numbers with the format character 'X'. |
| 'x', 'X' |
Formatted as a hexadecimal number. |
|<td rowspan="3">SIMD vector</td> 's' |
The array is surrounded by square brackets
and the elements are separated by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Delegate</td> 's', 'r', compound |
As the .stringof of this delegate treated as a string.
Please note: The implementation is currently buggy
and its use is discouraged. |
Source
std/format/package.d
Examples
Simple use:
// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");
// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");
Compound specifiers allow formatting arrays and other compound types:
/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
*/
assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");
/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
*/
assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");
/*
These compound format specifiers may be nested in the case of a
nested array argument:
*/
auto mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");
/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
*/
assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);
Using parameters:
// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");
// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == "> 1234.57<");
// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");
// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");
Providing parameters as arguments:
// Width as argument
assert(format(">%*s<", 10, "abc") == "> abc<");
// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");
// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");
// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");
// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == " 000/002147/483647");
format : (alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)Converts its arguments according to a format string into a string.
The second version of format takes the format string as template
argument. In this case, it is checked for consistency at
compile-time and produces slightly faster code, because the length of
the output buffer can be estimated in advance.
Params:
fmt = a $(MREF_ALTTEXT format string, std,format)
args = a variadic list of arguments to be formatted
Char = character type of fmt
Args = a variadic list of types of the arguments
Returns:
The formatted string.
Throws:
A $(LREF FormatException) if formatting did not succeed.
See_Also:
$(LREF sformat) for a variant, that tries to avoid garbage collection.
format;
(alias) object.string = stringstring (local variable) string out_out_;
foreach ((parameter) const(char) chch; (parameter) const(char)[] ss)
{
if ((local variable) const(char) chch == '\x1b') (local variable) string out_out_ ~= "ESC";
else if ((local variable) const(char) chch == '\a') (local variable) string out_out_ ~= "BEL";
else if ((local variable) const(char) chch < 0x20) (local variable) string out_out_ ~= string std.format.format!("\\x%02x", const(char))(const(char) __param_0) pure @safeExamples
The format string can be checked at compile-time:
auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");
// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format!"\\x%02x"((local variable) const(char) chch);
else (local variable) string out_out_ ~= (local variable) const(char) chch;
}
return (local variable) string out_out_;
}
/// Parse `CSI ? 997 ; Ps n`. Returns 1 (dark), 2 (light), or 0 (no answer).
int int platform_ui_color_scheme_probe.parseColorScheme(scope const(char)[] reply) @safeParse CSI ? 997 ; Ps n. Returns 1 (dark), 2 (light), or 0 (no answer).
parseColorScheme(scope const(char)[] (parameter) const(char)[] replyreply) @safe
{
import (package) stdstd.(module) std.algorithmThis package implements generic algorithms oriented towards the processing of
sequences. Sequences processed by these functions define range-based
interfaces. See also Reference on ranges and
tutorial on ranges.
Algorithms are categorized into the following submodules:
Submodule Functions
| Searching |
all
any
balancedParens
boyerMooreFinder
canFind
commonPrefix
count
countUntil
endsWith
find
findAdjacent
findAmong
findSkip
findSplit
findSplitAfter
findSplitBefore
minCount
maxCount
minElement
maxElement
minIndex
maxIndex
minPos
maxPos
skipOver
startsWith
until
|
| Comparison |
among
castSwitch
clamp
cmp
either
equal
isPermutation
isSameLength
levenshteinDistance
levenshteinDistanceAndPath
max
min
mismatch
predSwitch
|
| Iteration |
cache
cacheBidirectional
chunkBy
cumulativeFold
each
filter
filterBidirectional
fold
group
joiner
map
mean
permutations
reduce
splitWhen
splitter
substitute
sum
uniq
|
| Sorting |
completeSort
isPartitioned
isSorted
isStrictlyMonotonic
ordered
strictlyOrdered
makeIndex
merge
multiSort
nextEvenPermutation
nextPermutation
nthPermutation
partialSort
partition
partition3
schwartzSort
sort
topN
topNCopy
topNIndex
|
| Set operations (setops) |
cartesianProduct
largestPartialIntersection
largestPartialIntersectionWeighted
multiwayMerge
multiwayUnion
setDifference
setIntersection
setSymmetricDifference
|
| Mutation |
bringToFront
copy
fill
initializeAll
move
moveAll
moveSome
moveEmplace
moveEmplaceAll
moveEmplaceSome
remove
reverse
strip
stripLeft
stripRight
swap
swapRanges
uninitializedFill
|
Many functions in this package are parameterized with a predicate.
The predicate may be any suitable callable type
(a function, a delegate, a functor, or a lambda), or a
compile-time string. The string may consist of any legal D
expression that uses the symbol a (for unary functions) or the
symbols a and b (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is "a == b" for unordered operations and
"a < b" for ordered operations.
Example
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!greater(a); // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
Source
std/algorithm/package.d
algorithm : (alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see $(LREF find).
See_Also:
$(REF among, std,algorithm,comparison) for checking a value against multiple arguments.
canFind;
if ((parameter) const(char)[] replyreply.bool std.algorithm.searching.canFind!().canFind!(const(char)[], string)(const(char)[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("997;1"))
return 1;
if ((parameter) const(char)[] replyreply.bool std.algorithm.searching.canFind!().canFind!(const(char)[], string)(const(char)[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind("997;2"))
return 2;
return 0;
}
/// Parse `OSC 11 ; rgb:RRRR/GGGG/BBBB ST` into 8-bit channels. The channels are
/// 16-bit *hex of variable width* in practice — xterm emits four digits, some
/// terminals two — so each component is scaled by its own digit count rather
/// than assumed to be `/0xffff`.
bool bool platform_ui_color_scheme_probe.parseOsc11(scope const(char)[] reply, out ubyte r, out ubyte g, out ubyte b) @safeParse OSC 11 ; rgb:RRRR/GGGG/BBBB ST into 8-bit channels. The channels are
16-bit hex of variable width in practice — xterm emits four digits, some
terminals two — so each component is scaled by its own digit count rather
than assumed to be /0xffff.
parseOsc11(scope const(char)[] (parameter) const(char)[] replyreply, out ubyte (parameter) ubyte rr, out ubyte (parameter) ubyte gg, out ubyte (parameter) ubyte bb) @safe
{
import (package) stdstd.(module) std.algorithmThis package implements generic algorithms oriented towards the processing of
sequences. Sequences processed by these functions define range-based
interfaces. See also Reference on ranges and
tutorial on ranges.
Algorithms are categorized into the following submodules:
Submodule Functions
| Searching |
all
any
balancedParens
boyerMooreFinder
canFind
commonPrefix
count
countUntil
endsWith
find
findAdjacent
findAmong
findSkip
findSplit
findSplitAfter
findSplitBefore
minCount
maxCount
minElement
maxElement
minIndex
maxIndex
minPos
maxPos
skipOver
startsWith
until
|
| Comparison |
among
castSwitch
clamp
cmp
either
equal
isPermutation
isSameLength
levenshteinDistance
levenshteinDistanceAndPath
max
min
mismatch
predSwitch
|
| Iteration |
cache
cacheBidirectional
chunkBy
cumulativeFold
each
filter
filterBidirectional
fold
group
joiner
map
mean
permutations
reduce
splitWhen
splitter
substitute
sum
uniq
|
| Sorting |
completeSort
isPartitioned
isSorted
isStrictlyMonotonic
ordered
strictlyOrdered
makeIndex
merge
multiSort
nextEvenPermutation
nextPermutation
nthPermutation
partialSort
partition
partition3
schwartzSort
sort
topN
topNCopy
topNIndex
|
| Set operations (setops) |
cartesianProduct
largestPartialIntersection
largestPartialIntersectionWeighted
multiwayMerge
multiwayUnion
setDifference
setIntersection
setSymmetricDifference
|
| Mutation |
bringToFront
copy
fill
initializeAll
move
moveAll
moveSome
moveEmplace
moveEmplaceAll
moveEmplaceSome
remove
reverse
strip
stripLeft
stripRight
swap
swapRanges
uninitializedFill
|
Many functions in this package are parameterized with a predicate.
The predicate may be any suitable callable type
(a function, a delegate, a functor, or a lambda), or a
compile-time string. The string may consist of any legal D
expression that uses the symbol a (for unary functions) or the
symbols a and b (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is "a == b" for unordered operations and
"a < b" for ordered operations.
Example
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!greater(a); // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
Source
std/algorithm/package.d
algorithm : (alias template) findSplit = std.algorithm.searching.findSplit(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isForwardRange!R1 && isForwardRange!R2)These functions find the first occurrence of needle in haystack and then
split haystack as follows.
$(PANEL
`findSplit` returns a tuple `result` containing $(I three) ranges.
$(UL
$(LI result[0] is the portion of haystack before needle)
$(LI `result[1]` is the portion of
`haystack` that matches `needle`)
$(LI result[2] is the portion of haystack
after the match.)
)
If needle was not found, result[0] comprehends haystack
entirely and result[1] and result[2] are empty.
findSplitBefore returns a tuple result containing two ranges.
$(UL
$(LI result[0] is the portion of haystack before needle)
$(LI result[1] is the balance of haystack starting with the match.)
)
If needle was not found, result[0]
comprehends haystack entirely and result[1] is empty.
findSplitAfter returns a tuple result containing two ranges.
$(UL
$(LI result[0] is the portion of haystack up to and including the
match)
$(LI `result[1]` is the balance of `haystack` starting
after the match.)
)
If `needle` was not found, `result[0]` is empty
and `result[1]` is `haystack`.
)
$(P
In all cases, the concatenation of the returned ranges spans the
entire haystack.
If haystack is a random-access range, all three components of the tuple have
the same type as haystack. Otherwise, haystack must be a
$(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) and
the type of `result[0]` (and `result[1]` for `findSplit`) is the same as
the result of $(REF takeExactly, std,range).
For more information about pred see $(LREF find).
)
Params:
pred = Predicate to compare 2 elements.
haystack = The forward range to search.
needle = The forward range to look for.
Returns:
A sub-type of $(REF Tuple, std, typecons) of the split portions of haystack (see above for
details). This sub-type of Tuple defines opCast!bool, which
returns true when the separating needle was found and false otherwise.
See_Also: $(LREF find)
findSplit, (alias template) startsWith = std.algorithm.searching.startsWith(alias pred = (a, b) => a == b, Range, Needles...)(Range doesThisStart, Needles withOneOfThese) if (isInputRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles))Checks whether the given
$(REF_ALTTEXT input range, isInputRange, std,range,primitives) starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see $(LREF find).
Params:
pred = Predicate to use in comparing the elements of the haystack and the
needle(s). Mandatory if no needles are given.
doesThisStart = The input range to check.
withOneOfThese = The needles against which the range is to be checked,
which may be individual elements or input ranges of elements.
withThis = The single needle to check, which may be either a single element
or an input range of elements.
Returns:
0 if the needle(s) do not occur at the beginning of the given range;
otherwise the position of the matching needle, that is, 1 if the range starts
with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so
on.
In the case where doesThisStart starts with multiple of the ranges or
elements in withOneOfThese, then the shortest one matches (if there are
two which match which are of the same length (e.g. "a" and 'a'), then
the left-most of them in the argument
list matches).
In the case when no needle parameters are given, return true iff front of
doesThisStart fulfils predicate pred.
startsWith;
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) to = std.conv.to(T)The to template converts a value from one type _to another.
The source type is deduced and the target type must be specified, for example the
expression to!int(42.0) converts the number 42 from
double _to int. The conversion is "safe", i.e.,
it checks for overflow; to!int(4.2e10) would throw the
ConvOverflowException exception. Overflow checks are only
inserted when necessary, e.g., to!double(42) does not do
any checking because any int fits in a double.
Conversions from string _to numeric types differ from the C equivalents
atoi() and atol() by checking for overflow and not allowing whitespace.
For conversion of strings _to signed types, the grammar recognized is:
$(PRE $(I Integer):
$(I Sign UnsignedInteger)
$(I UnsignedInteger)
$(I Sign):
$(B +)
$(B -))
For conversion _to unsigned types, the grammar recognized is:
$(PRE $(I UnsignedInteger):
$(I DecimalDigit)
$(I DecimalDigit) $(I UnsignedInteger))
to;
auto (local variable) std.algorithm.searching.FindSplitResult!(cast(ubyte)1u, const(char)[], const(char)[], const(char)[]) splitsplit = (parameter) const(char)[] replyreply.std.algorithm.searching.FindSplitResult!(cast(ubyte)1u, const(char)[], const(char)[], const(char)[]) std.algorithm.searching.findSplit!("a == b", const(char)[], string)(const(char)[] haystack, string needle) pure nothrow @nogc @safeThese functions find the first occurrence of needle in haystack and then
split haystack as follows.
findSplit returns a tuple result containing three ranges.
result[0] is the portion of haystack before needle
result[1] is the portion of
haystack that matches needle
result[2] is the portion of haystack
after the match.
If needle was not found, result[0] comprehends haystack
entirely and result[1] and result[2] are empty.
findSplitBefore returns a tuple result containing two ranges.
result[0] is the portion of haystack before needle
result[1] is the balance of haystack starting with the match.
If needle was not found, result[0]
comprehends haystack entirely and result[1] is empty.
findSplitAfter returns a tuple result containing two ranges.
result[0] is the portion of haystack up to and including the
match
result[1] is the balance of haystack starting
after the match.
If needle was not found, result[0] is empty
and result[1] is haystack.
In all cases, the concatenation of the returned ranges spans the
entire haystack.
If haystack is a random-access range, all three components of the tuple have
the same type as haystack. Otherwise, haystack must be a
forward range and
the type of result[0] (and result[1] for findSplit) is the same as
the result of takeExactly.
For more information about pred see find.
findSplit("rgb:");
if (!(local variable) std.algorithm.searching.FindSplitResult!(cast(ubyte)1u, const(char)[], const(char)[], const(char)[]) splitsplit)
return false;
auto (local variable) const(char)[] restrest = (local variable) std.algorithm.searching.FindSplitResult!(cast(ubyte)1u, const(char)[], const(char)[], const(char)[]) splitsplit[2];
ubyte[3] (local variable) ubyte[3] chanschans;
(alias) object.size_t = ulongsize_t (local variable) ulong cici;
(alias) object.size_t = ulongsize_t (local variable) ulong ii;
while ((local variable) ulong cici < 3 && (local variable) ulong ii <= (local variable) const(char)[] restrest.(field) ulong const(char)[].lengthlength)
{
(alias) object.size_t = ulongsize_t (local variable) ulong startstart = (local variable) ulong ii;
while ((local variable) ulong ii < (local variable) const(char)[] restrest.(field) ulong const(char)[].lengthlength && bool platform_ui_color_scheme_probe.isHexDigit(char c) pure nothrow @nogc @safeisHexDigit((local variable) const(char)[] restrest[(local variable) ulong ii]))
(local variable) ulong ii++;
if ((local variable) ulong ii == (local variable) ulong startstart)
return false;
const (local variable) const(char[]) digitsdigits = (local variable) const(char)[] restrest[(local variable) ulong startstart .. (local variable) ulong ii];
const (local variable) const(uint) valuevalue = (local variable) const(char[]) digitsdigits.uint std.conv.to!uint.to!(const(char)[], int)(const(char)[] __param_0, int __param_1) pure @safeThe to template converts a value from one type to another.
The source type is deduced and the target type must be specified, for example the
expression to`!int(42.0)` converts the number 42 from
`double` to `int`. The conversion is "safe", i.e.,
it checks for overflow; to!int(4.2e10) would throw the
ConvOverflowException exception. Overflow checks are only
inserted when necessary, e.g., ``to!double(42) does not do
any checking because any int fits in a double.
Conversions from string to numeric types differ from the C equivalents
atoi() and atol() by checking for overflow and not allowing whitespace.
For conversion of strings to signed types, the grammar recognized is:
Integer:
Sign UnsignedInteger
UnsignedInteger
Sign:
+
-
For conversion to unsigned types, the grammar recognized is:
UnsignedInteger:
DecimalDigit
DecimalDigit UnsignedInteger
Examples
Converting a value to its own type (useful mostly for generic code)
simply returns its argument.
int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14
Converting among numeric types is a safe way to cast them around.
Conversions from floating-point types to integral types allow loss of
precision (the fractional part of a floating-point number). The
conversion is truncating towards zero, the same way a cast would
truncate. (To round a floating point value when casting to an
integral, use roundTo.)
import std.exception : assertThrown;
int a = 420;
assert(to!long(a) == a);
assertThrown!ConvOverflowException(to!byte(a));
assert(to!int(4.2e6) == 4200000);
assertThrown!ConvOverflowException(to!uint(-3.14));
assert(to!uint(3.14) == 3);
assert(to!uint(3.99) == 3);
assert(to!int(-3.99) == -3);
When converting strings to numeric types, note that D hexadecimal and binary
literals are not handled. Neither the prefixes that indicate the base, nor the
horizontal bar used to separate groups of digits are recognized. This also
applies to the suffixes that indicate the type.
To work around this, you can specify a radix for conversions involving numbers.
auto str = to!string(42, 16);
assert(str == "2A");
auto i = to!int(str, 16);
assert(i == 42);
Conversions from integral types to floating-point types always
succeed, but might lose accuracy. The largest integers with a
predecessor representable in floating-point format are 2^24-1 for
float, 2^53-1 for double, and 2^64-1 for real (when
real is 80-bit, e.g. on Intel machines).
// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);
Conversion from string types to char types enforces the input
to consist of a single code point, and said code point must
fit in the target type. Otherwise, ConvException is thrown.
import std.exception : assertThrown;
assert(to!char("a") == 'a');
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
assert(to!wchar("ñ") == 'ñ');
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
assert(to!dchar("😃") == '😃');
// Using wstring or dstring as source type does not affect the result
assert(to!char("a"w) == 'a');
assert(to!char("a"d) == 'a');
// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));
Converting an array to another array type works by converting each
element in turn. Associative arrays can be converted to associative
arrays as long as keys and values can in turn be converted.
import std.string : split;
int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);
Conversions operate transitively, meaning that they work on arrays and
associative arrays of any complexity.
This conversion works because to`!short` applies to an `int`, to!wstring
applies to a string, to`!string` applies to a `double`, and
to!(double[]) applies to an int[]. The conversion might throw an
exception because ``to!short might fail the range check.
int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);
Object-to-object conversions by dynamic casting throw exception when
the source is non-null and the target is null.
import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));
Stringize conversion from all types is supported.
String to string conversion works for any two string types having
(char, wchar, dchar) character widths and any
combination of qualifiers (mutable, const, or immutable).
Converts array (other than strings) to string.
Each element is converted by calling ``to!T.
Associative array to string conversion.
Each element is converted by calling ``to!T.
Object to string conversion calls toString against the object or
returns "null" if the object is null.
Struct to string conversion calls toString against the struct if
it is defined.
For structs that do not define toString, the conversion to string
produces the list of fields.
Enumerated types are converted to strings as their symbolic names.
Boolean values are converted to "true" or "false".
char, wchar, dchar to a string type.
Unsigned or signed integers to strings.
: Convert integral value to string in radix radix.
radix must be a value from 2 to 36.
value is treated as a signed value only if radix is 10.
The characters A through Z are used to represent values 10 through 36
and their case is determined by the letterCase parameter.
All floating point types to all string types.
Pointer to string conversions convert the pointer to a size_t value.
If pointer is char*, treat it as C-style strings.
In that case, this function is @system.
See formatValue on how toString should be defined.
// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
assert(to!string(a) == "[1, 3, 5]");
// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
to!string(associativeArray) == `["1":2, "0":1]`);
// char* to string conversion
assert(to!string(cast(char*) null) == "");
assert(to!string("foo\0".ptr) == "foo");
// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
assert(b.length == 8);
auto c = to!(wchar[])(b);
assert(c == "abcx");
Strings can be converted to enum types. The enum member with the same name as the
input string is returned. The comparison is case-sensitive.
A ConvException is thrown if the enum does not have the specified member.
import std.exception : assertThrown;
enum E { a, b, c }
assert(to!E("a") == E.a);
assert(to!E("b") == E.b);
assertThrown!ConvException(to!E("A"));
to!uint(16);
// Scale from `digits.length` nibbles down to 8 bits.
const (local variable) const(uint) maxmax = (1u << (4 * (local variable) const(char[]) digitsdigits.(field) ulong const(char[]).lengthlength)) - 1;
(local variable) ubyte[3] chanschans[(local variable) ulong cici++] = cast(ubyte) (((local variable) const(uint) valuevalue * 255 + (local variable) const(uint) maxmax / 2) / (local variable) const(uint) maxmax);
if ((local variable) ulong cici < 3)
{
if ((local variable) ulong ii >= (local variable) const(char)[] restrest.(field) ulong const(char)[].lengthlength || (local variable) const(char)[] restrest[(local variable) ulong ii] != '/')
return false;
(local variable) ulong ii++;
}
}
if ((local variable) ulong cici != 3)
return false;
(parameter) ubyte rr = (local variable) ubyte[3] chanschans[0]; (parameter) ubyte gg = (local variable) ubyte[3] chanschans[1]; (parameter) ubyte bb = (local variable) ubyte[3] chanschans[2];
return true;
}
bool bool platform_ui_color_scheme_probe.isHexDigit(char c) pure nothrow @nogc @safeisHexDigit(char (parameter) char cc) @safe pure nothrow @nogc
=> ((parameter) char cc >= '0' && (parameter) char cc <= '9') || ((parameter) char cc >= 'a' && (parameter) char cc <= 'f') || ((parameter) char cc >= 'A' && (parameter) char cc <= 'F');
void void D main() @safemain() @safe
{
// Both directions must be a terminal: the query goes out on stdout and the
// reply comes back on stdin. Under CI either one is a pipe.
if (!bool sparkles.base.term_caps.isTerminal(sparkles.base.term_caps.StdStream stream = StdStream.stdout) nothrow @nogc @trustedIs stream attached to a terminal? POSIX: isatty; Windows: GetConsoleMode
succeeds (it fails when the handle is redirected — the non-tty check).
Examples
The query never throws and is @nogc; the value is environment-dependent.
cast(void) isTerminal();
cast(void) isTerminal(StdStream.stderr);
isTerminal((enum) sparkles.base.term_caps.StdStreamA standard stream, for tty queries.
StdStream.(enum value) sparkles.base.term_caps.StdStream.stdout = 1stdout) || !bool sparkles.base.term_caps.isTerminal(sparkles.base.term_caps.StdStream stream = StdStream.stdout) nothrow @nogc @trustedIs stream attached to a terminal? POSIX: isatty; Windows: GetConsoleMode
succeeds (it fails when the handle is redirected — the non-tty check).
Examples
The query never throws and is @nogc; the value is environment-dependent.
cast(void) isTerminal();
cast(void) isTerminal(StdStream.stderr);
isTerminal((enum) sparkles.base.term_caps.StdStreamA standard stream, for tty queries.
StdStream.(enum value) sparkles.base.term_caps.StdStream.stdin = 0stdin))
{
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("SKIP: stdin/stdout is not a terminal — nothing to query.");
return;
}
void std.stdio.writefln!("TERM=%s TERM_PROGRAM=%s TMUX=%s", string, string, string)(string __param_0, string __param_1, string __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln!"TERM=%s TERM_PROGRAM=%s TMUX=%s"(
(class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("TERM", "(unset)"),
(class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("TERM_PROGRAM", "(unset)"),
(class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("TMUX") is null ? "no" : "yes (using DCS passthrough)");
void std.stdio.writefln!("COLORFGBG=%s", string)(string __param_0) @safeEquivalent to writef(fmt, args, '\n').
writefln!"COLORFGBG=%s"((class) std.process.environmentManipulates environment variables using an associative-array-like
interface.
This class contains only static methods, and cannot be instantiated.
See below for examples of use.
environment.string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safeRetrieves the value of the environment variable with the given name,
or a default value if the variable doesn't exist.
Unlike environment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL", "/bin/sh");
This function is also useful in checking for the existence of an
environment variable.
auto myVar = environment.get("MYVAR");
if (myVar is null)
{
// Environment variable doesn't exist.
// Note that we have to use 'is' for the comparison, since
// myVar == null is also true if the variable exists but is
// empty.
}
get("COLORFGBG", "(unset)"));
void std.stdio.writeln!()() @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln();
char[256] (local variable) char[256] bufbuf;
{
auto (local variable) platform_ui_color_scheme_probe.RawMode rawraw = (struct) platform_ui_color_scheme_probe.RawModeRaw-mode guard: a terminal reply arrives on stdin as ordinary input, so
canonical mode (which waits for a newline) and echo (which would paint the
reply into the user's scrollback) both have to go.
RawMode.platform_ui_color_scheme_probe.RawMode platform_ui_color_scheme_probe.RawMode.enter() nothrow @nogc @trustedenter();
// --- 1. DEC mode 2031 status query -------------------------------
const (local variable) const(string) dsrdsr = string platform_ui_color_scheme_probe.wrapForMultiplexer(string seq) @safetmux does not forward an unknown query to the outer terminal and does not
answer it either, so a bare probe times out. Wrapping it in DCS passthrough
(ESC P tmux; <escaped> ESC \, with every ESC doubled) hands it through.
See the deep-dive § "Hazards — multiplexers".
wrapForMultiplexer("\x1b[?996n");
void platform_ui_color_scheme_probe.emit(scope const(char)[] bytes) nothrow @nogc @trustedemit((local variable) const(string) dsrdsr);
auto (local variable) char[] replyreply = char[] platform_ui_color_scheme_probe.drain(return scope char[] buf) nothrow @nogc @trustedRead whatever arrives within replyTimeoutMs of the last byte seen, so a
reply split across packets is still collected whole. Returns the bytes read.
drain((local variable) char[256] bufbuf[]);
void std.stdio.writefln!("query CSI ? 996 n -> %s", string)(string __param_0) @safeEquivalent to writef(fmt, args, '\n').
writefln!"query CSI ? 996 n -> %s"(
(local variable) char[] replyreply.(field) ulong char[].lengthlength ? string platform_ui_color_scheme_probe.visible(scope const(char)[] s) @safeRender a byte string with escapes visible, so the report is copy-pasteable.
visible((local variable) char[] replyreply) : "(no reply within " ~ "200ms)");
const (local variable) const(int) schemescheme = int platform_ui_color_scheme_probe.parseColorScheme(scope const(char)[] reply) @safeParse CSI ? 997 ; Ps n. Returns 1 (dark), 2 (light), or 0 (no answer).
parseColorScheme((local variable) char[] replyreply);
void std.stdio.writefln!(" color scheme -> %s", string)(string __param_0) @safeEquivalent to writef(fmt, args, '\n').
writefln!" color scheme -> %s"(
(local variable) const(int) schemescheme == 1 ? "dark" : (local variable) const(int) schemescheme == 2 ? "light" : "unknown (mode 2031 unsupported)");
void std.stdio.writeln!()() @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln();
// --- 2. OSC 11 background color ----------------------------------
const (local variable) const(string) oscosc = string platform_ui_color_scheme_probe.wrapForMultiplexer(string seq) @safetmux does not forward an unknown query to the outer terminal and does not
answer it either, so a bare probe times out. Wrapping it in DCS passthrough
(ESC P tmux; <escaped> ESC \, with every ESC doubled) hands it through.
See the deep-dive § "Hazards — multiplexers".
wrapForMultiplexer("\x1b]11;?\x1b\\");
void platform_ui_color_scheme_probe.emit(scope const(char)[] bytes) nothrow @nogc @trustedemit((local variable) const(string) oscosc);
(local variable) char[] replyreply = char[] platform_ui_color_scheme_probe.drain(return scope char[] buf) nothrow @nogc @trustedRead whatever arrives within replyTimeoutMs of the last byte seen, so a
reply split across packets is still collected whole. Returns the bytes read.
drain((local variable) char[256] bufbuf[]);
void std.stdio.writefln!("query OSC 11 ; ? ST -> %s", string)(string __param_0) @safeEquivalent to writef(fmt, args, '\n').
writefln!"query OSC 11 ; ? ST -> %s"(
(local variable) char[] replyreply.(field) ulong char[].lengthlength ? string platform_ui_color_scheme_probe.visible(scope const(char)[] s) @safeRender a byte string with escapes visible, so the report is copy-pasteable.
visible((local variable) char[] replyreply) : "(no reply within 200ms)");
ubyte (local variable) ubyte rr, (local variable) ubyte gg, (local variable) ubyte bb;
if (bool platform_ui_color_scheme_probe.parseOsc11(scope const(char)[] reply, out ubyte r, out ubyte g, out ubyte b) @safeParse OSC 11 ; rgb:RRRR/GGGG/BBBB ST into 8-bit channels. The channels are
16-bit hex of variable width in practice — xterm emits four digits, some
terminals two — so each component is scaled by its own digit count rather
than assumed to be /0xffff.
parseOsc11((local variable) char[] replyreply, (local variable) ubyte rr, (local variable) ubyte gg, (local variable) ubyte bb))
{
import (package) stdstd.(module) std.formatThis package provides string formatting functionality using
printf style format strings.
Submodule Function Name Description package format Converts its arguments according to a format string into a string.
| package |
sformat |
Converts its arguments according to a format string into a buffer. |
| package |
FormatException |
Signals a problem while formatting. |
| write |
formattedWrite |
Converts its arguments according to a format string and writes
the result to an output range. |
| write |
formatValue |
Formats a value of any type according to a format specifier and
writes the result to an output range. |
| read |
formattedRead |
Reads an input range according to a format string and stores the read
values into its arguments. |
| read |
unformatValue |
Reads a value from the given input range and converts it according to
a format specifier. |
| spec |
FormatSpec |
A general handler for format strings. |
| spec |
singleSpec |
Helper function that returns a FormatSpec for a single format specifier. |
Limitation
This package does not support localization, but
adheres to the rounding mode of the floating point unit, if
available.
Format Strings
The functions contained in this package use format strings. A
format string describes the layout of another string for reading or
writing purposes. A format string is composed of normal text
interspersed with format specifiers. A format specifier starts
with a percentage sign '%', optionally followed by one or more
parameters and ends with a format indicator. A format
indicator may be a simple format character or a compound
indicator.
Format strings are composed according to the following grammar:
FormatString:
FormatStringItem FormatString
FormatStringItem:
Character
FormatSpecifier
FormatSpecifier:
'%' Parameters FormatIndicator
FormatIndicator:
FormatCharacter
CompoundIndicator
FormatCharacter:
see remark below
CompoundIndicator:
'(' FormatString '%)'
'(' FormatString '%|' Delimiter '%)'
Delimiter
empty
Character Delimiter
Parameters:
Position Flags Width Precision Separator
Position:
empty
Integer '$'**
*Integer* **':'** *Integer* **'$'
Integer ':' '$'**
*Flags*:
*empty*
*Flag* *Flags*
*Flag*:
**'-'**|**'+'**|**' '**|**'0'**|**'#'**|**'='**
*Width*:
*OptionalPositionalInteger*
*Precision*:
*empty*
**'.'** *OptionalPositionalInteger*
*Separator*:
*empty*
**','** *OptionalInteger*
**','** *OptionalInteger* **'?'**
*OptionalInteger*:
*empty*
*Integer*
**'*'**
*OptionalPositionalInteger*:
*OptionalInteger*
**'*'** *Integer* **'$'
Character
'%%'
AnyCharacterExceptPercent
Integer:
NonZeroDigit Digits
Digits:
empty
Digit Digits
NonZeroDigit:
'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Digit:
'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
Note
FormatCharacter is unspecified. It can be any character
that has no other purpose in this grammar, but it is
recommended to assign (lower- and uppercase) letters.
Note
The Parameters of a CompoundIndicator are currently
limited to a '-' flag.
Format Indicator
The format indicator can either be a single character or an
expression surrounded by '%(' and '%)'. It specifies the
basic manner in which a value will be formatted and is the minimum
requirement to format a value.
The following characters can be used as format characters:
FormatCharacter Semantics 's' To be formatted in a human readable format. Can be used with all types. 'c' To be formatted as a character. 'd' To be formatted as a signed decimal integer. 'u' To be formatted as a decimal image of the underlying bit representation. 'b' To be formatted as a binary image of the underlying bit representation. 'o' To be formatted as an octal image of the underlying bit representation. 'x' / 'X' To be formatted as a hexadecimal image of the underlying bit representation. 'e' / 'E' To be formatted as a real number in decimal scientific notation. 'f' / 'F' To be formatted as a real number in decimal natural notation. 'g' / 'G' To be formatted as a real number in decimal short notation. Depending on the number, a scientific notation or a natural notation is used. 'a' / 'A' To be formatted as a real number in hexadecimal scientific notation. 'r' To be formatted as raw bytes. The output may not be printable and depends on endianness.
The compound indicator can be used to describe compound types
like arrays or structs in more detail. A compound type is enclosed
within '%(' and '%)'. The enclosed sub-format string is
applied to individual elements. The trailing portion of the
sub-format string following the specifier for the element is
interpreted as the delimiter, and is therefore omitted following the
last element. The '%|' specifier may be used to explicitly
indicate the start of the delimiter, so that the preceding portion of
the string will be included following the last element.
The format string inside of the compound indicator should
contain exactly one format specifier (two in case of associative
arrays), which specifies the formatting mode of the elements of the
compound type. This format specifier can be a compound
indicator itself.
Note
Inside a compound indicator, strings and characters are
escaped automatically. To avoid this behavior, use "%-("
instead of "%(".
Flags
There are several flags that affect the outcome of the formatting.
Flag Semantics '-' When the formatted result is shorter than the value given by the width parameter, the output is left justified. Without the '-' flag, the output remains right justified.
There are two exceptions where the '-' flag has a
different meaning: (1) with 'r' it denotes to use little
endian and (2) in case of a compound indicator it means that
no special handling of the members is applied. |
| '=' |
When the formatted result is shorter than the value
given by the width parameter, the output is centered.
If the central position is not possible it is moved slightly
to the right. In this case, if '-' flag is present in
addition to the '=' flag, it is moved slightly to the left. |
| '+' / *' '* |
Applies to numerical values. By default, positive numbers are not
formatted to include the + sign. With one of these two flags present,
positive numbers are preceded by a plus sign or a space.
When both flags are present, a plus sign is used.
In case of 'r', a big endian format is used. |
| '0' |
Is applied to numerical values that are printed right justified.
If the zero flag is present, the space left to the number is
filled with zeros instead of spaces. |
| '#' |
Denotes that an alternative output must be used. This depends on the type
to be formatted and the format character used. See the
sections below for more information. |
Width, Precision and Separator
The width parameter specifies the minimum width of the result.
The meaning of precision depends on the format indicator. For
integers it denotes the minimum number of digits printed, for
real numbers it denotes the number of fractional digits and for
strings and compound types it denotes the maximum number of elements
that are included in the output.
A separator is used for formatting numbers. If it is specified,
the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by
providing a number or a ''* after the ','.
In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of
digits. If the argument is a negative number, the precision and
separator parameters are considered unspecified. For width,
the absolute value is used and the '-' flag is set.
The separator can also be followed by a '?'. In that case,
an additional argument is used to specify the symbol that should be
used to separate the chunks.
Position
By default, the arguments are processed in the provided order. With
the position parameter it is possible to address arguments
directly. It is also possible to denote a series of arguments with
two numbers separated by ':', that are all processed in the same
way. The second number can be omitted. In that case the series ends
with the last argument.
It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.
Types
This section describes the result of combining types with format
characters. It is organized in 2 subsections: a list of general
information regarding the formatting of types in the presence of
format characters and a table that contains details for every
available combination of type and format character.
When formatting types, the following rules apply:
If the format character is upper case, the resulting string will
be formatted using upper case letters.
The default precision for floating point numbers is 6 digits.
Rounding of floating point numbers adheres to the rounding mode
of the floating point unit, if available.
The floating point values NaN and Infinity are formatted as
nan and inf, possibly preceded by '+' or '-' sign.
Formatting reals is only supported for 64 bit reals and 80 bit reals.
All other reals are cast to double before they are formatted. This will
cause the result to be inf for very large numbers.
Characters and strings formatted with the 's' format character
inside of compound types are surrounded by single and double quotes
and unprintable characters are escaped. To avoid this, a '-'
flag can be specified for the compound specifier
(e.g. "%-(%s%)" instead of "%(%s%)" ).
Structs, unions, classes and interfaces are formatted by calling a
toString method if available.
See module std.format.write for more
details.
Only part of these combinations can be used for reading. See
module std.format.read for more
detailed information.
This table contains descriptions for every possible combination of
type and format character:
<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as... <td rowspan="1">null</td> 's' null
|<td rowspan="3">bool</td> 's' |
false or true |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integrals 0 or 1 with the same format character.
Please note, that 'o' and 'x' with '#' flag
might produce unexpected results due to special handling of
the value 0. |
| 'r' |
\0 or \1 |
|<td rowspan="4">Integral</td> 's', 'd' |
A signed decimal number. The '#' flag is ignored. |
| 'b', 'o', 'u', 'x', 'X' |
An unsigned binary, decimal, octal or hexadecimal number.
In case of 'o' and 'x', the '#' flag
denotes that the number must be preceded by 0 and 0x, with
the exception of the value 0, where this does not apply. For
'b' and 'u' the '#' flag has no effect. |
| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' |
As a floating point value with the same specifier.
Default precision is large enough to add all digits
of the integral value.
In case of 'a' and 'A', the integral digit can be
any hexadecimal digit.
|
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="5">Floating Point</td> 'e', 'E' |
Scientific notation: Exactly one integral digit followed by a dot
and fractional digits, followed by the exponent.
The exponent is formatted as 'e' followed by
a '+' or '-' sign, followed by at least
two digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'f', 'F' |
Natural notation: Integral digits followed by a dot and
fractional digits.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted.
Please note: the difference between 'f' and 'F'
is only visible for NaN and Infinity. |
| 's', 'g', 'G' |
Short notation: If the absolute value is larger than 10 ^^ precision
or smaller than 0.0001, the scientific notation is used.
If not, the natural notation is applied.
In both cases precision denotes the count of all digits, including
the integral digits. Trailing zeros (including a trailing dot) are removed.
If '#' flag is present, trailing zeros are not removed. |
| 'a', 'A' |
Hexadecimal scientific notation: 0x followed by 1
(or 0 in case of value zero or denormalized number)
followed by a dot, fractional digits in hexadecimal
notation and an exponent. The exponent is build by p,
followed by a sign and the exponent in decimal notation.
When there are no fractional digits and the '#' flag
is not present, the dot is omitted. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">Character</td> 's', 'c' |
As the character.
Inside of a compound indicator 's' is treated differently: The
character is surrounded by single quotes and non printable
characters are escaped. This can be avoided by preceding
the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'b', 'd', 'o', 'u', 'x', 'X' |
As the integral that represents the character. |
| 'r' |
Characters taken directly from the binary representation. |
|<td rowspan="3">String</td> 's' |
The sequence of characters that form the string.
Inside of a compound indicator the string is surrounded by double quotes
and non printable characters are escaped. This can be avoided
by preceding the compound indicator with a '-' flag
(e.g. "%-(%s%)"). |
| 'r' |
The sequence of characters, each formatted with 'r'. |
| compound |
As an array of characters. |
|<td rowspan="3">Array</td> 's' |
When the elements are characters, the array is formatted as
a string. In all other cases the array is surrounded by square brackets
and the elements are separated by a comma and a space. If the elements
are strings, they are surrounded by double quotes and non
printable characters are escaped. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="2">Associative Array</td> 's' |
As a sequence of the elements in unpredictable order. The output is
surrounded by square brackets. The elements are separated by a
comma and a space. The elements are formatted as key:value. |
| compound |
As a sequence of the elements in unpredictable order. Each element
is formatted according to the specifications given inside of the
compound specifier. The first specifier is used for formatting
the key and the second specifier is used for formatting the value.
The order can be changed with positional arguments. For example
"%(%2$s (%1$s), %)" will write the value, followed by the key in
parenthesis. |
|<td rowspan="2">Enum</td> 's' |
The name of the value. If the name is not available, the base value
is used, preceeded by a cast. |
| All, but 's' |
Enums can be formatted with all format characters that can be used
with the base value. In that case they are formatted like the base value. |
|<td rowspan="3">Input Range</td> 's' |
When the elements of the range are characters, they are written like a string.
In all other cases, the elements are enclosed by square brackets and separated
by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Struct</td> 's' |
When the struct has neither an applicable toString
nor is an input range, it is formatted as follows:
StructType(field1, field2, ...). |
|<td rowspan="1">Class</td> 's' |
When the class has neither an applicable toString
nor is an input range, it is formatted as the
fully qualified name of the class. |
|<td rowspan="1">Union</td> 's' |
When the union has neither an applicable toString
nor is an input range, it is formatted as its base name. |
|<td rowspan="2">Pointer</td> 's' |
A null pointer is formatted as 'null'. All other pointers are
formatted as hexadecimal numbers with the format character 'X'. |
| 'x', 'X' |
Formatted as a hexadecimal number. |
|<td rowspan="3">SIMD vector</td> 's' |
The array is surrounded by square brackets
and the elements are separated by a comma and a space. |
| 'r' |
The sequence of the elements, each formatted with 'r'. |
| compound |
The sequence of the elements, each formatted according to the specifications
given inside of the compound specifier. |
|<td rowspan="1">Delegate</td> 's', 'r', compound |
As the .stringof of this delegate treated as a string.
Please note: The implementation is currently buggy
and its use is discouraged. |
Source
std/format/package.d
Examples
Simple use:
// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");
// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");
Compound specifiers allow formatting arrays and other compound types:
/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
*/
assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");
/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
*/
assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");
/*
These compound format specifiers may be nested in the case of a
nested array argument:
*/
auto mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");
/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
*/
assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);
Using parameters:
// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");
// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == "> 1234.57<");
// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");
// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");
Providing parameters as arguments:
// Width as argument
assert(format(">%*s<", 10, "abc") == "> abc<");
// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");
// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");
// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");
// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == " 000/002147/483647");
format : (alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)Converts its arguments according to a format string into a string.
The second version of format takes the format string as template
argument. In this case, it is checked for consistency at
compile-time and produces slightly faster code, because the length of
the output buffer can be estimated in advance.
Params:
fmt = a $(MREF_ALTTEXT format string, std,format)
args = a variadic list of arguments to be formatted
Char = character type of fmt
Args = a variadic list of types of the arguments
Returns:
The formatted string.
Throws:
A $(LREF FormatException) if formatting did not succeed.
See_Also:
$(LREF sformat) for a variant, that tries to avoid garbage collection.
format;
const (local variable) const(string) hexhex = string std.format.format!("#%02X%02X%02X", ubyte, ubyte, ubyte)(ubyte __param_0, ubyte __param_1, ubyte __param_2) pure @safeExamples
The format string can be checked at compile-time:
auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");
// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format!"#%02X%02X%02X"((local variable) ubyte rr, (local variable) ubyte gg, (local variable) ubyte bb);
// The same Rec. 601 threshold `sparkles.ui.style.schemeForBackground`
// uses today, reproduced here so the two answers can be compared.
const (local variable) const(int) lumaluma = ((local variable) ubyte rr * 299 + (local variable) ubyte gg * 587 + (local variable) ubyte bb * 114) / 1000;
void std.stdio.writefln!(" background -> %s (Rec.601 luma %d \xe2\x87\x92 %s)", string, const(int), string)(string __param_0, const(int) __param_1, string __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln!" background -> %s (Rec.601 luma %d ⇒ %s)"(
(local variable) const(string) hexhex, (local variable) const(int) lumaluma, (local variable) const(int) lumaluma < 110 ? "dark" : "light");
if ((local variable) const(int) schemescheme != 0)
{
const (local variable) const(int) inferredinferred = (local variable) const(int) lumaluma < 110 ? 1 : 2;
void std.stdio.writefln!(" agreement -> %s", string)(string __param_0) @safeEquivalent to writef(fmt, args, '\n').
writefln!" agreement -> %s"(
(local variable) const(int) inferredinferred == (local variable) const(int) schemescheme
? "mode 2031 and the luminance guess agree"
: "DISAGREE — trust mode 2031, it is the terminal's own answer");
}
}
else
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln(" background -> unavailable (OSC 11 unsupported or blocked)");
}
void std.stdio.writeln!()() @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln();
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("Enabling unsolicited notifications (CSI ? 2031 h) makes the terminal");
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("send CSI ? 997 n whenever the scheme changes, so a long-running TUI");
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("never has to poll. Remember CSI ? 2031 l on exit.");
}