## dist_zef-japhb-Terminal-Capabilities.md
[![Actions Status](https://github.com/japhb/Terminal-Capabilities/actions/workflows/test.yml/badge.svg)](https://github.com/japhb/Terminal-Capabilities/actions)

# NAME

Terminal::Capabilities - Container for terminal capabilities, with useful defaults

# SYNOPSIS

```
use Terminal::Capabilities;
use Terminal::Capabilities::Autodetect;

# Autodetect terminal and its capabilities via examination of terminal-related
# environment variables.  This does not touch the process table or run any
# subprocesses, so it should be quick and safe.
my ($autocaps, $terminal, $version) = terminal-env-detect;

# Create a terminal capabilities object with DEFAULT settings based on the most
# commonly well-supported capabilities, as determined by submissions to the
# Terminal::Tests project.  This method does NO AUTODECTION.
my Terminal::Capabilities $caps .= new;

# Examine individual capabilities
say $caps.symbol-set;   # ASCII by default, as it is the most compatible
say $caps.vt100-boxes;  # False by default, because ASCII does not require it
say $caps.color8bit;    # True  by default, since most terminals support it

# Override default symbol set
my $symbol-set = Terminal::Capabilities::SymbolSet::Uni1;
my $caps       = Terminal::Capabilities.new(:$symbol-set);

# Symbol set affects default for other features
say $caps.vt100-boxes;  # True, because WGL4R and all larger sets require it

# Determine best available symbol set supported by terminal out of a list
say $caps.best-symbol-set(< ASCII WGL4 MES2 Uni7 >);  # MES2, best <= Uni1

# Select from a list of options keyed by required symbol set
my %arrows = ASCII  => « < > »,
             Latin1 => < « » >,
             WGL4   => < ◄ ► >,
             Uni1   => < ◀ ▶ >,
             Uni7   => < ⯇ ⯈ >;
say $caps.best-symbol-choice(%arrows);  # ◀ ▶ , the Uni1 option

# Map a possibly mis-cased string to a SymbolSet enumerant (for processing
# user symbol set config requests)
my $symbol-set = symbol-set('cp1252');  # Terminal::Capabilities::SymbolSet::CP1252

```

# DESCRIPTION

Terminal::Capabilities is a relatively simple module that collects information about the capabilities of *modern* terminals (it assumes *at least* the ASCII character set, and ANSI/DEC VT style control sequence emulation).

The `Terminal::Capabilities::Autodetect` child module provides routines for autodetecting the user's terminal and its capabilities. The first such routine *only* examines environment variables, thus avoiding creating subprocesses, performing asynchronous queries to the terminal emulator, or mucking about in the user's process table. Simply call the `terminal-env-detect` routine to obtain a pre-populated `Terminal::Capabilities` object with the autodetection's best guesses, along with the terminal type detected and terminal program version if available:

```
use Terminal::Capabilities::Autodetect;
my ($caps, $type, $version) = terminal-env-detect;

```

Conversely, the core `Terminal::Capabilities` module does **not** do any autodetection, merely serving as a standard for collecting capabilities detected or configured through other means. That said, there are reasonable defaults for each of the capability flags based on the collected submissions to the `Terminal::Tests` project. The default values represent the capabilities that are universally supported (or nearly so -- there are a few truly deeply broken terminals for which nearly *nothing* works properly which are considered out of scope for the defaults).

One quirk of this method of determining defaults is that 8-bit color is more uniformly supported by modern terminals than various color and style attributes that were "standardized" decades earlier. Thus `color8bit` is by default `True`, while `colorbright` and `italic` are by default `False`.

## Known Symbol Sets

In superset order, from smallest to largest:

| Symbol Set | Contents |
| --- | --- |
| ASCII | 7-bit ASCII printables only (most compatible) |
| Latin1 | Latin-1 / ISO-8859-1 |
| CP1252 | CP1252 / Windows-1252 |
| W1G | W1G-compatible subset of WGL4R |
| WGL4R | Required (non-optional) WGL4 glyphs |
| WGL4 | Full WGL4 / Windows Glyph List 4 |
| MES2 | MES-2 / Multilingual European Subset No. 2 |
| Uni1 | Unicode 1.1 |
| Uni7 | Unicode 7.0 and Emoji 0.7 |
| Full | Full modern Unicode support (most features) |

The difference between `WGL4R` and full `WGL4` is that the latter includes 18 additional symbol and drawing glyphs needed for full compatibility with CP437, the code page (glyph set) used in IBM PC-compatible video ROMs and thus all DOS programs. As these 18 are considered optional in the WGL4 spec, `WGL4R` allows specifying only the symbols *required* by WGL4, and thus guaranteed to work in any terminal font with at least minimal WGL4 compatibility.

## Known Feature Flags

Several sets of flag (Bool) attributes indicate support for various features. There are sets for classic ANSI attributes, color support, and emoji handling:

| Attribute | Supported Feature |
| --- | --- |
| .bold | ANSI/VT100 bold attribute |
| .italic | ANSI/VT100 italic attribute |
| .inverse | ANSI/VT100 inverse attribute |
| .underline | ANSI/VT100 underline attribute |
| .color3bit | Original paletted 3-bit color |
| .colorbright | Bright variants of 3-bit palette |
| .color8bit | 6x6x6 color cube and 24-value grayscale |
| .color24bit | 24-bit RGB color |
| .emoji-text | Text outline emoji (VS15) |
| .emoji-color | Color emoji (VS16) |
| .emoji-skin | Skin tones for faces and people |
| .emoji-iso | Emoji flags for ISO country codes |
| .emoji-reg | Emoji flags for region codes |
| .emoji-zwj | Emoji combinations via joining (ZWJ) |

## class Terminal::Capabilities

A container for the available capabilities of a particular terminal

### sub symbol-set

```
sub symbol-set(
    Str:D $set = "Full"
) returns SymbolSet:D

```

Determine the correct SymbolSet enumerant for a possibly mis-cased string

### has SymbolSet:D $.symbol-set

Largest supported symbol repertoire

### has Bool $.vt100-boxes

Supports VT100 box drawing glyphs (nearly universal, but only *required* by WGL4R)

### method best-symbol-set

```
method best-symbol-set(
    @sets
) returns SymbolSet:D

```

Find best symbol set supported by this terminal from a list of choices

### method best-symbol-choice

```
method best-symbol-choice(
    %options
) returns Mu

```

Choose the best choice out of options keyed by required symbol set

# AUTHOR

Geoffrey Broadwell [gjb@sonic.net](mailto:gjb@sonic.net)

# COPYRIGHT AND LICENSE

Copyright 2023,2025 Geoffrey Broadwell

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## base.md
base

Combined from primary sources listed below.

# [In role Real](#___top "go to top of document")[§](#(role_Real)_method_base "direct link")

See primary documentation
[in context](/type/Real#method_base)
for **method base**.

```raku
method base(Real:D: Int:D $base where 2..36, $digits? --> Str:D)
```

Converts the number to a string, using `$base` as base. For `$base` larger than ten, capital Latin letters are used.

```raku
255.base(16);            # 'FF'
```

The optional `$digits` argument asks for that many digits of fraction (which may not be negative). If omitted, a reasonable default is chosen based on type. For Int this default is 0. For [`Num`](/type/Num), the default is 8. For [`Rational`](/type/Rational), the number of places is scaled to the size of the denominator, with a minimum of 6.

A special value of [`Whatever`](/type/Whatever) (`*`) can be given as `$digits`, which functions the same as when `$digits` is not specified for all `Real` types except the [`Rational`](/type/Rational)s. For [`Rational`](/type/Rational)s, the [`Whatever`](/type/Whatever) indicates that you wish all of the possible digits of the fractional part, but use caution: since there's no detection of repeating fractional parts (the algorithm will eventually stop after generating 2\*\*63 digits).

The final digit produced is always rounded.

```raku
say pi.base(10, 3);      # OUTPUT: «3.142␤»
say (1/128).base(10, *); # OUTPUT: «0.0078125␤»
say (1/100).base(10, *); # OUTPUT: «0.01␤»
say (1/3)  .base(10, *); # WRONG: endlessly repeating fractional part
```

For reverse operation, see [`parse-base`](/routine/parse-base)


## dist_cpan-BDUGGAN-Terminal-UI.md
## Terminal::UI

A framework for building terminal interfaces.

## Example

Create a box in full screen with some text in it, wait for a key, then exit:

```
use Terminal::UI 'ui';
ui.setup(:1pane);
ui.pane.put("Hello world.");
ui.get-key;
ui.shutdown;

╔══════════════╗
║Hello world.  ║
║              ║
╚══════════════╝

```

## Example 2

Make a screen split with a line in the middle, with scrollable text on the top
and bottom, and a selected row in the top box. The arrow keys (or j,k) move
the selected line up and down. Tab switches to the other box.

```
use Terminal::UI 'ui';
ui.setup(:2panes);
ui.panes[0].put("$_") for 1..10;
ui.panes[1].put("$_") for <hello world>;
ui.interact;
ui.shutdown;

╔══════════════╗
║8             ║  <- selected in green, scrollable
║9             ║
║10            ║
╟──────────────╢
║hello         ║  <- selected in grey.
║world         ║
╚══════════════╝

```

## Example 3

Like example 2, but also -- pressing Enter in the top box
will some text about add the currently selected row to the
bottom box:

```
ui.setup(:2panes);
ui.panes[0].put("$_") for 1..10;

ui.panes[0].on: select => -> :$raw, :$meta {
  ui.panes[1].put("you chose $raw!")
}

ui.interact;
ui.shutdown;

╔══════════════╗
║8             ║  <- press Enter, and…
║9             ║
║10            ║
╟──────────────╢
║you chose 8!  ║  <- …this appears!
║              ║
╚══════════════╝

```

## Features and design goals

* Easy to quickly make a console interface with custom behavior, but practical defaults.
* Scrolling with some optimization, such as using ANSI scroll region escape sequences.
* Thread safe. Concurrency friendly. Unicode compatibile.
* Dynamic geometry calculation, for smart handling of window resizing.

## More examples

See the [eg](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/eg/) directory.

## See also

<https://blog.matatu.org/terminal-ui>

## Description

The best place for documentation is the
[examples](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/eg/) directory.

There is also reference documentation with links to the source code -- see
[Terminal::UI](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/lib/Terminal/UI.md). Other classes
with documentation are:

* [Terminal::UI::Screen](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/lib/Terminal/UI/Screen.md)
* [Terminal::UI::Frame](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/lib/Terminal/UI/Frame.md)
* [Terminal::UI::Pane](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/lib/Terminal/UI/Pane.md)
* [Terminal::UI::Style](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/lib/Terminal/UI/Style.md)
* [Terminal::UI::Input](https://git.sr.ht/~bduggan/raku-terminal-ui/tree/master/item/lib/Terminal/UI/Input.md)

## BUGS

Probably!

If you find some bugs, or just have something to say, feel free to contact the author, or
reach out on the mailing list:

<https://lists.sr.ht/~bduggan/raku-terminal-ui>

## Author

Brian Duggan (bduggan at matatu.org)


## controlflow.md
class X::ControlFlow

Error due to calling a loop control command in an ineligible scope

```raku
class X::ControlFlow is Exception { }
```

Thrown when a control flow construct (such as `next` or `redo`) is called outside the dynamic scope of an enclosing construct that is supposed to catch them.

For example

```raku
last;
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::ControlFlow: last without loop construct␤»
```

# [Methods](#class_X::ControlFlow "go to top of document")[§](#Methods "direct link")

## [method illegal](#class_X::ControlFlow "go to top of document")[§](#method_illegal "direct link")

```raku
method illegal returns Str:D
```

Returns the name of the control flow command that was called.

## [method enclosing](#class_X::ControlFlow "go to top of document")[§](#method_enclosing "direct link")

```raku
method enclosing returns Str:D
```

Returns the name of the missing enclosing construct.


## conditionvariable.md
class Lock::ConditionVariable

Condition variables used in locks

```raku
class Lock::ConditionVariable {}
```

Condition variables are used in [`Lock`](/type/Lock)s to wait for a particular condition to become true. You will normally not create one from scratch, but call [`Lock.condition`](/type/Lock#method_condition) to acquire one on a particular [`Lock`](/type/Lock).

# [Methods](#class_Lock::ConditionVariable "go to top of document")[§](#Methods "direct link")

## [method wait](#class_Lock::ConditionVariable "go to top of document")[§](#method_wait "direct link")

```raku
multi method wait( --> Nil )
multi method wait( &predicate --> Nil )
```

Without any predicate, it waits on the condition variable itself; with a predicate, waits until the code returns a truish value.

```raku
    my $times = 100;
    my $tried;
    my $failed;
    for ^$times {
        my $l = Lock.new;
        my $c = $l.condition;
        my $now1;
        my $now2;
        my $counter = 0;
        my $t1 = Thread.start({
            $l.protect({
                $c.wait( { $counter != 0 } );
                $now1 = now;
            });
        });

        my $t2 = Thread.start({
            $l.protect({
                $counter++;
                $c.signal();
            });
        });

        $t1.join();
        $now2 = now;
        $t2.join();

        $tried++;
        last if $failed = ( !$now1.defined or $now1 > $now2 );
    }

```

The condition we obtain from the `$l` lock is awaited using a predicate, in this case, check if the counter is still zero. When it takes another value, the program flow continues in the next instruction.

## [method signal](#class_Lock::ConditionVariable "go to top of document")[§](#method_signal "direct link")

```raku
method signal()
```

If and only if there are any threads that have previously waited on the condition variable, it unblocks at least one of them. Let's see how it works in this example:

```raku
constant ITEMS = 100;
for 1..15 -> $iter {
    my $lock = Lock.new;
    my $cond = $lock.condition;
    my $todo = 0;
    my $done = 0;
    my @in = 1..ITEMS;
    my @out = 0 xx ITEMS;

    for 1..ITEMS -> $i {
        my $in = $i;
        my $out := @out[$i];
        Thread.start( {
                    $out = $in * 10;
                    $lock.protect( {
                        $done++;
                        $cond.signal if $done == $todo;
                    } );
        } );
        $todo++;
    }
    $lock.protect( {
        $cond.wait({  $done == $todo } );
    });
    say @out;
}

```

We are repeating 15 times the same operation: start 100 threads, every one of which modify a single element in an array. We `protect` the modification of a global variable, `$done`, and use `signal` to wake up another thread to do its thing. This outputs the first elements of the generated arrays.


## dist_zef-coke-App-Cal.md
# NAME

cal - command-line calendar utility

# DESCRIPTION

```
$ cal

```

Displays the current month, highlighting today's date.

```
$ cal 2016

```

Displays the full calendar for the year 2016.

```
$ cal 9

```

Displays the calendar for the 9th month of the current year.

```
$ cal February

```

Displays the calendar for February of this year.

```
$ cal February 1997

```

Displays the calendar for February of 1997.

# Options

```
-h

```

Disable highlighting.

```
-n

```

Display weeks vertically instead of horizontally (like ncal).

```
-w

```

Include week numbers (Only works with `-n`).


## dist_zef-jonathanstowe-AccessorFacade.md
# AccessorFacade

A Raku method trait to turn indivdual get/set subroutines into a single read/write object attribute.

![Build Status](https://github.com/jonathanstowe/AccessorFacade/workflows/CI/badge.svg)

## Description

This module was initially designed to reduce the boiler plate code in
a native library binding that became something like:

```

    class Shout is repr('CPointer') {

        sub shout_set_host(Shout, Str) returns int32 is native('libshout') { * }
        sub shout_get_host(Shout) returns Str is native('libshout') { * }

        method host() is rw {
            Proxy.new(
                FETCH => sub ($) {
                    shout_get_host(self);
                },
                STORE   =>  sub ($, $host is copy ) {
                    explicitly-manage($host);
                    shout_set_host(self, $host);
                }
            );
        }

        ...

    }

```

That is the library API provides a sort of "object oriented" mechanism to
set and get attributes on an opaque object instance that was returned
by another "constructor" function. Because the object is an opaque
CPointer it can only have subroutines and methods and not private data or
attributes. The intent of the code is to provide fake "attributes" with
rw methods (which is similar to how public rw attributes are provided.)

The above code will be reduced with the use of AccessorFacade to:

```

    class Shout is repr('CPointer') {

        sub shout_set_host(Shout, Str) returns int32 is native('libshout') { * }
        sub shout_get_host(Shout) returns Str is native('libshout') { * }

        method host() is rw is accessor-facade(&shout_get_host, &shout_set_host) { }

        ...
    }

```

The named argument style is also supported so the method could be written as:

```
    method host() is rw is accessor-facade(getter => &shout_get_host, setter => &shout_set_host) { }

```

if that proves more suitable.

(The call to explicitly manage is omitted for simplicity but how this is
achieved is described in the documentation.) Libshout has a significant
number of these get/set pairs so there is a reduction of typing, copy
and paste and hopefully programmer error.

Whilst this was designed primarily to work with a fixed native API, it
is possible that it could be used to provide an OO facade to a plain
Raku procedural library. The only requirement that there is a getter
subroutine that accepts an object as its first argument and returns the
attribute value and a setter subroutine that accepts the object and the
value to be set (it may return a value to indicate success - how this
is handled is descibed in the documentation.)

## Installation

Assuming you have a working Rakudo installation you should be able to install this with *zef* :

```
# From the source directory

zef install .

# Remote installation

zef install AccessorFacade

```

## Support

Suggestions/patches are welcomed via github at:

<https://github.com/jonathanstowe/AccessorFacade/issues>

## Licence

This is free software.

Please see the <LICENCE> file in the distribution

© Jonathan Stowe 2015 - 2021


## named.md
class Pod::Block::Named

Named block in a Pod document

```raku
class Pod::Block::Named is Pod::Block { }
```

Class for a named Pod block. For example

```raku
=begin MySection
...
=end MySection

```

creates a `Pod::Block::Named` with name `MySection`.

# [Methods](#class_Pod::Block::Named "go to top of document")[§](#Methods "direct link")

## [method name](#class_Pod::Block::Named "go to top of document")[§](#method_name "direct link")

```raku
method name(--> Str:D)
```

Returns the name of the block.


## dist_zef-thundergnat-Acme-Scrub.md
[![Actions Status](https://github.com/thundergnat/Acme-Scrub/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Acme-Scrub/actions)

# NAME

Acme::Scrub

# DESCRIPTION

Are your Raku files a mess? Have some nasty code you keep meaning to refactor but just can't find the time? Tired of looking at all those impenetrable Unicode operators? Help has arrived!

In the spirit of Perl5's Acme::Bleach;

Acme::Scrub, a quick and easy way to clean up ugly code.

# USAGE

At or near the top of your file, include the line:

```
use Acme::Scrub;

```

The first time you run a script that uses Acme::Scrub, the line will be changed to:

```
use Acme::Scrub; # for REALLY clean code.

```

and all the unsightly code below that line will be cleaned up, but it will still work the same way.

# WARNINGS, CAVEATS, PROVISIOS & QUID PRO QUOS

This modifies and overwrites the original file. It is highly recommended to save backup copies BEFORE using Acme::Scrub. It is possible to recover the original code... but why would you want to?

Do not use Acme::Scrub for security. See above note. You will get only slightly less effective security by putting a sticky note over your source code.

You can not have anything else on the line after

```
use Acme::Scrub;

```

no spaces, no comments. Acme::Scrub will add it's own comment to the line, and it is somewhat fragile to manual edits. (Hey, if you wanted robust, why are you using an Acme module?)

# BUGS

Probably.

# AUTHOR

Stephen Schulze otherwise known as thundergnat [thundergnat@comcast.net](mailto:thundergnat@comcast.net)

# COPYRIGHT AND LICENSE

Copyright 2022 thundergnat

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_cpan-LEMBARK-FindBin-libs.md
```

This should work anyplace File::Spec can split directories, which
should be anywhere Perl runs.

This may not do much good on Windows: the crazy directory structure
common to Windows systems do not seem very amenable to using
$FindBin::Bin as the starting point for locating libraries.

Anyone with access to VMS warn me if this works at all -- through
judicious use of virtual devices should make it useful.

The pod describes using the module in a few situations, any
suggestions appreciated. In particular, I toyed with several ways of
passing in switches. The one used here was chosen because it supports
qw( ... ) syntax with optional parameters (e.g., qw(export) and
qw(export=foo)).

Versions of the module support Perl v5.8 - v5.13, v5.14 - v5.27,
and v5.28+. The 5.8-10 and v.14-28 versions are unmaintained
other than the tests which are common to all versions.

Installation:

    perl Makefile.PL;
    make all test install;
    perldoc FindBin::libs;

also see the examples for come common use cases.

Zei gesund

```


## dist_zef-martimm-Gnome-Gdk4.md
![](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png)

# Gnome Gdk

![Artistic License 2.0](https://martimm.github.io/label/License-label.svg)

# Description

## Documentation

* [🔗 Website, entry point for all documents and blogs](https://martimm.github.io/)
* [🔗 License document](https://www.perlfoundation.org/artistic_license_2_0)
* [🔗 Release notes of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/blob/main/CHANGES.md)
* [🔗 Issues of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/issues)

# Installation

Do not install this package on its own. Instead install `Gnome::Gtk4` newest api.

`zef install Gnome::Gtk4:api<2>`

# Author

Name: **Marcel Timmerman**
Github account name: **MARTIMM**

# Issues

There are always some problems! If you find one please help by filing an issue at [my github project](https://github.com/MARTIMM/gnome-source-skim-tool/issues).

# Attribution

* The inventors of Raku, formerly known as Perl 6, of course and the writers of the documentation which helped me out every time again and again.
* The builders of all the Gnome libraries and the documentation.
* Other helpful modules for their insight and use.


## dist_zef-raku-community-modules-URI.md
[![Actions Status](https://github.com/raku-community-modules/URI/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/URI/actions) [![Actions Status](https://github.com/raku-community-modules/URI/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/URI/actions) [![Actions Status](https://github.com/raku-community-modules/URI/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/URI/actions)

# NAME

URI — Uniform Resource Identifiers (absolute and relative)

# SYNOPSIS

```
use URI;
my $u = URI.new('http://example.com/foo/bar?tag=woow#bla');

# Look at the parts
say $u.scheme;     #> http
say $u.authority;  #> example.com
say $u.host;       #> example.com
say $u.port;       #> 80
say $u.path;       #> /foo/bar
say $u.query;      #> tag=woow
say $u.fragment;   #> bla

# Modify the parts
$u.scheme('https');
$u.authority('example.com:8443');
$u.path('/bar/foo');
$u.query('x=1&y=2'); # OR
$u.fragment('cool');
say "$u"; #> https://example.com:8443/bar/foo?x=1&y=2#cool

# Authority is an object, but may be undefined
with $u.authority {
    say .userinfo; # none set, no output
    say .host;     #> example.com
    say .port;     #> 8443

    # It is mutable too
    .userinfo('bob');
    say $u.authority; #> bob@example.com:8443
}

# Path is an object, always defined, but immutable
with $u.path {
    say .path;          #> /bar/foo
    .say for .segments; #> bar\nfoo\n
}

# Query is an object, always defined, mutable
with $u.query {
    say .query;              #> x=1&y=2
    .query('foo=1&foo=2');
    say .query-form<foo>[0]; #> 1
    say .query-form<foo>[1]; #> 2

    .query-form.push: 'bar' => 'ok';
    say .query;              #> foo=1&foo=2&bar=ok

    .query('');
    .query-form<abc> = 123;
    say .query;              #> abc=123
}

```

# DESCRIPTION

A URI object represents a parsed string that abides by the grammar defined in RFC 3986 for Universal Resource Identifiers. The object then works to enforce the rules defined in the RFC for any modifications made to it.

As of this writing, The URI class is scheme agnostic. It will verify that URI is correct, in general, but not correct for a given scheme. For example, `http:foo` would be considered a valid URI even though that is not a valid URI according to the rules specific to the `http` scheme.

This class uses "heavy accessors". From the SYNOPSIS, you may have noted that assignment to accessors is not used. This is because nearly all accessors in this class do some extra work of parsing, validating, and cross-referencing with other fields to guarantee that the URI is correct before making a change.

```
my $u = URI.new;
$u.path = '/foo/bar'; # ERROR: «Cannot modify an immutable URI::Path»
$u.path('/foo/bar');  # WORKS!

```

This mutator pattern is meant to reflect the internal complexity.

## SCHEME, AUTHORITY, AND PATH

In RFC 3986 URIs, the scheme, the authority, and the path are related. This should not matter most of the time, but to avoid problems when setting these three, it is safest to set them in this order:

```
my $u = URI.new;
$u.path('');
$u.scheme($my-scheme);
$u.authority($my-host);
$u.path($my-path);

```

This is because an empty path is permitted in any case, but the format of the path is limited whether an authority and scheme are set.

With an authority set (i.e., the URI either starts with "//" or with "scheme://"), a non-empty path must start with a "/" and may start with empty path segments, e.g. "scheme://foo//" is valid.

When there's no authority set, but a scheme is used (e.g., it starts with "scheme:", but not "scheme://"), a non-empty path may either start with a "/" or not, but must contain one or more other characters in the first segment of the path. Thus, the following code will fail:

```
my $u = URI.new('scheme:');
$u.path('//'); # ERROR: «Could not parse path "//" as part of URI: scheme://»

```

When there's no authority and no scheme used, a non-empty path may start with a "/" or not, but must contain one or more other characters in the first segment.

These rules are enforced whenever setting or clearing the scheme, authority, or path. If the resulting URI object would be invalid an `X::URI::Path::Invalid` exception will be thrown.

## QUERY

The `query` method of this class returns a `URI::Query` object. This is a special object that is `Positional`, `Associative`, and `Iterable`. That is, it can be bound to an array variable, a hash variable, and iterated using a loop. If stringified, it will return a URI-encoded query. If used as an array, will act like somewhat like an array of `Pair`s. If used as a hash, will provide a map from query keys to query values.

The native internal representation is a list of `Pair`s as this is the best match for how queries are defined. Because of this, there's a problem when using a query as a hash: duplicate pairs are valid. To handle this, the `URI::Query` object always returns a list of values, sorted in the order they appear for each key.

For example:

```
my $u = URI.new('?foo=1&bar=2&foo=3');
say $u.query<foo>[0]; #> 1
say $u.query<foo>[1]; #> 3
say $u.query<bar>[0]; #> 2

```

Older versions of the URI module handled this differently, using a mixed value representation. In order to gain some backwards compatibility, this is still supported by setting the `hash-format`:

```
# Continues from previous
$u.query.hash-format = URI::Query::Mixed;
say $u.query<foo>[0]; #> 1
say $u.query<foo>[1]; #> 3

# The bar value is NOT a list now
say $u.query<bar>;    #> 2

# Return to the default mode
$u.query.hash-format = URI::Query::Lists;

```

However, the list version is safer and may likely work with most existing code that worked with mixed before.

Another mode is provided to force single values, which is often how applications treat these out of convenience. In that case, only the last value will be kept:

```
# Continues from previous
$u.query.hash-format = URI::Query::Singles;

# These are never lists now
say $u.query<foo>; #> 3
say $u.query<bar>; #> 2

```

The `URI::Query::Lists` mode is default and recommended mode.

## GRAMMAR

This class will keep a copy of the result of parsing the URI string for you. If you are interested in precise details of the parse tree, you get them using the `grammar` method:

```
my $host-in-grammar =
  $u.grammar.parse-result<URI-reference><URI><hier-part><authority><host>;
if $host-in-grammar<reg-name> {
    say 'Host looks like registered domain name - approved!';
}
else {
    say 'Sorry we do not take ip address hosts at this time.';
    say 'Please use registered domain name!';
}

```

The `IETF::RFC_Grammar::URI` grammar sticks close to the BNF defined in RFC 3986.

## PARTIAL MATCHING

Many times a URI you are interested in is embedded within another string. This class will allow you to parse URIs out of a larger string, so long as the URI is at the start. This is done by setting the `:match-prefix` option during construction or when calling `parse`:

```
{
    # require whole string matches URI and throw exception otherwise ..
    my $u_v = URI.new('http://?#?#');
    CATCH { when X::URI::Invalid { ... } }
}

my $u_pfx = URI.new('http://example.com } function(var mm){', :match-prefix);

```

# METHODS

## method new

```
multi method new(URI:U: Str() $uri, Bool :$match-prefix--> URI:D)
multi method new(URI:U: Str() :$uri, Bool :$match-prefix--> URI:D)

```

These construct a new `URI` object and return it. The given `$uri` value is converted to a string and then parsed using the `parse` method.

If `:match-prefix` is set, then the grammar will be allowed to match a prefix of the given input string rather than requiring a total match. The `:match-prefix` given also becomes the default value for any future calls to `parse`.

Throws a `X::URI::Invalid` exception if the URI cannot be parsed.

## method parse

```
method parse(URI:D: Str() $str, Bool :$match-prefix = $.match-prefix)

```

This method allows an existing URI object to be reused to parse another string. This parses the given string and replaces all internal state of the object with values for the new parse.

The given `:match-prefix` flag becomes the new default when set.

Throws a `X::URI::Invalid` exception if the URI cannot be parsed.

## method grammar

```
method grammar(URI:D: --> IETF::RFC_Grammar:D)

```

Returns the object used to parse and store the state of the parse.

## method match-prefix

```
method match-prefix(URI:D:--> Bool:D)

```

Returns `True` if the most recent call to `parse` (or `new`) allowed a prefix match or `False` if a total match was required. This is the default value of any future call to `parse`.

## method scheme

```
multi method scheme(URI:D:--> URI::Scheme:D)
multi method scheme(URI:D: Str() $scheme--> URI::Scheme:D)

```

Returns the scheme part of the URI. This is a string that must match the `URI::Scheme` subset type.

The second form allows the scheme to be replaced with a new scheme. It is legal for the scheme to be set to an empty string, which has the effect of making the URI scheme-less.

This will throw an `X::URI::Path::Invalid` exception if adding or removing the scheme will make the URI invalid. See SCHEME, AUTHORITY, AND PATH section for additional details.

## method authority

```
multi method authority(URI:D:--> URI::Authority)
multi method authority(URI:D: Nil--> URI::Authority:U)
multi method authority(URI:D: Str() $new--> URI::Authority:D)

```

Returns the `URI::Authority` for the current URI object. This may be an undefined type object if no authority has been set or found during parse.

When passed a string, the string will have the authority parsed out of it and a new authority object will be used to store the parsed information. An empty authority is valid.

When passed `Nil`, the authority will be cleared.

When passing an argument, this will throw an `X::URI::Path::Invalid` exception if setting or clearing the authority on the URI will make the URI invalid. See SCHEME, AUTHORITY, AND PATH section for details.

The authority is made up of three components: userinfo, host, and port. Additional methods are provided for accessing each of those parts separately.

## method userinfo

```
multi method userinfo(URI:D:--> URI::Userinfo:D)
multi method userinfo(URI:D: Str() $new--> URI::Userinfo:D)

```

The userinfo is an optional component of the URI authority. This method returns the current userinfo or an empty string.

Setting this method will cause a `URI::Authority` to be constructed and `authority` to be set, if it is not already defined. This may result in a `X::URI::Path::Invalid` exception being thrown if adding an authority will make the path invalid.

## method host

```
multi method host(URI:D:--> URI::Host:D)
multi method host(URI:D: Str() $new--> URI::Host:D)

```

The host is a component of the URI authority. This method returns the current host or an empty string.

Setting this method will cause a `URI::Authority` to be constructed and `authority` to be set, if it is not already defined. This may result in a `X::URI::Path::Invalid` exception being thrown if adding an authority will make the path invalid.

## method default-port

```
method default-port(URI:D:--> URI::Port)

```

This method applies the `scheme-port` method of `URI::DefaultPort` to the scheme set on this object. Basically, a shortcut for:

```
my $u = URI.new("...");
my $port = URI::DefaultPort.scheme-port($u.scheme);

```

It returns the usual port for the named scheme.

## method \_port

```
multi method _port(URI:D:--> URI::Port)
multi method _port(URI:D: Nil--> URI::Port:U)
multi method _port(URI:D: Int() $new--> URI::Port:D)

```

When an authority is set on the URI, this gets or sets the authority's port. This differs from `port`, which returns either the port set or the `default-port`. This method returns just the port.

If no authority is set or no port is set, this returns an undefined value (i.e., an `Int` type object).

Setting this method will cause a `URI::Authority` to be constructed and `authority` to be set, if it is not already defined. This may result in a `X::URI::Path::Invalid` exception being thrown if adding an authority will make the path invalid.

## method port

```
multi method port(URI:D:--> URI::Port)
multi method port(URI:D: Nil--> URI::Port)
multi method port(URI:D: Int() $new--> URI::Port)

```

When retrieving a value from the object, this method returns either the port set on the authority or the default port for the current URI scheme. It may return an undefined value (i.e., an `Int` type object) if there is no port set and no known default port for the current scheme or no scheme set.

When setting a value on the object, this method sets the port on the authority.

Setting this method will cause a `URI::Authority` to be constructed and `authority` to be set, if it is not already defined. This may result in a `X::URI::Path::Invalid` exception being thrown if adding an authority will make the path invalid.

## method path

```
multi method path(URI:D:--> URI::Path:D)
multi method path(URI:D: Str() $path--> URI::Path:D)

```

Path is the main required element of a URI, but may be an empty string. This method returns the current setting for the path as a `URI::Path` object. It also allows setting a new path, which will construct a new `URI::Path` object.

This method will throw a `X::URI::Path::Invalid` exception if the path is not valid for the current scheme and authority settings.

## method segments

```
multi method segments(URI:D:--> List:D)
multi method segments(URI:D: @segments where *.elems > 0--> List:D)
multi method segments(URI:D: $first-segment, *@remaining-segments--> List:D)

```

Returns the path segments (i.e., the parts between slashes). This is a shortcut for:

```
my $u = URI.new("...");
my @s = $u.path.segments;

```

The number of segments is equal to the number of slashes in the original path plus one. The segments are constructed so that joining the segments by a slash (/) will give you the original path.

You may pass a list in to replace the segments with a new value. This will throw a `X::URI::Path::Invalid` exception if any of the segments contain a slash or if the set path will cause the URI to become invalid.

Be sure when setting segments to include an initial empty string if you want the path to start with a slash.

## method query

```
multi method query(URI:D:--> URI::Query:D)
multi method query(URI:D: Str() $new--> URI::Query:D)
multi method query(URI:D: *@new--> URI::Query:D)

```

Accesses or updates the query associated with the URI. This is returns as a `URI::Query` object. This will always be defined, but may be empty.

When passed a string, the string will be parsed using `split-query` and the query object will be updated. When passed a list, the list of `Pair`s given will be used to setup a new query that way.

When the list form is used, any named parameters passed will be ignored (they will not be used to fill the query) and a warning will be issued.

## method path-query

```
method path-query(URI:D:--> Str:D)

```

Returns the path and query as a string joined by a question mark ("?"). It will return just the path as a string if the query is empty.

## method fragment

```
multi method fragment(URI:D:--> URI::Fragment:D)
multi method fragment(URI:D: Str() $new--> URI::Fragment:D)

```

Returns the URI fragment, which is always defined, but may be an empty string. If passed a value, it will set the fragment.

## method gist

```
multi method gist(URI:D:--> Str:D)

```

Reconstructs the URI from the components and returns it as a string.

## method Str

```
multi method Str(URI:D:--> Str:D)

```

Reconstructs the URI from the components and returns it as a string.

# SUBROUTINES

## sub split-query

```
sub split-query(Str() $query, :$hash-format = URI::Query::None)

```

This routine will slice and dice a query string, which is useful when parsing URIs and may also be useful when parsing POST entities that are encoded as `application/x-www-form-urlencoded`.

This routine is exported with the `:split-query` tag or can be used with the full namespace, `URI::split-query`.

With just the required string, this routine will parse that string and return a list of `Pair`s mapping each query form key to its respective value. The order is preserved. This is used by `URI::Query` during construction.

For example:

```
my @qf = URI::split-query("foo=1&bar%20=2&foo=3");
dd @qf; #> Array @qf = [:foo("1"), "bar " => ("2"), :foo("3")]

```

Notice that this will perform a `uri-escape` operation of keys and values in the process so the values you receive have had the URI encoded characters decoded.

You can retrieve the query string as a hash instead by passing the `:hash-format` option. This works exactly as it does for `URI::Query`.

The options for `:hash-format` include:

### URI::Query::Lists

Every key is mapped to a list of one or more values. From the example input, a structure like the following is returned:

```
my %qf = URI::split-query("foo=1&bar%20=2&foo=3",
    hash-format => URI::Query::Lists,
);
dd %qf; #> Hash %qf = {"bar " => (["2"]), :foo(["1", "3"])}

```

This is also the default if you just pass `:hash-format` as a boolean option.

### URI::Query::Mixed

Every key is mapped to either a list of two or more values or directly to a single value, like the following:

```
my %qf = URI::split-query("foo=1&bar%20=2&foo=3",
    hash-format => URI::Query::Mixed,
);
dd %qf; #> Hash %qf = {"bar " => ("2"), :foo(["1", "3"])}

```

### URI::Query::Singles

Every key is mapped to a single value, which will be the last value encountered in the input, like this:

```
my %qf = URI::split-query("foo=1&bar%20=2&foo=3",
    hash-format => URI::Query::Mixed,
);
dd %qf; #> Hash %qf = {"bar " => ("2"), :foo("3")}

```

# HELPER SUBSETS

## URI::Scheme

This is a subset of `Str` that only accepts valid schemes.

## URI::Userinfo

This is a subset of `Str` that only accepts valid userinfo.

## URI::Host

This is a subset of `Str` that only accepts valid hosts.

## URI::Port

This is a subset of `UInt`.

## URI::Query::ValidQuery

This is a subset of `Str` that only accepts valid query strings.

## URI::Fragment

This is a subset of `Str` that only accepts valid URI fragments.

# HELPER CLASSES

## URI::Authority

The `authority` method of a URI constructs or returns this object.

It is recommended that you do not construct a `URI::Authority` object directly, but let the methods of `URI` handle construction.

### method userinfo

```
method userinfo(URI::Authority:D: --> URI::Userinfo:D) is rw

```

This is a simple setter/getter for the userinfo on the authority. It must be defined, but may be the empty string. If not empty, it must be valid for the userinfo component of a URI.

### method host

```
method host(URI::Authority:D: --> URI::Host:D) is rw

```

This is a simple setter/getter for the host part of the URI authority. It must be defined, but may be the empty string. If not empty, must be a valid host value, which may be an IP address or registered name.

### method port

```
method port(URI::Authority:D: --> URI::Port) is rw

```

This is a simple setter/getter for the port part of the URI authority. It may be set to an undefined value if no explicit port is set in the authority. If defined, it must an unsigned integer.

### method gist

```
multi method gist(URI::Authority:D:--> Str:D)

```

Returns the string representation of the URI authority. For example:

```
my $u = URI.new("http://steve@example.com:8008");

# say calls .gist
say $u.authority; #> "steve@example.com:8080";

```

### method Str

```
multi method gist(URI::Authority:D:--> Str:D)

```

Stringifies identical to `gist`.

## URI::Path

This class is used to represent URI path components.

It is recommended that you do not construct a `URI::Path` object directly, but rely on the `path` setter in `URI` instead. These objects are immutable. Please use methods on `URI` to make changes.

### method path

```
method path(URI::Path:D:--> Str:D)

```

Returns the string representation of the path.

### method segments

```
method segments(URI::Path:D:--> List:D)

```

Returns a list representation of the path segments. In a URI, the path segments are the strings between slashes ("/").

### method gist

```
method gist(URI::Path:D:--> Str:D)

```

Returns the `path`.

### method Str

```
method Str(URI::Path:D:--> Str:D)

```

Returns the `path`.

## URI::Query

This class is used to represent a URI query component. This class may be safely constructed and used independently of the URI object.

It behaves as both a positional and associative object and is iterable. Internally, it is stored as an `Array` of `Pair`s. You must not treat this object purely as you would an `Array` or purely as you would a `Hash` as some methods will not work the way you expect.

The performance of the associative methods is not guaranteed and is probably going to be relatively slow. This implementation values simplicity and accuracy of representation to CPU performance. If you need something that is better for CPU performance, you should investigate the use of another library, such as `Hash::MultiValue` or sub-class to provide a higher performance implementation of `URI::Query`'s associative methods.

### method new

```
multi method new(Str() $query, URI::Query::HashFormat :$hash-format = URI::Query::Lists--> URI::Query:D)
multi method new(:$query, URI::Query::HashFormat :$hash-format = URI::Query::Lists--> URI::Query:D)

```

Constructs a new `URI::Query` from the given string, which may be empty.

Unlike `split-query`, which permits boolean values for the `hash-format` option, `URI::Query` requires a `URI::Query::HashFormat` value and will reject a boolean (because the boolean does not make sense in this case).

### enum HashFormat

This enumeration provides the values that may be set on `hash-format` on a `URI::Query`. Possible values are as follows.

#### URI::Query::List

This is the default and recommended value. When set in `hash-format`, each key in the hash representation will point to a list of one or more values.

This is recommended as it is the most accurate representation to what is actually possible in a query string. The values within each key will be sorted in the same order as they appear in the query.

#### URI::Query::Mixed

When set in `hash-format`, each key in the hash representation may be mapped to either a list of two or more values, or to the value itself if there is only one.

This is not recommended because it means that setting a key to an iterable value will be treated as multiple key-value pairs when it comes time to render the query as a string. This could have unintended consequences.

#### URI::Query::Singles

When set in `hash-format`, each key in the hash representation will be mapped directly to a single value. If there are multiple values that have been set in the query, then only the last will be visible through the hash representation.

This is not recommended because it may hide certain values, but may be useful for simple applications that treat the query string as having unique values. Just note that the trade-off is that your application may be confused when multiple values are present.

#### URI::Query::None

This value should not be used, but will be treated the same as `URI::Query::List` if used here. It is provided for use with `split-query` only.

### method hash-format

```
method hash-format(URI::Query:D --> URI::Query::HashFormat) is rw

```

This is a simple setter/getter for setting the way in which associative lookups are performed. See `enum URI::Query::HashFormat` for a description of each mode.

### method query

```
method query(Query:D:--> URI::Query::ValidQuery:D)
method query(Query:D: Str() $new--> URI::Query::ValidQuery:D)

```

This method returns the string representation of the URI query component. When passed a string, it will replace the query with the new value and will use `split-query` to parse that query into an array of `Pair`s.

The primary representation of the queryo object is the value returned by `query-form`. The `query` is cached to keep the value stored in it when this method is called to set it or when `URI::Query` is constructed from a string. Any modification to the internal array of pairs, though, will clear this cache. It will be generated the next time the `query` method is called and that string will be cached.

### method query-form

```
method query-form(Query:D:--> Array:D)
method query-form(Query:D: *@new, *%new--> Array:D)

```

This method returns the array of `Pair`s that store the internal representation of the URI query component. When passed an array of `Pair`s, it will replace the current value with that array.

A quick note about the way pairs are passed as parameters to a method, you most likely want to avoid passing values as named parameters. If values are passed using unquoted strings, they will be treated as named parameters, which is most likely what you want:

```
my $q = URI::Query.new;

# Prefer this
$q.query-form('foo' => 1, 'bar' => 2, 'foo' => 3);

# Avoid these
$q.query-form(foo => 1, bar => 2, foo => 3);
$q.query-form(:foo(1), :bar(2), :foo(3));

```

The latter two will result in the first "foo" pair being lost. Named parameters assume unique names and the latter "foo" key will effectively override the former.

That said, the method will allow hashes to be passed in, if that is your preference.

### method of

```
method of()

```

Always returns `Pair`.

### method iterator

```
method iterator(Query:D:--> Iterator:D)

```

Returns the iterator on the internal array of `Pair`s.

### method postcircumflex:<[ ]>

```
method postcircumflex:<[ ]> returns Pair

```

This permits positional access to each `Pair` stored internally. You may use this to get a `Pair`, set a `Pair`, test for existence, or delete.

### method postcircumflex:<{ }>

```
method AT-KEY(key)

```

This permits associative access to the values stored internally by key. What is returned here when fetching values depends on the setting in `hash-format`, a list of one or more values or `Nil`, by default. You can use this for getting, setting, existence testing, or deletion.

### method keys

```
method keys(Query:D:--> Seq:D)

```

This method returns all the keys of the query in order.

### method values

```
method values(Query:D:--> Seq:D)

```

This method returns all the values of the query in order.

### method kv

```
method kv(Query:D:--> Seq:D)

```

This method returns a sequence alternating the keys and values of the query in order.

### method pairs

```
method kv(Query:D:--> Seq:D)

```

This method returns a copy of the internal representation of the query string array.

### method pop

```
method pop(Query:D:--> Pair)

```

This method removes the last `Pair` from the array of pairs and returns it.

### method push

```
method push(Query:D: *@new)

```

This method adds the given pairs to the end of the array of pairs in the query using `push` semantics.

### method append

```
method append(Query:D: *@new)

```

This method adds the given pairs to the end of the array of pairs in the query using `append` semantics.

### method shift

```
method shift(Query:D:--> Pair)

```

This method removes the first `Pair` from the array of pairs and returns it.

### method unshift

```
method unshift(Query:D: *@new)

```

This method adds the given pairs to the front of the array of pairs in the query using `unshift` semantics.

### method prepend

```
method prepend(Query:D: *@new)

```

This method adds the given pairs to the front of the array of pairs in the query using `prepend` semantics.

### method splice

```
method splice(Query:D: $start, $elems?, *@replacement)

```

This method removes a `$elems` number of pairs from the array of pairs in the query starting at index `$start`. It then inserts the pairs in `@replacement` into that part of the array (if any are given).

### method elems

```
method elems(Query:D:--> Int:D)

```

Returns the number of pairs stored in the query.

### method end

```
method end(Query:D:--> Int:D)

```

Returns the index of the last pair stored in the query.

### method Bool

```
method Bool(Query:D:--> Bool:D)

```

Returns `True` if the at least one pair is stored in the query or `False` otherwise.

### method Int

```
method Int(Query:D:--> Int:D)

```

Returns `elems`.

### method Numeric

```
method Numeric(Query:D:--> Int:D)

```

Returns `elems`.

### method gist

```
method gist(Query:D:--> Str:D)

```

Returns the `query`.

### method Str

```
method Str(Query:D:--> Str:D)

```

Returns the `query`.

# EXCEPTIONS

## X::URI::Invalid

This exception is thrown in many places where the URI is being parsed or manipulated. If the string being parsed is not a valid URI or if certain manipulations of the URI object would cause it to become an invalid URI, this exception may be used.

It provides a `source` accessor, which returns the string that was determined to be invalid.

## X::URI::Path::Invalid

In some cases where an attempt is made to set `path` to an invalid value, this exception is thrown.

The `source` field will name the invalid URI. Strictly speaking, the URI might be valid, but will not parse the same way as given. To make it clear that this is the case, the `path` field names the invalid path part.

In cases where the segments have been modified in an invalid way, the first invalid segment will be set in `bad-segment`.

# POTENTIALLY INCOMPATIBLE CHANGES BETWEEN v0.2.2 and v0.3.0

The v0.3.0 introduced the ability to mutate the parts of an existing URI, which in turn may have introduced changes which are incompatible with existing applications:

* URI.query now returns an object of type URI::Query not a Str The object will coerce correctly when interpolated into a string but will need an explicit .Str coercion if being assigned to a Str typed variable.
* URI.path now returns an object of type URI::Path not a Str The object will coerce correctly when interpolated into a string but will need an explicit .Str coercion if being assigned to a Str typed variable.
* URI.query-form no longer returns a Hash but an object of URI::Query The object does the Associative role so for the most part can be treated like a Hash but an explicit .Hash coercion may be required when comparing with another Hash or when merging with another Hash. Some uses of query-form have been marked as deprecated and should use .query instead.

The changes have been tested with the majority of modules that depend on URI and only a few required changes.

# AUTHORS

Contributors to this module include:

* Ronald Schmidt (ronaldxs)
* Moritz Lentz (moritz)
* Nick Logan (ugexe)
* Tobias Leich (FROGGS)
* Jonathan Stowe (jonathanstowe)
* Justin DeVuyst (jdv)
* Solomon Foster (colomon)
* Roman Baumer (rba)
* Zoffix Znet (zoffixznet)
* Ahmad M. Zawawi (azawawi)
* Gabor Szabo (szabgab)
* Samantha McVey (samcv)
* Pawel Pabian (bbkr)
* Rob Hoelz (hoelzro)
* radiak
* Paul Cochrane (paultcochrane)
* Steve Mynott (stmuk)
* timo
* David Warring (dwarring)
* Sterling Hanenkamp (zostay)

Source can be located at: <https://github.com/raku-community-modules/URI> . Comments and Pull Requests are welcome.

# COPYRIGHT & LICENSE

Copyright 2017 Ronald Schmidt.

Copyright 2015 - 2024 Raku Community Authors

This software is licensed under the Artistic 2.0 License.


## dist_cpan-JMASLAK-TCP-LowLevel.md
[![Build Status](https://travis-ci.org/jmaslak/Raku-TCP-LowLevel.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-TCP-LowLevel)

# NAME

TCP::LowLevel - Raku bindings for NativeCall TCP on Linux w/ Non-NativeCall Fallback`

# SYNOPSIS

## SERVER

```
use TCP::LowLevel;

react {
  my $server = TCP::LowLevel.new;
  $server-tcp.listen;
  whenever $server-tcp.acceptor -> $conn {
    whenever $conn.Supply -> $msg {
      say "Received: $msg";
    }
  }

  say "Listening on port: " ~ $server.socket-port.result;
}

```

## CLIENT

```
use TCP::LowLevel;

react {
  my $client = TCP::LowLevel.new;
  my $conn   = $client.connect('127.0.0.1', 12345).result;

  $conn.print("Hello!");

  whenever $conn.Supply -> $msg{
    say "Received: $msg";
  }
}

```

# DESCRIPTION

On Linux, this module utilizes NativeCall to use the low level socket library in an asyncronous way. This allows enhanced functionality, such as the use of the MD5 authentication header option (see internet RFC 2385). When not using Linux, this module is essentially a factory for the built-in asyncronous network libraries, although functionality such as MD5 authentication headers is not available in this mode.

# WARNING

This module may experience some interface changes as I determine the best possible interface. I will however try to keep the existing public interface working as documented in this documentation.

# ATTRIBUTES

## my-host

```
my $server = TCP::LowLevel.new(:my-host('127.0.0.1'));

```

This is the source IP used to create the socket. It defaults to 0.0.0.0, which represents all IPv4 addresses on the system. You can set this to `::` if your host supports IPv6, to allow listenig on both IPv4 and IPv6 addresses.

Setting the value of this attribute is only supported at consturction time as an argument to the constructor.

## my-port

```
my $server = TCP::LowLevel.new(:my-port(55666));

```

This is the source port used to create the socket. It defaults to 0, meaning to assign a random source port. This is usually set if you desire to create a listening socket on a static port number.

Setting the value of this attribute is only supported at consturction time as an argument to the constructor.

## socket-port

```
my $port = $server.socket-port.result;

```

This contains a promise that is kept when the source port being actively used is known. This is useful when listening on a random port, to determine what port was selected. Note that this value will not necessaril be the same as the value of `my-port`, as `my-port` may be zero, while this will never return zero.

This value is not settable by the user.

## sock

This contains the socket object belonging to a current connection. It is not anticipated that this would be used directly.

# METHODS

## listen

```
$server.listen;

```

This creates a listening socket on the address specified by `my-host` and the port specified by `my-port`.

## acceptor

```
whenever $server.acceptor -> $conn { … }

```

This, when executed on a listening socket (one which you previously had called `listen()` on) will create a supply of connections, with a new connection emitted for every new connection.

## connect

```
my $conn = $client.connect('127.0.0.1', 8888).result;

```

Creates a TCP connection to the destination address and port provided. This returns a promise that when kept will contain the actual connection object.

## close

```
$server.close;

```

Closes a listening socket.

## add-md5($host, $key)

```
my $server = TCP::LowLevel.new;
$client-tcp.add-md5('127.0.0.1', $key);
$server-tcp.listen;

```

On Linux systems, this module supports RFC 2385 MD5 TCP authentication, which is often used for BGP connections.

It takes two parameters, the host that the MD5 key applies to and the actual key.

This can be used on inbound or outbound connections.

This will throw an exception if MD5 is not supported on the platform.

## supports-md5

```
die("No MD5 support") unless TCP::LowLevel.supports-md5;

```

Returns `True` if MD5 authentication is supported on the platform, `False` otherwise.

# USING CONNECTION OBJECTS

The objects returned by the `acceptor` Supply or the `connect()` Promise may be Raku native objects or the wrapper around the Linux networking libraries.

## METHODS

### Supply(:$bin?)

```
whenever $conn.Supply(:bin) -> $msg { … }

```

This returns a supply that emits received messages. If `:bin` is `True`, the messages are returned as `buf8` objects, othrwise they are returned as `Str` objects.

### print($msg)

```
$conn.print("Hello world!\n");

```

This sends a `Str` across the TCP session.

### write($msg)

```
$conn.write($msg)

```

This sends a `buf8` across the TCP session.

# AUTHOR

Joelle Maslak [jmaslak@antelope.net](mailto:jmaslak@antelope.net)

# COPYRIGHT AND LICENSE

Copyright © 2018-2019 Joelle Maslak

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-thundergnat-X11-libxdo.md
# NAME

X11::libxdo

Version: 0.1.2

Raku bindings to the [libxdo X11 automation library](https://github.com/jordansissel/xdotool).

Note: This is a WORK IN PROGRESS. The tests are under construction and some may not work on your computer. Several functions are not yet implemented, but a large core group is.

Many of the test files do not actally run tests that can be checked for correctness. (Many of the object move & resize tests for example.) Rather, they attempt to perform an action and fail/pass based on if the attempt does or doesn't produce an error.

Not all libxdo functions are supported by every window manager. In general, mouse info & move and window info, move, & resize routines seem to be well supported, others... not so much.

# SYNOPSIS

```
use X11::libxdo;

my $xdo = Xdo.new;

say 'Version: ', $xdo.version;

say 'Active window id: ', my $active = $xdo.get-active-window;

say 'Active window title: ', $xdo.get-window-name($active);

say "Pause for a bit...";
sleep 4; # pause for a bit

loop {
    my ($x, $y, $window-id, $screen) = $xdo.get-mouse-info;
    my $name = (try $xdo.get-window-name($window-id) if $window-id)
       // 'No name set';

    my $line = "Mouse location: $x, $y, Window under mouse - ID: " ~
       $window-id ~ ', Name: ' ~ $name ~ ", Screen #: $screen";

    print "\e[H\e[JMove mouse around screen; move to top to exit.\n", $line;

    # exit if pointer moved to top of screen
    say '' and last if $y < 1;

    # update periodically.
    sleep .05;
}

```

# DESCRIPTION

Raku bindings to the [libxdo X11 automation library](https://github.com/jordansissel/xdotool).

Requires that libxdo-dev library is installed and accessible.

| Platform | Install Method |
| --- | --- |
| Debian and Ubuntu | [sudo] apt-get install libxdo-dev |
| FreeBSD | [sudo] pkg install libxdo-dev |
| Fedora | [sudo] dnf install libxdo-dev |
| OSX | [sudo] brew install libxdo-dev |
| OpenSUSE | [sudo] zypper install libxdo-dev |
| Source Code on GitHub | https://github.com/jordansissel/xdotool/releases |

Many (most?) of the xdo methods take a window ID # in their parameters. This is an integer ID# and MUST be passed as an unsigned Int. In general, to act on the currently active window, set the window ID to 0 or just leave blank.

Note that many of the methods will require a small delay for them to finish before moving on to the next, especially when performing several actions in a row. Either do a short sleep or a .activate-window($window-ID) to give the action time to complete before moving on to the next action.

There are several broad categories of methods available.

* Misc
* Mouse
* Window
* Keystrokes
* Desktop

## Miscellaneous

```
.version()

```

Get the library version.

Takes no parameters.

Returns the version string of the current libxdo library.

--

```
.get_symbol_map()

```

Get modifier symbol pairs.

Takes no parameters.

Returns an array of modifier symbol pairs.

--

```
.search(%query)

```

Reimplementation of the libxdo search function to give greater flexibility under Raku.

May seach for a name, class, ID or pid or any combination, against a string / regex.

```
.search( :name(), :class(), :ID(), :pid() )

```

Search for an open window where the title contains the exact string 'libxdo':

```
.search( :name('libxdo') )

```

Search for an open window where the title contains 'Raku' case insensitvely:

```
.search( :name(rx:i['raku']) )

```

Returns a hash { :name(), :class(), :ID(), :pid() } pairs of the first match found for one of the search parameters.

if you need more granularity or control over the search, use get-windows to get a hash of all of the visible windows and search through them manually.

--

```
.get-windows()

```

Takes no parameters.

Returns a hoh of all of the visible windows keyed on the ID number with value of a hash of { :name(), :class(), :ID(), :pid() } pairs.

## Mouse

```
.move-mouse( $x, $y, $screen )

```

Move the mouse to a specific location.

Takes three parameters:

* int $x: the target X coordinate on the screen in pixels.
* int $y: the target Y coordinate on the screen in pixels.
* int $screen the screen (number) you want to move on.

Returns 0 on success !0 on failure.

--

```
.move-mouse-relative( $delta-x, $delta-y )

```

Move the mouse relative to it's current position.

Takes two parameters:

* int $delta-x: the distance in pixels to move on the X axis.
* int $delta-y: the distance in pixels to move on the Y axis.

Returns 0 on success !0 on failure.

--

```
.move-mouse-relative-to-window( $x, $y, $window )

```

Move the mouse to a specific location relative to the top-left corner of a window.

Takes three parameters:

* int $x: the target X coordinate on the screen in pixels.
* int $y: the target Y coordinate on the screen in pixels.
* Window $window: ID of the window.

Returns 0 on success !0 on failure.

--

```
.get-mouse-location()

```

Get the current mouse location (coordinates and screen ID number).

Takes no parameters;

Returns three integers:

* int $x: the x coordinate of the mouse pointer.
* int $y: the y coordinate of the mouse pointer.
* int $screen: the index number of the screen the mouse pointer is located on.

--

```
.get-mouse-info()

```

Get all mouse location-related data.

Takes no parameters;

Returns four integers:

* int $x: the x coordinate of the mouse pointer.
* int $y: the y coordinate of the mouse pointer.
* Window $window: the ID number of the window the mouse pointer is located on.
* int $screen: the index number of the screen the mouse pointer is located on.

--

```
.wait-for-mouse-to-move-from( $origin-x, $origin-y )

```

Wait for the mouse to move from a location. This function will block until the condition has been satisfied.

Takes two integer parameters:

* int $origin-x: the X position you expect the mouse to move from.
* int $origin-y: the Y position you expect the mouse to move from.

Returns nothing.

--

```
.wait-for-mouse-to-move-to( $dest-x, $dest-y )

```

Wait for the mouse to move to a location. This function will block until the condition has been satisfied.

Takes two integer parameters:

* int $dest-x: the X position you expect the mouse to move to.
* int $dest-y: the Y position you expect the mouse to move to.

Returns nothing.

--

```
.mouse-button-down( $window, $button )

```

Send a mouse press (aka mouse down) for a given button at the current mouse location.

Takes two parameters:

* Window $window: The ID# of the window receiving the event. 0 for the current window.
* int $button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down.

Returns nothing.

--

```
.mouse-button-up( $window, $button )

```

Send a mouse release (aka mouse up) for a given button at the current mouse location.

Takes two parameters:

* Window $window: The ID# of the window receiving the event. 0 for the current window.
* int $button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down.

Returns nothing.

--

```
.mouse-button-click( $window, $button )

```

Send a click for a specific mouse button at the current mouse location.

Takes two parameters:

* Window $window: The ID# of the window receiving the event. 0 for the current window.
* int $button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down.

Returns nothing.

--

```
.mouse-button-multiple( $window, $button, $repeat = 2, $delay? )

```

Send a one or more clicks of a specific mouse button at the current mouse location.

Takes three parameters:

* Window $window: The ID# of the window receiving the event. 0 for the current window.
* int $button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down.
* int $repeat: (optional, defaults to 2) number of times to click the button.
* int $delay: (optional, defaults to 8000) useconds delay between clicks. 8000 is a reasonable default.

Returns nothing.

--

```
.get-window-under-mouse()

```

Get the window the mouse is currently over

Takes no parameters.

Returns the ID of the topmost window under the mouse.

## Window

```
.get-active-window()

```

Get the currently-active window. Requires your window manager to support this.

Takes no parameters.

Returns one integer:

* $screen: Window ID of active window.

--

```
.select-window-with-mouse()

```

Get a window ID by clicking on it. This function blocks until a selection is made.

Takes no parameters.

Returns one integer:

* $screen: Window ID of active window.

--

```
.get-window-location( $window?, $scrn? )

```

Get a window's location.

Takes two optional parameters:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.
* int $screen: Optional parameter screen ID. If none supplied, uses active screen ID.

Returns three integers:

* $x: x coordinate of top left corner of window.
* $y: y coordinate of top left corner of window.
* $screen index of screen the window is located on.

--

```
.get-window-size( $window? )

```

Get a window's size.

Takes one optional parameter:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.

Returns two integers:

* int $width the width of the queried window in pixels.
* int $height the height of the queried window in pixels.

--

```
.get-window-geometry( $window? )

```

Get a windows geometry string.

Takes one optional parameter:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.

Returns standard geometry string

* Str $geometry "{$width}x{$height}+{$x}+{$y}" format

400x200+250+450 means a 400 pixel wide by 200 pixel high window with the top left corner at 250 x position 450 y position.

--

```
.get-window-name( $window? )

```

Get a window's name, if any.

Takes one optional parameter:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.

Returns one string:

* Str $name Name of the queried window.

--

```
.get-window-pid( $window )

```

Get the PID or the process owning a window. Not all applications support this. It looks at the \_NET\_WM\_PID property of the window.

Takes one parameter:

* Window $window: Window ID.

Returns one integer:

* int $pid process id, or 0 if no pid found.

--

```
.set-window-size( $window, $width, $height, $flags? = 0 )

```

Set the window size.

Takes four parameters:

* Window $window: the ID of the window to resize.
* int $width: the new desired width.
* int $height: the new desired height
* int $flags: Optional, if 0, use pixels for units. Otherwise the units will be relative to the window size hints.

HINTS:

* 0 size window in pixels
* 1 size X dimension relative to character block width
* 2 size Y dimension relative to character block height
* 3 size both dimensions relative to character block size

Returns 0 on success !0 on failure.

--

```
.focus-window( $window )

```

Set the focus on a window.

Takes one parameter:

* Window $window: ID of window to focus on.

Returns 0 on success !0 on failure.

--

```
.get-focused-window( )

```

Get the ID of the window currently having focus.

Takes no parameters:

Returns one parameter:

* Window $window: ID of window currently having focus.

--

```
.activate-window( $window )

```

Activate a window. This is generally a better choice than .focus\_window for a variety of reasons, but it requires window manager support.

* If the window is on another desktop, that desktop is switched to.
* It moves the window forward rather than simply focusing it

Takes one parameter:

* Window $window: Window ID.

Returns 0 on success !0 on failure.

--

```
.raise-window( $window )

```

Raise a window to the top of the window stack. This is also sometimes termed as bringing the window forward.

Takes one parameter:

* Window $window: Window ID.

Returns 0 on success !0 on failure.

--

```
.minimize( $window )

```

Minimize a window.

Takes one parameter:

* Window $window: Window ID.

Returns 0 on success !0 on failure.

--

```
.map-window( $window )

```

Map a window. This mostly means to make the window visible if it is not currently mapped.

Takes one parameter:

* Window $window: Window ID.

Returns 0 on success !0 on failure.

--

```
.unmap-window( $window )

```

Unmap a window. This means to make the window invisible and possibly remove it from the task bar on some WMs.

Takes one parameter:

* Window $window: Window ID.

Returns 0 on success !0 on failure.

--

```
.move-window( $window )

```

Move a window to a specific location.

The top left corner of the window will be moved to the x,y coordinate.

Takes three parameters:

* Window $window: Window ID of the window to move.
* int $x : the X coordinate to move to.
* int $y: the Y coordinate to move to.

Returns 0 on success !0 on failure.

--

```
.wait_for_window_active( $window )

```

Wait for a window to be active or not active. Requires your window manager to support this. Uses \_NET\_ACTIVE\_WINDOW from the EWMH spec.

Takes one parameter:

* Window $window: Window ID. If none supplied, uses active window ID.

Returns 0 on success !0 on failure.

--

```
.close-window( $window )

```

TODO not working under Cinnamon?

Close a window without trying to kill the client.

Takes one parameter:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.

Returns 0 on success !0 on failure.

--

```
.kill-window( $window )

```

TODO not working under Cinnamon?

Kill a window and the client owning it.

Takes one parameter:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.

Returns 0 on success !0 on failure.

--

```
.override-redirect( $window, $value )

```

TODO not working under Cinnamon?

Set the override\_redirect value for a window. This generally means whether or not a window manager will manage this window.

Takes two parameters:

* Window $window: Optional parameter window ID. If none supplied, uses active window ID.
* int $value: If you set it to 1, the window manager will usually not draw borders on the window, etc. If you set it to 0, the window manager will see it like a normal application window.

Returns 0 on success !0 on failure.

--

```
.wait-for-window-map-state( $window, $state )

```

Wait for a window to have a specific map state.

State possibilities:

* 0 IsUnmapped - window is not displayed.
* 1 IsViewable - window is mapped and shown (though may be clipped by windows on top of it)
* 2 IsUnviewable - window is mapped but a parent window is unmapped.

Takes two parameters:

* Window $window: Window ID, the window you want to wait for.
* int map\_state: the state to wait for.

--

```
.set-window-state( $window, $action, $property)

```

Change window state

Takes three parameters:

* Window $window: Window ID, the window you want to act on.
* ulong $action: the \_NET\_WM\_STATE action
* str $property: the property to change

--

```
ACTIONS:
_NET_WM_STATE_REMOVE: 0 -  remove/unset property
_NET_WM_STATE_ADD:    1 -  add/set property
_NET_WM_STATE_TOGGLE: 2 -  toggle property

SOME POSSIBLE PROPERTIES:
_NET_WM_STATE_MAXIMIZED_VERT
_NET_WM_STATE_MAXIMIZED_HORZ
_NET_WM_STATE_SHADED
_NET_WM_STATE_HIDDEN
_NET_WM_STATE_FULLSCREEN
_NET_WM_STATE_ABOVE
_NET_WM_STATE_BELOW

```

Retuns 0 on sucess, !0 on failure

## Keystrokes

```
.type( $window, $string, $delay? )

```

Type a string to the specified window.

If you want to send a specific key or key sequence, such as "alt+l", you want instead send-sequence(...).

Not well supported under many window managers or by many applications unfortunately. Somewhat of a crapshoot as to which applications pay attention to this function. Web browsers tend to; (Firefox and Chrome tested), many other applications do not. Need to try it to see if it will work in your situation.

Takes three parameters:

* int $window: The window you want to send keystrokes to or 0 for the current window.
* string $string: The string to type, like "Hello world!"
* int $delay: Optional delay between keystrokes in microseconds. 12000 is a decent choice if you don't have other plans.

Returns 0 on success !0 on failure.

--

```
.send-sequence( $window, $string, $delay? )

```

This allows you to send keysequences by symbol name. Any combination of X11 KeySym names separated by '+' are valid. Single KeySym names are valid, too.

Examples: "l" "semicolon" "alt+Return" "Alt\_L+Tab"

Takes three parameters:

* int $window: The window you want to send keystrokes to or 0 for the current window.
* string $string: The string keysequence to send.
* int $delay: Optional delay between keystrokes in microseconds. 12000 is a decent choice if you don't have other plans.

Returns 0 on success !0 on failure.

--

```
.send-key-press( $window, $string, $delay? )

```

Send key press (down) events for the given key sequence.

See send-sequence

Takes three parameters:

* int $window: The window you want to send keystrokes to or 0 for the current window.
* string $string: The string keysequence to send.
* int $delay: Optional delay between key down events in microseconds.

Returns 0 on success !0 on failure.

--

```
.send-key-release( $window, $string, $delay? )

```

Send key release (up) events for the given key sequence.

See send-sequence

Takes three parameters:

* int $window: The window you want to send keystrokes to or 0 for the current window.
* string $string: The string keysequence to send.
* int $delay: Optional delay between key down events in microseconds.

Returns 0 on success !0 on failure.

## Desktop

```
.get-desktop-dimensions( $screen? )

```

Query the viewport (your display) dimensions

If Xinerama is active and supported, that api internally is used. If Xinerama is disabled, will report the root window's dimensions for the given screen.

Takes one parameter:

* int $screen: Optional parameter screen index. If none supplied, uses default 0.

Returns three integers:

* $x: x dimension of the desktop window.
* $y: y dimension of the desktop window.
* $screen index of screen for which the dimensions are reported.

--

```
.set-number-of-desktops($number)

```

Set the number of desktops. Uses \_NET\_NUMBER\_OF\_DESKTOPS of the EWMH spec.

Takes one parameter:

* $ndesktops: the new number of desktops to set.

Returns 0 on success, !0 on failure

--

```
.get-number-of-desktops()

```

Get the current number of desktops. Uses \_NET\_NUMBER\_OF\_DESKTOPS of the EWMH spec.

Takes no parameters:

Returns one integer:

* $number: the current number of desktops (workspaces).

--

```
.set-current-desktop($number)

```

Switch to another desktop. Uses \_NET\_CURRENT\_DESKTOP of the EWMH spec.

Takes one parameter:

* int $number The desktop number to switch to.

--

```
.get-current-desktop()

```

Get the current desktop. Uses \_NET\_CURRENT\_DESKTOP of the EWMH spec.

Takes no parmeters:

Returns one integer:

* int $number The index number of the current desktop (workspace).

--

```
.move-window-to-desktop($window, $number)

```

Move a window to another desktop. Uses \_NET\_WM\_DESKTOP of the EWMH spec.

Takes two parameters:

* Window $window: ID of the window to move
* int $desktop: the desktop destination for the window

Returns 0 on success, !0 on failure

--

```
.get-desktop-for-window($window)

```

Get the desktop a window is on. Uses \_NET\_WM\_DESKTOP of the EWMH spec.

If your desktop does not support \_NET\_WM\_DESKTOP ruturns Nil.

Takes one parameter:

* Window $window: ID of the window to query.

Returns one integer:

* int $desktop: the desktop where the window is located.

--

```
.get-desktop-viewport()

```

Get the position of the current viewport.

This is only relevant if your window manager supports \_NET\_DESKTOP\_VIEWPORT

Takes no parameters:

Returns two values:

* int $x: the X value of the top left corner of the viewport.
* int $y: the Y value of the top left corner of the viewport.

--

```
.set-desktop-viewport($x, $y)

```

Set the position of the current viewport.

This is only relevant if your window manager supports \_NET\_DESKTOP\_VIEWPORT

Takes two parameters:

* int $x: the X value of the top left corner of the viewport.
* int $y: the Y value of the top left corner of the viewport.

# AUTHOR

2018 Steve Schulze aka thundergnat

This package is free software and is provided "as is" without express or implied warranty. You can redistribute it and/or modify it under the same terms as Perl itself.

# LICENSE

Licensed under The Artistic 2.0; see LICENSE.


## dist_zef-bduggan-LLM-DWIM.md
[![Actions Status](https://github.com/bduggan/raku-llm-dwim/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/raku-llm-dwim/actions/workflows/linux.yml)
[![Actions Status](https://github.com/bduggan/raku-llm-dwim/actions/workflows/macos.yml/badge.svg)](https://github.com/bduggan/raku-llm-dwim/actions/workflows/macos.yml)

# NAME

LLM::DWIM -- Do What I Mean, with help from large language models.

# SYNOPSIS

```
use LLM::DWIM;

say dwim "How many miles is it from the earth to the moon?";
# Approximately 238,900 miles (384,400 kilometers)

say dwim "@NothingElse How many miles is it from the earth to the moon? #NumericOnly";
# 238900

sub distance-between($from,$to) {
  dwim "@NothingElse #NumericOnly What is the distance in miles between $from and $to?";
}

say distance-between("earth","sun");
# 92955887.6 miles

my $agent = dwim-chat("Answer every question with an exclamation point!");
say $agent.eval: "My name is bob and I have five dogs.";
# That's great!

say $agent.eval: "How many paws is that?";
# Twenty!

```

Meanwhile, in ~/.config/llm-dwim.toml:

```
evaluator = "gemini"
gemini.temperature = 0.5

```

# DESCRIPTION

This is a simple wrapper around [LLM::Functions](https://raku.land/zef:antononcube/LLM::Functions), and [LLM::Prompts](https://raku.land/zef:antononcube/LLM::Prompts) It provides a single subroutine, `dwim`, that sends a string to an LLM evaluator, making use of a configuration file to say a little more about what you mean.

# FUNCTIONS

## dwim

```
sub dwim(Str $str) returns Str

```

This function takes a string, expands it using LLM::Prompts, and uses LLM::Functions to evaluate the string.

## dwim-chat

```
sub dwim-chat(Str $prompt) returns Str

```

Create a chat agent that will have a conversation.

For diagnostics, use [Log::Async](https://raku.land/cpan:BDUGGAN/Log::Async) and add a tap, like so:

```
use LLM::DWIM;
use Log::Async;

logger.send-to($*ERR);

say dwim "How many miles is it from earth is the moon? #NumericOnly";

```

# CONFIGURATION

This module looks for `llm-dwim.toml` in either `XDG_HOME` or `HOME/.config`. This can be overridden by setting `DWIM_LLM_CONF` to another filename.

The configuration file should be in TOML format and should contain at least one key, `evaluator`, which should be the name of the LLM evaluator to use. Evaluators can be configured using TOML syntax, with the evaluator name as the key.

Sample configurations:

Use Gemini (which has a free tier) :

```
evaluator = "gemini"

```

Use OpenAI, and modify some parameters:

```
evaluator = "OpenAI"
OpenAI.temperature = 0.9
OpenAI.max-tokens = 100

```

See [LLM::Functions](https://raku.land/zef:antononcube/LLM::Functions) for all of the configuration options.

# COMMAND LINE USAGE

This package has two scripts:

First, `llm-dwim` can be used to evaluate a string from the command line.

Sample usage:

```
llm-dwim -h  # get usage
llm-dwim "How many miles is it from the earth to the moon?"
llm-dwim -v how far is it from the earth to the moon\?
echo "what is the airspeed velocity of an unladen swallow?" | llm-dwim -

```

Second, `llm-dwim-chat` will have a chat with you.

Sample session:

```
llm-dwim-chat you are a french tutor --name=Professor

you > Hello
Professor > Bonjour !  Comment allez-vous ?
you > Bien merci
Professor > Et vous ?  (And you?)
you >

```

# SEE ALSO

[LLM::Functions](https://raku.land/zef:antononcube/LLM::Functions), [LLM::Prompts](https://raku.land/zef:antononcube/LLM::Prompts)

This was inspired by the also excellent [DWIM::Block](https://metacpan.org/pod/DWIM::Block) module.

# AUTHOR

Brian Duggan


## submethod.md
class Submethod

Member function that is not inherited by subclasses

```raku
class Submethod is Routine {}
```

A Submethod is a method that is not inherited by child classes. They are typically used for per-class initialization and tear-down tasks which are called explicitly per class in an inheritance tree, usually for enforcing a particular order. For example object construction with the `BUILD` submethod happens from the least-derived to most-derived, so that the most-derived (child) classes can depend on the parent already being initialized.

Submethods are of type `Submethod`, and are declared with the `submethod` declarator:

```raku
class Area {
    has $.size;
    submethod BUILD(:$x, :$y, :$z) {
        $!size = $x * $y * $z;
    }
}
```

Since submethods are not inherited, an interesting use case is precisely methods that are going to be called from the *standard* submethods such as `BUILD` or `TWEAK`.

```raku
class Hero {
    has @.inventory;
    has Str $.name;
    submethod BUILD( :$!name, :@!inventory ) {
        @!inventory = self.clean-inventory( @!inventory );
    }
    submethod clean-inventory( @inventory ) {
        @!inventory.unique.sort
    }
}

my Hero $þor .= new( name => "Þor",
                     inventory => ( "Mjölnir", "Megingjörð", "Mjölnir" ) );
say $þor.inventory;
# OUTPUT: «[Megingjörð Mjölnir]␤»

```

Invoking these methods make sense only in the specific context of the submethod it is invoked from.

# [Methods](#class_Submethod "go to top of document")[§](#Methods "direct link")

## [method gist](#class_Submethod "go to top of document")[§](#method_gist "direct link")

```raku
multi method gist(Submethod:D:)
```

Returns the name of the submethod.

# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")

Type relations for `Submethod`

raku-type-graph

Submethod
Submethod

Routine
Routine

Submethod->Routine

Mu
Mu

Any
Any

Any->Mu

Callable
Callable

Code
Code

Code->Any

Code->Callable

Block
Block

Block->Code

Routine->Block

[Expand chart above](/assets/typegraphs/Submethod.svg)


## dist_zef-raku-community-modules-IO-Path-ChildSecure.md
[![Actions Status](https://github.com/raku-community-modules/IO-Path-ChildSecure/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/IO-Path-ChildSecure/actions)

# NAME

IO::Path::ChildSecure - Secure version of IO::Path.child

# SYNOPSIS

```
use IO::Path::ChildSecure;

# good; you get IO::Path
"foo".IO.&child-secure: 'meow';

# still good if 'foo/meow/foo/bar/../' exists; Failure if it doesn't
"foo".IO.&child-secure: 'meow/foo/bar/../meow';

# bad; path isn't a child; you get Failure
"foo".IO.&child-secure: '../';

```

# DESCRIPTION

In the Raku Programming Language, [IO::Path.child](https://docs.raku.org/type/IO::Path#method_child) isn't secure, in a sense that it does no checks for whether the resultant path is actually a child of the original path.

This module provides a subroutine that can be used as an alternative that **will** check whether the resultant path is a child of the original path.

# EXPORTED SUBROUTINES

## child-secure

```
"foo".IO.&child-secure: 'meow'; # good; you get IO::Path
"foo".IO.&child-secure: 'meow/foo/bar/../meow'; # still good
"foo".IO.&child-secure: '../';  # bad; path isn't a child; you get Failure

child-secure "foo".IO, '../';  # can also use as a proper sub

```

Appends the given path chunk to the invocant and ensures the resultant path is, in fact, a child of the invocant, by accessing the filesystem and fully-resolving the path. The last chunk of the resultant path does not have to exist for the resolution to succeed.

Will [fail](https://docs.raku.org/routine/fail) with `X::IO::Resolve` if failed to fully resolve the resultant path or with `X::IO::NotAChild` if the resultant path is not a child of the invocant.

# SPECIAL NOTES

If you don't need to ensure secureness, use the much-faster core [`IO::Path.add` method](https://docs.raku.org/type/IO::Path#method_add)

# AUTHOR

Zoffix Znet

# COPYRIGHT AND LICENSE

Copyright 2017-2018 Zoffix Znet

Copyright 2019-2022 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-lizmat-Sequence-Generator.md
[![Actions Status](https://github.com/lizmat/Sequence-Generator/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Sequence-Generator/actions) [![Actions Status](https://github.com/lizmat/Sequence-Generator/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Sequence-Generator/actions) [![Actions Status](https://github.com/lizmat/Sequence-Generator/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Sequence-Generator/actions)

# NAME

Sequence::Generator - generate sequences of values from endpoints

# SYNOPSIS

```
use Sequence::Generator;

say 1,2,4 ... 64; # (1 2 4 8 16 32 64)

```

# DESCRIPTION

Raku provides a `...` operator (and its friends `...^`, `^...` and `^...^`) to generate values from a given set of endpoints. It is one of the oldest parts of the Raku Programming Language.

During its development, it obtained some quirks and behaviours that are now considered too magical, or considered to be a bug (which is sometimes actually frozen into spectests). On top of that, the development of the `...` operator preceded the occurrence of the `Iterator` role, so it actually does not use any of its benefits.

This module started out as an attempt to make the `...` operator (and friends) much faster by re-implementing it using `Iterator`s, rather than `gather` / `take`. However, it became clear that fixing behaviour considered too magical or buggy, could break existing Raku code. It was therefore decided to turn this work into this module, with the option of incorporating it into a later language version of Raku.

This module is between 4x and 20x faster than the Raku 6.d implementation.

# RULES

This describes the rules that are being applied to the begin and end points of these generated sequences.

## Meaning of carets

The carets `^` on the infix `...` operator are interpreted in a very strict way. On the left-hand side (`^...`) it means that the **initial** value will **not** be produced. On the right-hand side it means that the final value will **not** be produced.

## Two Real numbers

If the end point is larger than the begin point, then the functionality is the same as the `..` infix operator: add **1** for each step until the value is larger than the end point value.

```
say 1 ... 10;    # (1 2 3 4 5 6 7 8 9 10)
say 1.5 ... 10;  # (1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5)

```

If the end point is smaller than the begin point, then **-1** is added for each step until the value is smaller than the end point value.

```
say 10 ... 1;   # (10 9 8 7 6 5 4 3 2 1)
say 10.5 ... 1; # (10.5 9.5 8.5 7.5 6.5 5.5 4.5 3.5 2.5 1.5)

```

If you need other increments or decrements, you must either use elucidation or provide a `Callable` that will do the production of values.

## Sequence elucidation

If the left hand side just consists of two or more `Real` numbers, then the last three (or two if there are only two) values will be used to try to determine the type of sequence in a process called "elucidation".

If the difference between the values is constant (or if there are only two values), then the sequence is called to be "arithmetic": the difference will then be assumed to the the step to be applied for each subsequent value produced.

```
say 1, 3 ... 10;     # (1 3 5 7 9)
say 10, 8, 6 ... 1;  # (10 8 6 4 2)

```

If the division between the values is constant, then the sequence is called to the "geometric": that value will then be used to multiply to produce the next value.

```
say 1 2 4 8 16 32 64;  # (1 2 4 8 16 32 64)
say 64, 32, 16 ... 1;  # (64 32 16 8 4 2 1)

```

If elucidation fails, a `Failure` will be returned with as much information possible to indicate the reason of the failure.

## Non-numeric endpoints

If the sequence has a non-numeric end point, then the sequence will continue to produce values until the generated value smartmatches with the end point.

```
say 5, { $_ ?? $_ - 1 !! "liftoff" } ... Str;
# (5 4 3 2 1 0 liftoff)

```

## Two strings

A sequence can only be generated for two strings if they have the same number of characters and all of the characters are either in the range of `a .. z`, `A .. Z` or `0 .. 9`. Furthermore, the range of each character of the begin point needs to be in the same range as the associated end point.

Each character will be incremented / decremented according to its counterpart to generate strings, with the rightmost character being incremented / decremented first.

```
say "ac" ... "ba";  # (ac ab aa bc bb ba)

```

Any other combination of strings will return a `Failure`. If you want some other string based sequence semantics, you should probably be using the magic increment / decrementfunctionality on strings, as offered by the `.succ` and `.pred` methods, and use a `Callable` to produce the values.

```
say ("zy", *.succ ... *).head(8);   # (zy zz aaa aab aac aad aae aaf)

say ("¹²", *.pred ... *).head(20);  # (¹² ¹¹ ¹⁰ ⁰⁹ ⁰⁸ ⁰⁷ ⁰⁶ ⁰⁵ ⁰⁴ ⁰³ ⁰² ⁰¹ ⁰⁰)

```

# BREAKING CHANGES

## Semantics of multiple endpoints

The original implementation of the `...` operator allowed a chain of endpoints to be specified:

```
say 1 ... 5 ... 1; # (1 2 3 4 5 4 3 2 1)

```

This is no longer supported because of the unclear semantics of an endpoint also serving as a starting point as soon as it is anything more than a numeric value. If you would like to have such a sequence, you will have to use parentheses to indicate meaning:

```
say 1 ... (5 ... 1); # (1 2 3 4 5 4 3 2 1)

```

## Strict meaning of ^

The original implementation of the `...^` operator treated omission of endpoints differently for numeric values:

```
say 1 ...^ 5.5; # (1 2 3 4 5)

```

This is generalized to **always** omit the last **generated** value, regardless of whether it actually compared exactly with the endpoint or not.

## Using .pred ends sequence if Failure

The original implementation of the `...` operator would die if `.pred` was being used to generate the next value, and that would return a Failure. This has been changed to ending the sequence.

## No longer silently ignores values on LHS after Callable

The original implementation of the `...` operator would ignore any values **after** a Callable on the LHS, e.g.:

```
1,2,3, * + 1, 7,8,9 ... 100;

```

This now returns a `Failure`.

## No longer silently ignores values with RHS list starting with \*

The original implementation of the `...` operator would ignore any values **after** a Whatever as the first element of a list on the RHS, e.g.:

```
1,2,3 ... *,42,666;

```

This now returns a `Failure`.

## LHS elucidation should always have identical types

This implementation requires all values for sequence elucidation (either 2 elements on the left, or the last three of three or more values) to be either all Real, or of the same type. If they are not, the elucidation will fail. This behaviour makes quite a few edge cases fail that the original implementation of the `...` operator would try to make sense of.

## Elucidation of LHS with identical values now fail

The original implementation of the `...` operator would produce unexplicable results if the 2 or the last 3 values of the LHS list would contain the same values. This will now return `Failure`.

## Multiplication factor must be positive

In elucidation, any multiplication factor found must be positive. Negative multiplication factors are too magic with regards to determine when the sequence must be ended. Please use a WhateverCode (e.g. `* * -1`) to indicate a negative multiplication factor.

# CLASS INTERFACE

The `Sequence::Generator` class can not be instantiated: it merely serves as an entry point to the sequence generating logic. It exposes **one** method:

## iterator

The `iterator` method takes two positional arguments: the seed for the sequence (aka the left-hand side of the `...` infix operator) and the end point (aka the right-hand side of the `...` infix operator). It returns an `Iterator` object.

```
my $iterator = Sequence::Generator.iterator((1,2,4), 64);
say Seq.new($iterator);  # (1 2 4 8 16 32 64)

```

If you like to exclude the first or last generated value, you can pass the `:no-first` and/or the `:no-last` named arguments.

```
my $iterator = Sequence::Generator.iterator((1,2,4), 64, :no-first, :no-last);
say Seq.new($iterator);  # (2 4 8 16 32)

```

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

Source can be located at: <https://github.com/lizmat/Sequence-Generator> . Comments and Pull Requests are welcome.

If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!

# COPYRIGHT AND LICENSE

Copyright 2020, 2024 Elizabeth Mattijsen

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-martimm-Gnome-N.md
![](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png)

# Gnome::N - Native Object and Raku - Gnome Interfacing

![Artistic License 2.0](https://martimm.github.io/label/License-label.svg)

# Description

This package holds the native object descriptions and types as well as the interface description to connect to the Gnome libraries. This set of modules will never act on their own. They will be used by other packages such as `Gnome::Gtk4` and the like.

## Documentation

* [🔗 Website, entry point for all documents and blogs](https://martimm.github.io/)
* [🔗 License document](https://www.perlfoundation.org/artistic_license_2_0)
* [🔗 Release notes of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/blob/main/CHANGES.md)
* [🔗 Issues of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/issues)

# Installation

Do not install this package on its own. Instead install `Gnome::Gtk4` newest api.

`zef install Gnome::Gtk4:api<2>`

# Author

Name: **Marcel Timmerman**
Github account name: **MARTIMM**

# Issues

There are always some problems! If you find one please help by filing an issue at [my github project](https://github.com/MARTIMM/gnome-source-skim-tool/issues).

# Attribution

* The inventors of Raku, formerly known as Perl 6, of course and the writers of the documentation which helped me out every time again and again.
* The builders of all the Gnome libraries and the documentation.
* Other helpful modules for their insight and use.


## atomic-inc-fetch.md
atomic-inc-fetch

Combined from primary sources listed below.

# [In atomicint](#___top "go to top of document")[§](#(atomicint)_sub_atomic-inc-fetch "direct link")

See primary documentation
[in context](/type/atomicint#sub_atomic-inc-fetch)
for **sub atomic-inc-fetch**.

```raku
multi atomic-inc-fetch(atomicint $ is rw)
```

Performs an atomic increment on a native integer. This will be performed using hardware-provided atomic operations. Since the operation is atomic, it is safe to use without acquiring a lock. Returns the value resulting from the increment. Overflow will wrap around silently.