#!/usr/bin/env dub
/+ dub.sdl:
name "editor-tui-close-probe"
targetPath "../build"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/// Exercise the real terminal interrupt/dirty-close policy on a private PTY.
module (module) editor_tui_close_probeExercise the real terminal interrupt/dirty-close policy on a private PTY.
editor_tui_close_probe;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.fcntlD header file for POSIX.
fcntl : (alias) editor_tui_close_probe.fcntl = int core.sys.posix.fcntl.fcntl(int, int, ...) nothrow @nogcfcntl, (alias constant) editor_tui_close_probe.F_GETFL = int core.sys.posix.fcntl.F_GETFL = 3F_GETFL, (alias constant) editor_tui_close_probe.F_SETFL = int core.sys.posix.fcntl.F_SETFL = 4F_SETFL, (alias constant) editor_tui_close_probe.O_NONBLOCK = int core.sys.posix.fcntl.O_NONBLOCK = 2048O_NONBLOCK;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.pollD header file for POSIX.
poll : (alias) editor_tui_close_probe.poll = int core.sys.posix.poll.poll(core.sys.posix.poll.pollfd*, ulong, int) nothrow @nogcpoll, (alias enum value) editor_tui_close_probe.POLLIN = core.sys.posix.poll.POLLIN = 1POLLIN, (struct) core.sys.posix.poll.pollfdpollfd;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.signalD header file for POSIX.
Source
core/sys/posix/signal.d
signal : (alias) editor_tui_close_probe.kill = int core.sys.posix.signal.kill(int, int) nothrow @nogckill, (alias constant) editor_tui_close_probe.SIGKILL = int core.sys.posix.signal.SIGKILL = 9SIGKILL;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(package) core.sys.posix.syssys.(module) core.sys.posix.sys.ioctlD header file for POSIX.
ioctl : (struct) core.sys.posix.sys.ioctl.winsizewinsize;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(package) core.sys.posix.syssys.(module) core.sys.posix.sys.waitD header file for POSIX.
wait : (alias) editor_tui_close_probe.waitpid = int core.sys.posix.sys.wait.waitpid(int, int*, int) nothrow @nogcwaitpid, (alias constant) editor_tui_close_probe.WNOHANG = int core.sys.posix.sys.wait.WNOHANG = 1WNOHANG;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.unistdD header file for POSIX.
unistd : (alias) editor_tui_close_probe.close = int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose, (alias) editor_tui_close_probe.execvp = int core.sys.posix.unistd.execvp(scope const(char*), scope const(char**)) nothrow @nogcexecvp, (alias) editor_tui_close_probe.read = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread, (alias) editor_tui_close_probe.write = long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite, (alias) editor_tui_close_probe._exit = noreturn core.sys.posix.unistd._exit(int) nothrow @nogc @trusted_exit;
import (package) corecore.(module) core.timeModule containing core time functionality, such as Duration (which
represents a duration of time) or MonoTime (which represents a
timestamp of the system's monotonic clock).
Various functions take a string (or strings) to represent a unit of time
(e.g. convert!("days", "hours")(numDays)). The valid strings to use
with such functions are "years", "months", "weeks", "days", "hours",
"minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds),
"hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There
are a few functions that also allow "nsecs", but very little actually
has precision greater than hnsecs.
Symbol Description Types Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). TickDuration DEPRECATED Represents a duration of time in system clock ticks, using the highest precision that the system provides. MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides. Functions convert Generic way of converting between two time units. dur Allows constructing a Duration from the given time units with the given length. weeks days hours
minutes seconds msecs
usecs hnsecs nsecs |
Convenience aliases for dur. |
| abs | Returns the absolute value of a duration. |
From Duration
From TickDuration
From units
To Duration tickDuration.to, std,conv!Duration() dur!"msecs"(5) or 5.msecs()
| To TickDuration |
duration.to, std,conv!TickDuration() |
|
TickDuration.from!"msecs"(msecs) |
| To units |
duration.total!"days" |
tickDuration.msecs |
convert!("days", "msecs")(msecs) |
Source
core/time.d
time : (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime, msecs, seconds;
import (package) corecore.(module) core.threadThe thread module provides support for thread creation and management.
Source
core/thread/package.d
thread : (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread;
import (package) stdstd.(package) std.algorithmalgorithm.(module) std.algorithm.searchingThis is a submodule of std.algorithm.
It contains generic searching algorithms.
Function Name Description all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses. boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm. canFind canFind("hello world", "or") returns true. count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns 3,
count([1, 2, 1], 1) returns 2 and
count!"a < 0"([1, -3, 0]) returns 1. |
| countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. |
| commonPrefix | commonPrefix("parakeet", "parachute") returns "para". |
| endsWith | endsWith("rocks", "ks") returns true. |
| extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. |
| find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) |
| findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. |
| findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". |
| findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. |
| findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". |
| findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". |
| findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". |
| minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). |
| maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). |
| minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. |
| maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. |
| minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. |
| maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. |
| minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. |
| maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. |
| skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. |
| startsWith | startsWith("hello, world", "hello") returns true. |
| until | Lazily iterates a range until a specific value is found. |
Source
std/algorithm/searching.d
searching : (alias template) editor_tui_close_probe.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 find.
canFind;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) editor_tui_close_probe.mkdir = std.file.mkdir(R)(R pathname) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Make a new directory pathname.
mkdir, (alias) editor_tui_close_probe.rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse, (alias) editor_tui_close_probe.tempDir = string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
tempDir;
import (package) stdstd.(module) std.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) editor_tui_close_probe.buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
buildPath, (alias template) editor_tui_close_probe.dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)Returns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
dirName;
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) editor_tui_close_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) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias) editor_tui_close_probe.toStringz = immutable(char)* std.string.toStringz(scope const(char)[] s) pure nothrow @trustedtoStringz;
import (package) stdstd.(module) std.uuidA UUID, or
Universally unique identifier,
is intended to uniquely identify information in a distributed environment
without significant central coordination. It can be
used to tag objects with very short lifetimes, or to reliably identify very
persistent objects across a network.
Category Functions
| Parsing UUIDs |
parseUUID
UUID
UUIDParsingException
uuidRegex
|
| Generating UUIDs |
sha1UUID
randomUUID
md5UUID
timestampRandomUUID
|
| Using UUIDs |
<a href="#uuidVersion">UUID.uuidVersion</a>
<a href="#variant">UUID.variant</a>
<a href="#toString">UUID.toString</a>
<a href="#data">UUID.data</a>
<a href="#swap">UUID.swap</a>
<a href="#opEquals">UUID.opEquals</a>
<a href="#opCmp">UUID.opCmp</a>
<a href="#toHash">UUID.toHash</a>
|
| UUID namespaces |
dnsNamespace
urlNamespace
oidNamespace
x500Namespace
|
UUIDs have many applications. Some examples follow: Databases may use UUIDs to identify
rows or records in order to ensure that they are unique across different
databases, or for publication/subscription services. Network messages may be
identified with a UUID to ensure that different parts of a message are put back together
again. Distributed computing may use UUIDs to identify a remote procedure call.
Transactions and classes involved in serialization may be identified by UUIDs.
Microsoft's component object model (COM) uses UUIDs to distinguish different software
component interfaces. UUIDs are inserted into documents from Microsoft Office programs.
UUIDs identify audio or video streams in the Advanced Systems Format (ASF). UUIDs are
also a basis for OIDs (object identifiers), and URNs (uniform resource name).
An attractive feature of UUIDs when compared to alternatives is their relative small size,
of 128 bits, or 16 bytes. Another is that the creation of UUIDs does not require
a centralized authority.
When UUIDs are generated by one of the defined mechanisms, they are either guaranteed
to be unique, different from all other generated UUIDs (that is, it has never been
generated before and it will never be generated again), or it is extremely likely
to be unique (depending on the mechanism).
For efficiency, UUID is implemented as a struct. UUIDs are therefore empty if not explicitly
initialized. An UUID is empty if <a href="#empty">UUID.empty</a> is true. Empty UUIDs are equal to
UUID.init, which is a UUID with all 16 bytes set to 0.
Use UUID's constructors or the UUID generator functions to get an initialized UUID.
This is a port of boost.uuid from the Boost project with some minor additions and API
changes for a more D-like API.
Source
std/uuid.d
Examples
import std.uuid;
UUID[] ids;
ids ~= randomUUID();
ids ~= md5UUID("test.name.123");
ids ~= sha1UUID("test.name.123");
foreach (entry; ids)
{
assert(entry.variant == UUID.Variant.rfc4122);
}
assert(ids[0].uuidVersion == UUID.Version.randomNumberBased);
assert(ids[1].toString() == "22390768-cced-325f-8f0f-cfeaa19d0ccd");
assert(ids[1].data == [34, 57, 7, 104, 204, 237, 50, 95, 143, 15, 207,
234, 161, 157, 12, 205]);
UUID id;
assert(id.empty);
uuid : (alias) editor_tui_close_probe.randomUUID = std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safeThis function generates a random number based UUID from a random
number generator.
This function is not supported at compile time.
Warning
This function must not be used for cryptographic purposes.
UUIDs generated by this function do not have sufficient randomness
for all use cases.
This especially applies to the overload that accepts a caller-provided RNG.
At the moment, Phobos does not provide a cryptographically-secure
pseudo-random number generator (CSPRNG) that could be supplied to this
function.
While the function overload with no parameters will attempt to use the
system CSPRNG where available and implemented, there are no guarantees.
See unpredictableSeed for details.
randomUUID;
extern (C) int int editor_tui_close_probe.forkpty(int* master, char* name, const(void*) termp, const(core.sys.posix.sys.ioctl.winsize*) winp)forkpty(int* (parameter) int* mastermaster, char* (parameter) char* namename, const void* (parameter) const(void*) termptermp, const (struct) core.sys.posix.sys.ioctl.winsizewinsize* (parameter) const(core.sys.posix.sys.ioctl.winsize*) winpwinp);
int int D main() @systemmain() @system
{
const (local variable) const(string) statestate = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath(string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
Examples
import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;
// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;
myFile.write("hello");
assert(myFile.readText == "hello");
tempDir, "editor-tui-state-" ~ std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safeThis function generates a random number based UUID from a random
number generator.
This function is not supported at compile time.
Warning
This function must not be used for cryptographic purposes.
UUIDs generated by this function do not have sufficient randomness
for all use cases.
This especially applies to the overload that accepts a caller-provided RNG.
At the moment, Phobos does not provide a cryptographically-secure
pseudo-random number generator (CSPRNG) that could be supplied to this
function.
While the function overload with no parameters will attempt to use the
system CSPRNG where available and implemented, there are no guarantees.
See unpredictableSeed for details.
randomUUID().string std.uuid.UUID.toString() const pure nothrow @trustedReturn the UUID as a string in the canonical form.
Examples
immutable str = "8ab3060e-2cba-4f23-b74c-b52db3bdfb46";
auto id = UUID(str);
assert(id.toString() == str);
toString());
void std.file.mkdir!string(string pathname) @safeMake a new directory pathname.
mkdir((local variable) const(string) statestate);
scope (exit) void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse((local variable) const(string) statestate);
const (local variable) const(string) editoreditor = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath(__FILE_FULL_PATH__.string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safeReturns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Examples
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
dirName.string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safeReturns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Examples
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
dirName, "build", "editor");
auto (local variable) const(string)[] argsargs = [(local variable) const(string) editoreditor, "--tui", "--state-dir", (local variable) const(string) statestate];
(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["TERM"] = "xterm-256color";
(struct) core.sys.posix.sys.ioctl.winsizewinsize (local variable) core.sys.posix.sys.ioctl.winsize sizesize = {ws_row: 30, ws_col: 90};
int (local variable) int mastermaster;
const (local variable) const(int) childchild = int editor_tui_close_probe.forkpty(int* master, char* name, const(void*) termp, const(core.sys.posix.sys.ioctl.winsize*) winp)forkpty(&(local variable) int mastermaster, null, null, &(local variable) core.sys.posix.sys.ioctl.winsize sizesize);
assert((local variable) const(int) childchild >= 0);
if ((local variable) const(int) childchild == 0)
{
auto (local variable) const(char)*[] argvargv = new const(char)*[(local variable) const(string)[] argsargs.(field) ulong const(string)[].lengthlength + 1];
foreach ((parameter) ulong ii, (parameter) const(string) argarg; (local variable) const(string)[] argsargs) (local variable) const(char)*[] argvargv[(local variable) ulong ii] = (local variable) const(string) argarg.immutable(char)* std.string.toStringz(scope const(char)[] s) pure nothrow @trustedExamples
import core.stdc.string : strlen;
import std.conv : to;
auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
assert(strlen(p) == 2);
string test = "";
p = toStringz(test);
assert(*p == 0);
test = "\0";
p = toStringz(test);
assert(*p == 0);
test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);
const string test2 = "";
p = toStringz(test2);
assert(*p == 0);
assert(toStringz([]) is toStringz(""));
toStringz;
int core.sys.posix.unistd.execvp(scope const(char*), scope const(char**)) nothrow @nogcexecvp((local variable) const(char)*[] argvargv[0], cast(char**) (local variable) const(char)*[] argvargv.(field) const(char)** const(char)*[].ptrptr);
noreturn core.sys.posix.unistd._exit(int) nothrow @nogc @trusted_exit(127);
}
bool (local variable) bool reapedreaped;
int (local variable) int statusstatus;
scope (exit)
{
if (!(local variable) bool reapedreaped)
{
int core.sys.posix.signal.kill(int, int) nothrow @nogckill((local variable) const(int) childchild, (constant) int core.sys.posix.signal.SIGKILL = 9SIGKILL); // Only the probe-owned child.
int core.sys.posix.sys.wait.waitpid(int, int*, int) nothrow @nogcwaitpid((local variable) const(int) childchild, &(local variable) int statusstatus, 0);
}
int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose((local variable) int mastermaster);
}
assert(int core.sys.posix.fcntl.fcntl(int, int, ...) nothrow @nogcfcntl((local variable) int mastermaster, (constant) int core.sys.posix.fcntl.F_SETFL = 4F_SETFL, int core.sys.posix.fcntl.fcntl(int, int, ...) nothrow @nogcfcntl((local variable) int mastermaster, (constant) int core.sys.posix.fcntl.F_GETFL = 3F_GETFL) | (constant) int core.sys.posix.fcntl.O_NONBLOCK = 2048O_NONBLOCK) == 0);
char[] (local variable) char[] capturedcaptured;
void void editor_tui_close_probe.main.drain() nothrow @systemdrain()
{
char[8192] (local variable) char[8192] bytesbytes;
while (true)
{
const (local variable) const(long) countcount = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread((local variable) int mastermaster, (local variable) char[8192] bytesbytes.(constant) char* char[8192].ptr = &bytesptr, (local variable) char[8192] bytesbytes.(constant) ulong char[8192].length = 8192LUlength);
if ((local variable) const(long) countcount <= 0) break;
(local variable) char[] capturedcaptured ~= (local variable) char[8192] bytesbytes[0 .. (local variable) const(long) countcount];
}
if (!(local variable) bool reapedreaped) (local variable) bool reapedreaped = int core.sys.posix.sys.wait.waitpid(int, int*, int) nothrow @nogcwaitpid((local variable) const(int) childchild, &(local variable) int statusstatus, (constant) int core.sys.posix.sys.wait.WNOHANG = 1WNOHANG) == (local variable) const(int) childchild;
}
void void editor_tui_close_probe.main.awaitText(string expected, ulong since = 0LU) nothrow @systemawaitText((alias) object.string = stringstring (parameter) string expectedexpected, (alias) object.size_t = ulongsize_t (parameter) ulong sincesince = 0)
{
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!(local variable) char[] capturedcaptured[(parameter) ulong sincesince .. $].bool std.algorithm.searching.canFind!().canFind!(char[], string)(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((parameter) string expectedexpected) && !(local variable) bool reapedreaped && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
deadline)
{
(struct) core.sys.posix.poll.pollfdpollfd (local variable) core.sys.posix.poll.pollfd descriptordescriptor = {fd: (local variable) int mastermaster, events: (enum value) core.sys.posix.poll.POLLIN = 1POLLIN};
int core.sys.posix.poll.poll(core.sys.posix.poll.pollfd*, ulong, int) nothrow @nogcpoll(&(local variable) core.sys.posix.poll.pollfd descriptordescriptor, 1, 10);
void editor_tui_close_probe.main.drain() nothrow @systemdrain();
}
assert((local variable) char[] capturedcaptured[(parameter) ulong sincesince .. $].bool std.algorithm.searching.canFind!().canFind!(char[], string)(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((parameter) string expectedexpected), "Missing terminal text: " ~ (parameter) string expectedexpected ~ "\n" ~ (local variable) char[] capturedcaptured.string object.idup!char(char[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup);
assert(!(local variable) bool reapedreaped, "Terminal exited before the close decision: " ~ (local variable) char[] capturedcaptured.string object.idup!char(char[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup);
}
void void editor_tui_close_probe.main.send(string bytes) nothrow @nogc @systemsend((alias) object.string = stringstring (parameter) string bytesbytes) { assert(long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite((local variable) int mastermaster, (parameter) string bytesbytes.(field) immutable(char)* string.ptrptr, (parameter) string bytesbytes.(field) ulong string.lengthlength) == (parameter) string bytesbytes.(field) ulong string.lengthlength); }
void editor_tui_close_probe.main.awaitText(string expected, ulong since = 0LU) nothrow @systemawaitText("Sparkles Editor");
void editor_tui_close_probe.main.send(string bytes) nothrow @nogc @systemsend("a");
void editor_tui_close_probe.main.awaitText(string expected, ulong since = 0LU) nothrow @systemawaitText("Modified");
void editor_tui_close_probe.main.send(string bytes) nothrow @nogc @systemsend("\x03"); // Ctrl+C must request closure while the terminal is alive.
void editor_tui_close_probe.main.awaitText(string expected, ulong since = 0LU) nothrow @systemawaitText("Save, Discard or Cancel?");
void editor_tui_close_probe.main.send(string bytes) nothrow @nogc @systemsend("\x1B"); // Cancel; then use the ordinary Quit command.
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs); // Let the terminal's standalone-Escape deadline expire.
void editor_tui_close_probe.main.drain() nothrow @systemdrain();
const (local variable) const(ulong) beforebefore = (local variable) char[] capturedcaptured.(field) ulong char[].lengthlength;
void editor_tui_close_probe.main.send(string bytes) nothrow @nogc @systemsend("\x11"); // Ctrl+Q.
void editor_tui_close_probe.main.awaitText(string expected, ulong since = 0LU) nothrow @systemawaitText("Save, Discard or Cancel?", (local variable) const(ulong) beforebefore);
void editor_tui_close_probe.main.send(string bytes) nothrow @nogc @systemsend("d");
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!(local variable) bool reapedreaped && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
deadline)
{
(struct) core.sys.posix.poll.pollfdpollfd (local variable) core.sys.posix.poll.pollfd descriptordescriptor = {fd: (local variable) int mastermaster, events: (enum value) core.sys.posix.poll.POLLIN = 1POLLIN};
int core.sys.posix.poll.poll(core.sys.posix.poll.pollfd*, ulong, int) nothrow @nogcpoll(&(local variable) core.sys.posix.poll.pollfd descriptordescriptor, 1, 10);
void editor_tui_close_probe.main.drain() nothrow @systemdrain();
}
assert((local variable) bool reapedreaped && (local variable) int statusstatus == 0, "Discard did not flush and exit cleanly: " ~ (local variable) char[] capturedcaptured.string object.idup!char(char[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup);
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("terminal Ctrl+C deferred dirty close; Escape retained the draft; Ctrl+Q and Discard flushed and exited");
return 0;
}